file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// File: openzeppelin-solidity/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.8; /** * @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-solidity/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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-solidity/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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-solidity/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/oracle/ILinearDividendOracle.sol /** * @title ILinearDividendOracle * @notice provides dividend information and calculation strategies for linear dividends. */ interface ILinearDividendOracle { /** * @notice calculate the total dividend accrued since last dividend checkpoint to now * @param tokenAmount amount of token being held * @param timestamp timestamp to start calculating dividend accrued * @param fromIndex index in the dividend history that the timestamp falls into * @return amount of dividend accrued in 1e18, and the latest dividend index */ function calculateAccruedDividends( uint256 tokenAmount, uint256 timestamp, uint256 fromIndex ) external view returns (uint256, uint256); /** * @notice calculate the total dividend accrued since last dividend checkpoint to (inclusive) a given dividend index * @param tokenAmount amount of token being held * @param timestamp timestamp to start calculating dividend accrued * @param fromIndex index in the dividend history that the timestamp falls into * @param toIndex index in the dividend history to stop the calculation at, inclusive * @return amount of dividend accrued in 1e18, dividend index and timestamp to use for remaining dividends */ function calculateAccruedDividendsBounded( uint256 tokenAmount, uint256 timestamp, uint256 fromIndex, uint256 toIndex ) external view returns (uint256, uint256, uint256); /** * @notice get the current dividend index * @return the latest dividend index */ function getCurrentIndex() external view returns (uint256); /** * @notice return the current dividend accrual rate, in USD per second * @return dividend in USD per second */ function getCurrentValue() external view returns (uint256); /** * @notice return the dividend accrual rate, in USD per second, of a given dividend index * @return dividend in USD per second of the corresponding dividend phase. */ function getHistoricalValue(uint256 dividendIndex) external view returns (uint256); } // File: contracts/standardTokens/WrappingERC20WithLinearDividends.sol /** * @title WrappingERC20WithLinearDividends * @dev a wrapped token from another ERC 20 token with linear dividends delegation */ contract WrappingERC20WithLinearDividends is ERC20 { using SafeMath for uint256; event Mint(address indexed to, uint256 value); event Burn(address indexed from, uint256 value); event DividendClaimed(address indexed from, uint256 value); /** * @dev records an address's dividend state **/ struct DividendState { // amount of dividend that has been consolidated uint256 consolidatedAmount; // timestamp to start calculating newly accrued dividends from uint256 timestamp; // index of the dividend phase that the timestamp falls into uint256 index; } IERC20 public _backingToken; IERC20 public _dai; ILinearDividendOracle public _dividendOracle; // track account balances, only original holders of backing tokens can unlock their tokens mapping (address => uint256) public _lockedBalances; // track account dividend states mapping (address => DividendState) public _dividends; constructor( address backingTokenAddress, address daiAddress, address dividendOracleAddress, string memory name, string memory symbol ) public ERC20(name, symbol) { require(backingTokenAddress != address(0), "Backing token must be defined"); require(dividendOracleAddress != address(0), "Dividend oracle must be defined"); _backingToken = IERC20(backingTokenAddress); _dai = IERC20(daiAddress); _dividendOracle = ILinearDividendOracle(dividendOracleAddress); } /** * @notice deposit backing tokens to be locked, and generate wrapped tokens to sender * @param amount amount of token to wrap * @return true if successful */ function wrap(uint256 amount) external returns(bool) { return wrapTo(msg.sender, amount); } /** * @notice deposit backing tokens to be locked, and generate wrapped tokens to recipient * @param recipient address to receive wrapped tokens * @param amount amount of tokens to wrap * @return true if successful */ function wrapTo(address recipient, uint256 amount) public returns(bool) { require(recipient != address(0), "Recipient cannot be zero address"); // transfer backing token from sender to this contract to be locked _backingToken.transferFrom(msg.sender, address(this), amount); // update how many tokens the sender has locked in total _lockedBalances[msg.sender] = _lockedBalances[msg.sender].add(amount); // mint wTokens to recipient _mint(recipient, amount); emit Mint(recipient, amount); return true; } /** * @notice burn wrapped tokens to unlock backing tokens to sender * @param amount amount of token to unlock * @return true if successful */ function unwrap(uint256 amount) external returns(bool) { return unwrapTo(msg.sender, amount); } /** * @notice burn wrapped tokens to unlock backing tokens to recipient * @param recipient address to receive backing tokens * @param amount amount of tokens to unlock * @return true if successful */ function unwrapTo(address recipient, uint256 amount) public returns (bool) { require(recipient != address(0), "Recipient cannot be zero address"); // burn wTokens from sender, burn should revert if not enough balance _burn(msg.sender, amount); // update how many tokens the sender has locked in total _lockedBalances[msg.sender] = _lockedBalances[msg.sender].sub(amount, "Cannot unlock more than the locked amount"); // transfer backing token from this contract to recipient _backingToken.transfer(recipient, amount); emit Burn(msg.sender, amount); return true; } /** * @notice return locked balances of backing tokens for a given account * @param account account to query for * @return balance of backing token being locked */ function lockedBalance(address account) external view returns (uint256) { return _lockedBalances[account]; } /** * @notice withdraw all accrued dividends by the sender to the sender * @return true if successful */ function claimAllDividends() external returns (bool) { return claimAllDividendsTo(msg.sender); } /** * @notice withdraw all accrued dividends by the sender to the recipient * @param recipient address to receive dividends * @return true if successful */ function claimAllDividendsTo(address recipient) public returns (bool) { require(recipient != address(0), "Recipient cannot be zero address"); consolidateDividends(msg.sender); uint256 dividends = _dividends[msg.sender].consolidatedAmount; _dividends[msg.sender].consolidatedAmount = 0; _dai.transfer(recipient, dividends); emit DividendClaimed(msg.sender, dividends); return true; } /** * @notice withdraw portion of dividends by the sender to the sender * @return true if successful */ function claimDividends(uint256 amount) external returns (bool) { return claimDividendsTo(msg.sender, amount); } /** * @notice withdraw portion of dividends by the sender to the recipient * @param recipient address to receive dividends * @param amount amount of dividends to withdraw * @return true if successful */ function claimDividendsTo(address recipient, uint256 amount) public returns (bool) { require(recipient != address(0), "Recipient cannot be zero address"); consolidateDividends(msg.sender); uint256 dividends = _dividends[msg.sender].consolidatedAmount; require(amount <= dividends, "Insufficient dividend balance"); _dividends[msg.sender].consolidatedAmount = dividends.sub(amount); _dai.transfer(recipient, amount); emit DividendClaimed(msg.sender, amount); return true; } /** * @notice view total accrued dividends of a given account * @param account address of the account to query for * @return total accrued dividends */ function dividendsAvailable(address account) external view returns (uint256) { uint256 balance = balanceOf(account); // short circut if balance is 0 to avoid potentially looping from 0 dividend index if (balance == 0) { return _dividends[account].consolidatedAmount; } (uint256 dividends,) = _dividendOracle.calculateAccruedDividends( balance, _dividends[account].timestamp, _dividends[account].index ); return _dividends[account].consolidatedAmount.add(dividends); } /** * @notice view dividend state of an account * @param account address of the account to query for * @return consolidatedAmount, timestamp, and index */ function getDividendState(address account) external view returns (uint256, uint256, uint256) { return (_dividends[account].consolidatedAmount, _dividends[account].timestamp, _dividends[account].index); } /** * @notice calculate all dividends accrued since the last consolidation, and add to the consolidated amount * @dev anybody can consolidation dividends for any account * @param account account to perform dividend consolidation on * @return true if success */ function consolidateDividends(address account) public returns (bool) { uint256 balance = balanceOf(account); // balance is at 0, re-initialize dividend state if (balance == 0) { initializeDividendState(account); return true; } (uint256 dividends, uint256 newIndex) = _dividendOracle.calculateAccruedDividends( balance, _dividends[account].timestamp, _dividends[account].index ); _dividends[account].consolidatedAmount = _dividends[account].consolidatedAmount.add(dividends); _dividends[account].timestamp = block.timestamp; _dividends[account].index = newIndex; return true; } /** * @notice perform dividend consolidation to the given dividend index * @dev this function can be used if consolidateDividends fails due to running out of gas in an unbounded loop. * In such case, dividend consolidation can be broken into several transactions. * However, dividend rates do not change frequently, * this function should not be needed unless account stays dormant for a long time, e.g. a decade. * @param account account to perform dividend consolidation on * @param toDividendIndex dividend index to stop consolidation at, inclusive * @return true if success */ function consolidateDividendsToIndex(address account, uint256 toDividendIndex) external returns (bool) { uint256 balance = balanceOf(account); // balance is at 0, re-initialize dividend state if (balance == 0) { initializeDividendState(account); return true; } (uint256 dividends, uint256 newIndex, uint256 newTimestamp) = _dividendOracle.calculateAccruedDividendsBounded( balance, _dividends[account].timestamp, _dividends[account].index, toDividendIndex ); _dividends[account].consolidatedAmount = _dividends[account].consolidatedAmount.add(dividends); _dividends[account].timestamp = newTimestamp; _dividends[account].index = newIndex; return true; } /** * @notice setups for parameters for dividend accrual calculations * @param account account to setup for */ function initializeDividendState(address account) internal { // initialize the time to start dividend accrual _dividends[account].timestamp = block.timestamp; // initialize the dividend index to start dividend accrual _dividends[account].index = _dividendOracle.getCurrentIndex(); } /** * @notice consolidate dividends with the balance as is, the new balance will initiate dividend calculations from 0 again * @dev Hook that is called before any transfer of tokens. This includes minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. */ function _beforeTokenTransfer(address from, address to, uint256) internal virtual override { if (from != address(0)) { consolidateDividends(from); } if (to != address(0) && to != from) { consolidateDividends(to); } } }
setups for parameters for dividend accrual calculations account account to setup for/ initialize the time to start dividend accrual initialize the dividend index to start dividend accrual
function initializeDividendState(address account) internal { _dividends[account].timestamp = block.timestamp; _dividends[account].index = _dividendOracle.getCurrentIndex(); }
7,716,836
/** ██████╗░░█████╗░███╗░░██╗████████╗██╗░░██╗███████╗░█████╗░███╗░░██╗ ██╔══██╗██╔══██╗████╗░██║╚══██╔══╝██║░░██║██╔════╝██╔══██╗████╗░██║ ██████╔╝███████║██╔██╗██║░░░██║░░░███████║█████╗░░██║░░██║██╔██╗██║ ██╔═══╝░██╔══██║██║╚████║░░░██║░░░██╔══██║██╔══╝░░██║░░██║██║╚████║ ██║░░░░░██║░░██║██║░╚███║░░░██║░░░██║░░██║███████╗╚█████╔╝██║░╚███║ ╚═╝░░░░░╚═╝░░╚═╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝░░╚═╝╚══════╝░╚════╝░╚═╝░░╚══╝ ██████╗░██╗░░░██╗░██████╗██╗███╗░░██╗███████╗░██████╗░██████╗  ░█████╗░██╗░░░░░██╗░░░██╗██████╗░ ██╔══██╗██║░░░██║██╔════╝██║████╗░██║██╔════╝██╔════╝██╔════╝  ██╔══██╗██║░░░░░██║░░░██║██╔══██╗ ██████╦╝██║░░░██║╚█████╗░██║██╔██╗██║█████╗░░╚█████╗░╚█████╗░  ██║░░╚═╝██║░░░░░██║░░░██║██████╦╝ ██╔══██╗██║░░░██║░╚═══██╗██║██║╚████║██╔══╝░░░╚═══██╗░╚═══██╗  ██║░░██╗██║░░░░░██║░░░██║██╔══██╗ ██████╦╝╚██████╔╝██████╔╝██║██║░╚███║███████╗██████╔╝██████╔╝  ╚█████╔╝███████╗╚██████╔╝██████╦╝ ╚═════╝░░╚═════╝░╚═════╝░╚═╝╚═╝░░╚══╝╚══════╝╚═════╝░╚═════╝░  ░╚════╝░╚══════╝░╚═════╝░╚═════╝░ */ // 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; } } // 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); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // OpenZeppelin Contracts v4.4.1 (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); } // 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); } // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // 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; } } } // 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 * ==== * * [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); } } } } // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) 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; } } // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableMap.sol) pragma solidity ^0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { using EnumerableSet for EnumerableSet.Bytes32Set; // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { map._values[key] = value; return map._keys.add(key); } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { delete map._values[key]; return map._keys.remove(key); } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.length(); } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // 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); } } // OpenZeppelin Contracts v4.4.1 (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; // Base URI string private _baseURI = ""; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Fonction to lock the sale of the NFT bool public isSecondaryMarketOpen = false; mapping(address => bool) public whitelistTransfer; /** * @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_; } // Fonction to lock the sale of the NFT or to unlock function _changeSecondaryMarketState() internal virtual { isSecondaryMarketOpen = !isSecondaryMarketOpen; } // Fonction add or remove address from transfer Whitelist function _modifyAuthorizedSellers(address[] memory addresses, bool state) internal virtual { for (uint256 i = 0; i < addresses.length; i++) { whitelistTransfer[addresses[i]] = state; } } // View Function to check if an adress is present on the map whiteListTransfer function _isWhitelistTransfer(address addr) internal view virtual returns (bool) { return whitelistTransfer[addr]; } /** * @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())) : ""; } function baseURI() public view virtual returns (string memory) { return _baseURI; } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); //require(isSecondaryMarketOpen == true, "Secondary Market sale is not open"); if (isSecondaryMarketOpen == false){ require(whitelistTransfer[from], "Transfer is not authorized for the Sender : contact the project team to be on the Whitelist"); } _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // OpenZeppelin Contracts v4.4.1 (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(); } } // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // 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); } // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Can modify the shares own by the team. * They triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. * After the transfer the new shares are setup */ function _modifyShares(address[] memory oldPayees,address[] memory newPayees , uint256[] memory shares_) internal virtual { // triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the total shares and their previous withdrawals. for (uint256 i = 0; i < oldPayees.length; i++) { require(_shares[oldPayees[i]] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(oldPayees[i], totalReceived, released(oldPayees[i])); if (payment != 0){ _released[oldPayees[i]] += payment; _totalReleased += payment; Address.sendValue(payable(oldPayees[i]), payment); emit PaymentReleased(oldPayees[i], payment); } _released[oldPayees[i]] = 0; _shares[oldPayees[i]] = 0; } // refresh the shares variable to start as a new team shares _totalShares = 0; _totalReleased = 0; // Update des shares for the Payees @dev wants require(newPayees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(newPayees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < newPayees.length; i++) { _addPayee(newPayees[i], shares_[i]); } } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // File: contracts/PantheonBusinessClub.sol pragma solidity ^0.8.0; /** * @title Panthéon Business Club contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract PantheonBusinessClub is ERC721Enumerable, Ownable, PaymentSplitter { using SafeMath for uint256; // The base price is set here. uint256 public nftPrice = 350000000000000000; // 0.35 ETH // Repartition of ETH earned uint256[] private _teamShares = [16, 16, 12, 36, 20]; address[] public _team = [ 0x17482Fa6221f7A6c8453901711d6E2cb3C1355E7, 0xa2D23B0C857E802B97c99bD006Bd707139bAef9A, 0x645AEe5D605b09350BA2135EB340759357E0fA20, 0x0EefcD4C37C78eD786971EC822a1DA6977B08EaC, 0x0d9A8d33428bB813Ea81D32B57A632C532057Fd5 ]; // Only 20 Pantheon Cards can be purchased per transaction. uint256 public constant maxNumPurchase = 20; // Only 8888 total member card will be generated uint256 public MAX_TOKENS = 8888; // Number of token allowed for the Presale uint256 public totalEarlyAccessTokensAllowed = 500; // List of address whitelisted for the Presale mapping(address => bool) private earlyAccessAllowList; // Number max allow during stages uint256 public stage = 0; uint256 private stage2 = 2222; uint256 private stage3 = 3333; uint256 private stage4 = 4444; uint256 private stage5 = 5555; uint256 private stage6 = 6666; uint256 private stage7 = 7777; // List of addresse allowed for different stages mapping(address => bool) private whitelistStage2; mapping(address => bool) private whitelistStage3; mapping(address => bool) private whitelistStage4; mapping(address => bool) private whitelistStage5; mapping(address => bool) private whitelistStage6; mapping(address => bool) private whitelistStage7; // Burn variable true or false if you want people to be able to burn tokens bool public isBurnEnabled = false; event ChangeBurnState(bool _isBurnEnabled); //The hash of the concatented hash string of all the images. string public provenance = ''; /** * The state of the sale: * 0 = closed * 1 = EA * 2 = WL2, 3 = WL3, 4 = WL4, 5 = WL5, 6 = WL6, 7 = WL7 * 8 = stage * 9 = open */ uint256 public saleState = 0; constructor() ERC721("PantheonBusinessClub", "PBC") PaymentSplitter(_team, _teamShares) { setBaseURI('ipfs://QmaWqGvPUVeBRfEc39RRqZ9Hm91kx4qfZiFgGS6TgPbEe7/'); _safeMint(msg.sender, totalSupply()); } /** * Set URL of the NFT */ function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } /** * Modify Shares in paymentSplitter */ function modifyShares(uint256[] memory shares_) public onlyOwner { _modifyShares(_team, _team, shares_); } /** * Modify Shares and Team addresses in paymentSplitter */ function modifyTeamAndShares(address[] memory oldPayees,address[] memory newPayees , uint256[] memory shares_) public onlyOwner { _modifyShares(oldPayees, newPayees, shares_); _team = newPayees; } /** * Lock or unlock the transfer of tokens */ function changeSecondaryMarketState() public onlyOwner { _changeSecondaryMarketState(); } /** * Modify authorized transfer whitelist */ function modifyAuthorizedSellers(address[] memory addresses, bool state) public onlyOwner { _modifyAuthorizedSellers(addresses, state); } /** * retrait des eth stockés dans le smart contrat par le contract Owner */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * Set some tokens aside. */ function reserveTokens(uint256 number) public onlyOwner { require( totalSupply().add(number) <= MAX_TOKENS, 'Reservation would exceed max supply' ); uint256 i; for (i = 0; i < number; i++) { _safeMint(msg.sender, totalSupply() + i); } } /** * Ability for people to burn their tokens */ function burn(uint256 tokenId) external { require(isBurnEnabled, "Pantheon: burning disabled"); require( _isApprovedOrOwner(msg.sender, tokenId), "Pantheon: burn caller is not owner" ); _burn(tokenId); totalSupply().sub(1); } /** * Ability for people to burn their tokens */ function burnRemainingTokens(uint256 tokenNb) external onlyOwner { require(MAX_TOKENS - tokenNb >= totalSupply(), 'Invalid state'); MAX_TOKENS = MAX_TOKENS - tokenNb; } /** * Set the state of the sale. */ function setSaleState(uint256 newState) public onlyOwner { require(newState >= 0 && newState <= 9, 'Invalid state'); saleState = newState; } function setProvenanceHash(string memory hash) public onlyOwner { provenance = hash; } function setPrice(uint256 value) public onlyOwner { nftPrice = value; } function setStage(uint256 value) public onlyOwner { stage = value; } function setBurnState(bool _isBurnEnabled) external onlyOwner { isBurnEnabled = _isBurnEnabled; emit ChangeBurnState(_isBurnEnabled); } /** * Early Access Member list for the presale */ function changeEarlyAccessMembers(address[] memory addresses, bool state) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { earlyAccessAllowList[addresses[i]] = state; } } /** * Allow users to remove themselves from the whitelist */ function removeEarlyAccessMemberHimself() public { require( earlyAccessAllowList[msg.sender], 'Sender is not on the early access list' ); earlyAccessAllowList[msg.sender] = false; } function isWhitelistTransfer(address addr) public view returns (bool) { return _isWhitelistTransfer(addr); } /** * Whitelist functions for stages */ function changeWhitelistMembersForStage(address[] memory addresses, uint256 stageNumber, bool state) public onlyOwner { if (stageNumber == 2) { for (uint256 i = 0; i < addresses.length; i++) { whitelistStage2[addresses[i]] = state; } } else if (stageNumber == 3) { for (uint256 i = 0; i < addresses.length; i++) { whitelistStage3[addresses[i]] = state; } } else if (stageNumber == 4) { for (uint256 i = 0; i < addresses.length; i++) { whitelistStage4[addresses[i]] = state; } } else if (stageNumber == 5) { for (uint256 i = 0; i < addresses.length; i++) { whitelistStage5[addresses[i]] = state; } } else if (stageNumber == 6) { for (uint256 i = 0; i < addresses.length; i++) { whitelistStage6[addresses[i]] = state; } } else if (stageNumber == 7) { for (uint256 i = 0; i < addresses.length; i++) { whitelistStage7[addresses[i]] = state; } } } function isWhitelistForStage(address addr, uint256 stageNumber) public view returns (bool) { if (stageNumber == 2) { return whitelistStage2[addr]; } else if (stageNumber == 3) { return whitelistStage3[addr]; } else if (stageNumber == 4) { return whitelistStage4[addr]; } else if (stageNumber == 5) { return whitelistStage5[addr]; } else if (stageNumber == 6) { return whitelistStage6[addr]; } else if (stageNumber == 7) { return whitelistStage7[addr]; } } function _checkEarlyAccess(address sender, uint256 numberOfTokens) internal view { uint256 supply = totalSupply(); if (saleState == 1) { require( earlyAccessAllowList[sender], 'Sender is not on the early access list' ); require( supply + numberOfTokens <= totalEarlyAccessTokensAllowed, 'Minting would exceed total allowed for early access' ); } else if (saleState == 2) { require( whitelistStage2[sender], 'Sender is not on the Whitelist' ); require( supply + numberOfTokens <= stage2, 'Minting would exceed total allowed for early access' ); } else if (saleState == 3) { require( whitelistStage3[sender], 'Sender is not on the Whitelist' ); require( supply + numberOfTokens <= stage3, 'Minting would exceed total allowed for early access' ); } else if (saleState == 4) { require( whitelistStage4[sender], 'Sender is not on the Whitelist' ); require( supply + numberOfTokens <= stage4, 'Minting would exceed total allowed for early access' ); } else if (saleState == 5) { require( whitelistStage5[sender], 'Sender is not on the early access list' ); require( supply + numberOfTokens <= stage5, 'Minting would exceed total allowed for early access' ); } else if (saleState == 6) { require( whitelistStage6[sender], 'Sender is not on the early access list' ); require( supply + numberOfTokens <= stage6, 'Minting would exceed total allowed for early access' ); } else if (saleState == 7) { require( whitelistStage7[sender], 'Sender is not on the early access list' ); require( supply + numberOfTokens <= stage7, 'Minting would exceed total allowed for early access' ); } } /** * Verify if we are on the whitelist or not */ function checkIfWhitelist(address addr) public view returns (bool) { return earlyAccessAllowList[addr]; } /** * Number of token max you can mint with 1 transaction * You can make unlimmited number of transactions */ function _checkNumberOfTokens(uint256 numberOfTokens) internal pure { require( numberOfTokens <= maxNumPurchase, 'Can only mint 20 tokens at a time' ); } /** * Mints an NFT */ function mintPBC(uint256 numberOfTokens) public payable { require( saleState == 1 || saleState == 2 || saleState == 3 || saleState == 4 || saleState == 5 || saleState == 6 || saleState == 7 || saleState == 8 || saleState == 9, 'Sale must be active to mint' ); if (saleState == 1 || saleState == 2 || saleState == 3 || saleState == 4 || saleState == 5 || saleState == 6 || saleState == 7) { _checkEarlyAccess(msg.sender, numberOfTokens); _checkNumberOfTokens(numberOfTokens); } else if (saleState == 8) { _checkNumberOfTokens(numberOfTokens); require( totalSupply().add(numberOfTokens) <= stage, 'Purchase would exceed stage supply, confirm with the project team the maximum card available for this stage' ); } else if (saleState == 9) { _checkNumberOfTokens(numberOfTokens); } require( totalSupply().add(numberOfTokens) <= MAX_TOKENS, 'Purchase would exceed max supply' ); require( nftPrice.mul(numberOfTokens) <= msg.value, 'Ether value sent is not correct' ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } /** * Mint on wallet list */ function mintG(address[] memory addresses, uint256 nbCard) public onlyOwner { require( totalSupply().add(addresses.length * nbCard) <= MAX_TOKENS, 'Reservation would exceed max supply' ); uint256 i; for (i = 0; i < addresses.length; i++) { uint256 j; for (j = 0; j < nbCard; j++) { uint256 mintIndex = totalSupply(); _safeMint(addresses[i], mintIndex); } } } }
Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the total shares and their previous withdrawals./
function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); }
6,127,354
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "interfaces/yearn/VaultApi.sol"; import "interfaces/yearn/RegistryApi.sol"; abstract contract BaseSimpleWrapperUpgradeable is Initializable { using MathUpgradeable for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; IERC20Upgradeable public token; // Reduce number of external calls (SLOADs stay the same) VaultAPI[] private _cachedVaults; RegistryAPI public registry; // ERC20 Unlimited Approvals (short-circuits VaultAPI.transferFrom) uint256 constant UNLIMITED_APPROVAL = type(uint256).max; // Sentinal values used to save gas on deposit/withdraw/migrate // NOTE: DEPOSIT_EVERYTHING == WITHDRAW_EVERYTHING == MIGRATE_EVERYTHING uint256 constant DEPOSIT_EVERYTHING = type(uint256).max; uint256 constant WITHDRAW_EVERYTHING = type(uint256).max; uint256 constant MIGRATE_EVERYTHING = type(uint256).max; // VaultsAPI.depositLimit is unlimited uint256 constant UNCAPPED_DEPOSITS = type(uint256).max; function _BaseSimpleWrapperUpgradeable_init(address _token, address _registry) internal initializer { token = IERC20Upgradeable(_token); // v2.registry.ychad.eth registry = RegistryAPI(_registry); } function setRegistry(address _registry) external { require(msg.sender == registry.governance()); // In case you want to override the registry instead of re-deploying registry = RegistryAPI(_registry); // Make sure there's no change in governance // NOTE: Also avoid bricking the wrapper from setting a bad registry require(msg.sender == registry.governance()); } }
v2.registry.ychad.eth
function _BaseSimpleWrapperUpgradeable_init(address _token, address _registry) internal initializer { token = IERC20Upgradeable(_token); registry = RegistryAPI(_registry); }
5,367,486
pragma solidity 0.5.8; import "./ModuleFactory.sol"; import "../interfaces/IModuleRegistry.sol"; import "../proxy/OwnedUpgradeabilityProxy.sol"; /** * @title Factory for deploying upgradable modules */ contract UpgradableModuleFactory is ModuleFactory { event LogicContractSet(string _version, uint256 _upgrade, address _logicContract, bytes _upgradeData); event ModuleUpgraded( address indexed _module, address indexed _securityToken, uint256 indexed _version ); struct LogicContract { string version; address logicContract; bytes upgradeData; } // Mapping from version to logic contract mapping (uint256 => LogicContract) public logicContracts; // Mapping from Security Token address, to deployed proxy module address, to module version mapping (address => mapping (address => uint256)) public modules; // Mapping of which security token owns a given module mapping (address => address) public moduleToSecurityToken; // Current version uint256 public latestUpgrade; /** * @notice Constructor * @param _setupCost Setup cost of the module * @param _logicContract Contract address that contains the logic related to `description` * @param _polymathRegistry Address of the Polymath registry * @param _isCostInPoly true = cost in Poly, false = USD */ constructor( string memory _version, uint256 _setupCost, address _logicContract, address _polymathRegistry, bool _isCostInPoly ) public ModuleFactory(_setupCost, _polymathRegistry, _isCostInPoly) { require(_logicContract != address(0), "Invalid address"); logicContracts[latestUpgrade].logicContract = _logicContract; logicContracts[latestUpgrade].version = _version; } /** * @notice Used to upgrade the module factory * @param _version Version of upgraded module * @param _logicContract Address of deployed module logic contract referenced from proxy * @param _upgradeData Data to be passed in call to upgradeToAndCall when a token upgrades its module */ function setLogicContract(string calldata _version, address _logicContract, bytes calldata _upgradeData) external onlyOwner { require(keccak256(abi.encodePacked(_version)) != keccak256(abi.encodePacked(logicContracts[latestUpgrade].version)), "Same version"); require(_logicContract != logicContracts[latestUpgrade].logicContract, "Same version"); require(_logicContract != address(0), "Invalid address"); latestUpgrade++; _modifyLogicContract(latestUpgrade, _version, _logicContract, _upgradeData); } /** * @notice Used to update an existing token logic contract * @param _upgrade logic contract to upgrade * @param _version Version of upgraded module * @param _logicContract Address of deployed module logic contract referenced from proxy * @param _upgradeData Data to be passed in call to upgradeToAndCall when a token upgrades its module */ function updateLogicContract(uint256 _upgrade, string calldata _version, address _logicContract, bytes calldata _upgradeData) external onlyOwner { require(_upgrade <= latestUpgrade, "Invalid upgrade"); // version & contract must differ from previous version, otherwise upgrade proxy will fail if (_upgrade > 0) { require(keccak256(abi.encodePacked(_version)) != keccak256(abi.encodePacked(logicContracts[_upgrade - 1].version)), "Same version"); require(_logicContract != logicContracts[_upgrade - 1].logicContract, "Same version"); } require(_logicContract != address(0), "Invalid address"); require(_upgradeData.length > 4, "Invalid Upgrade"); _modifyLogicContract(_upgrade, _version, _logicContract, _upgradeData); } function _modifyLogicContract(uint256 _upgrade, string memory _version, address _logicContract, bytes memory _upgradeData) internal { logicContracts[_upgrade].version = _version; logicContracts[_upgrade].logicContract = _logicContract; logicContracts[_upgrade].upgradeData = _upgradeData; IModuleRegistry moduleRegistry = IModuleRegistry(polymathRegistry.getAddress("ModuleRegistry")); moduleRegistry.unverifyModule(address(this)); emit LogicContractSet(_version, _upgrade, _logicContract, _upgradeData); } /** * @notice Used by a security token to upgrade a given module * @param _module Address of (proxy) module to be upgraded */ function upgrade(address _module) external { // Only allow the owner of a module to upgrade it require(moduleToSecurityToken[_module] == msg.sender, "Incorrect caller"); // Only allow issuers to upgrade in single step verisons to preserve upgradeToAndCall semantics uint256 newVersion = modules[msg.sender][_module] + 1; require(newVersion <= latestUpgrade, "Incorrect version"); OwnedUpgradeabilityProxy(address(uint160(_module))).upgradeToAndCall(logicContracts[newVersion].version, logicContracts[newVersion].logicContract, logicContracts[newVersion].upgradeData); modules[msg.sender][_module] = newVersion; emit ModuleUpgraded( _module, msg.sender, newVersion ); } /** * @notice Used to initialize the module * @param _module Address of module * @param _data Data used for the intialization of the module factory variables */ function _initializeModule(address _module, bytes memory _data) internal { super._initializeModule(_module, _data); moduleToSecurityToken[_module] = msg.sender; modules[msg.sender][_module] = latestUpgrade; } /** * @notice Get the version related to the module factory */ function version() external view returns(string memory) { return logicContracts[latestUpgrade].version; } }
Used to initialize the module _module Address of module _data Data used for the intialization of the module factory variables/
function _initializeModule(address _module, bytes memory _data) internal { super._initializeModule(_module, _data); moduleToSecurityToken[_module] = msg.sender; modules[msg.sender][_module] = latestUpgrade; }
1,774,014
pragma solidity ^0.4.8; //Smart contract developed in Solidity for kyc and supplychain integration // India Hacks // By Ashish Singla & Deeksha Sachdeva - RBS_Blockgeeks contract IndiaHacks{ //employee details recieved during the kyc are stored in a struct called KYC struct KYC{ uint empId; bytes32 name; bytes32 location; } //an array of type struct to store the details of the employees KYC[] public kyc; //store KYC information on the blockchain i.e. Emp Id, Name and Location function do_KYC(uint _empId, bytes32 _name, bytes32 _location) returns (bool success){ KYC memory newKYC; newKYC.empId=_empId; newKYC.name=_name; newKYC.location=_location; kyc.push(newKYC); return true; } // data structure for mapping(hashmap) between employee ID and names mapping (uint => bytes32) public admins; //create a mapping(hashmap) between employee ID and names function signup(uint _empId, bytes32 _name){ admins[_empId]=_name; } //check whether the employee is already registered in KYC using emp Id function login(uint empId) constant returns (bool) { if(admins[empId]== 0) return false; else return true; } //create a mapping of the employeeId and the requisition he has raised using requisition id mapping (uint => uint) public req_admins; function req_signup(uint _requisitionId, uint _empId){ req_admins[_requisitionId]=_empId; } //check whether a requisition of that id is made or its a invalid id function req_login(uint _requisitionId) constant returns (bool) { if(req_admins[_requisitionId]== 0) return false; else return true; } // data structure for mapping order to the requisition if to a supplier mapping (uint => bytes32) public req_supplier_order_admins; //map the order corresponding to requisition id to a supplier function req_supplier_order_signup(uint _requisitionId, bytes32 _supplier){ req_supplier_order_admins[_requisitionId]=_supplier; } // validate the order is alreday placed corresponding to the requisition for a supplier function req_supplier_order_login(uint _requisitionId) constant returns (bool) { if(req_supplier_order_admins[_requisitionId]== 0) return false; else return true; } // to view all the registered KYC in the regulator node function getKYC() constant returns (uint[],bytes32[],bytes32[]){ uint length =kyc.length; uint[] memory empIds = new uint[](length); bytes32[] memory names = new bytes32[](length); bytes32[] memory locations = new bytes32[](length); for(uint i=0; i< empIds.length; i++){ KYC memory currentKYC; currentKYC = kyc[i]; empIds[i]=currentKYC.empId; names[i]=currentKYC.name; locations[i]=currentKYC.location; } return (empIds, names, locations); } //suppliers can view KYC details of the employee who has placed the order function getKYCforEmployee(uint empId) constant returns (uint,bytes32,bytes32){ uint length =kyc.length; uint[] memory empIds = new uint[](length); for(uint i=0; i< empIds.length; i++){ KYC memory currentKYC; currentKYC = kyc[i]; empIds[i]=currentKYC.empId; if(empIds[i] == empId) { return (currentKYC.empId,currentKYC.name,currentKYC.location); } } return (empId, 'Could not find Employee Details', 'Could not find Employee Details'); } //A struct to store the requisition details Requisition [] public requisition; struct Requisition { uint empId; uint requisitionId; uint qty; } //store the requisitions recieved on the blockchain i.e. employee Id, requisition Id and Quantity function place_requisition(uint _empId, uint _requisitionId,uint _qty) returns (bool success){ Requisition memory newRequisition; newRequisition.empId=_empId; newRequisition.requisitionId=_requisitionId; newRequisition.qty=_qty; requisition.push(newRequisition); return true; } //function to support generation of new requisition id function get_maxRequisitionNumber() constant returns (uint) { uint location = requisition.length - 1; Requisition memory currentRequisition; currentRequisition = requisition[location]; uint reqId = currentRequisition.requisitionId; return (reqId); } // to view all the requisitions placed so far by the regulator, supplier and employee node function get_RequisitionDetails() constant returns ( uint[],uint[],uint[]){ uint length=requisition.length; uint[] memory empIds = new uint[](length); uint[] memory requisitionIds = new uint[](length); uint[] memory qtys = new uint[](length); for(uint i=0; i< requisition.length; i++){ Requisition memory currentRequisition; currentRequisition = requisition[i]; empIds[i]=currentRequisition.empId; requisitionIds[i]=currentRequisition.requisitionId; qtys[i]=currentRequisition.qty; } return (empIds,requisitionIds,qtys); } Quotes[] public quote; // a structure to store all the quotation details from the suppliers corresponding to a requisition struct Quotes { uint requisitionId; uint price; bytes32 vendor; } //Store the quotations on the blockchain by the suppliers i.e. requisition id, price, vendor function place_quotes( uint _requisitionId, uint _price, bytes32 _vendor) returns (bool success) { Quotes memory newQuote; newQuote.requisitionId =_requisitionId; newQuote.price =_price; newQuote.vendor =_vendor; quote.push(newQuote); return true; } // the employee & regulator can view all the quotations recieved which is fetched by this function using their blockchain node function get_quotations() constant returns (uint[],uint[],bytes32[]){ uint length=quote.length; uint[] memory requisitionIds = new uint[](length); uint[] memory prices = new uint[](length); bytes32[] memory vendors = new bytes32[](length); for(uint j=0; j< quote.length; j++){ Quotes memory currentQuote; currentQuote = quote[j]; requisitionIds[j]=currentQuote.requisitionId; prices[j]=currentQuote.price; vendors[j]=currentQuote.vendor; } return (requisitionIds,prices,vendors); } Orders[] public order; // a structure to store all the order details struct Orders { uint requisitionId; bytes32 vendor; } // store the orders placed by the employee on the blockchain i.e. requisitionId & vendor function place_orders( uint _requisitionId, bytes32 _vendor) returns (bool success) { Orders memory newOrder; newOrder.requisitionId =_requisitionId; newOrder.vendor =_vendor; order.push(newOrder); return true; } //the regulator, employee & supplier can view the orders on their respective nodes function get_orders() constant returns (uint[],bytes32[]){ uint length=order.length; uint[] memory requisitionIds = new uint[](length); bytes32[] memory vendors = new bytes32[](length); for(uint j=0; j< order.length; j++){ Orders memory currentOrder; currentOrder = order[j]; requisitionIds[j]=currentOrder.requisitionId; vendors[j]=currentOrder.vendor; } return (requisitionIds,vendors); } }
the employee & regulator can view all the quotations recieved which is fetched by this function using their blockchain node
function get_quotations() constant returns (uint[],uint[],bytes32[]){ uint length=quote.length; uint[] memory requisitionIds = new uint[](length); uint[] memory prices = new uint[](length); bytes32[] memory vendors = new bytes32[](length); for(uint j=0; j< quote.length; j++){ Quotes memory currentQuote; currentQuote = quote[j]; requisitionIds[j]=currentQuote.requisitionId; prices[j]=currentQuote.price; vendors[j]=currentQuote.vendor; } return (requisitionIds,prices,vendors); } Orders[] public order;
1,839,478
/************************************************************************************** * This contract is an Experiment, and should be used at your own risk. * * Author: Stinky Fi & Twisted Tech * Name: Nightmare On Fantom St. * Desc: Knock on our door, and say the magic words, if you dare! * Minters will receive a Trick or a Treat, determined by on-chain randomness. * The ghost haunting our contract has replaced the mint cap with a time cap. * When this contract is Haunted, You will be able to mint as many times as * you want. Take advantage, this haunting will not last long! Once Halloween * is over, no one will be able to mint from this contract again! *************************************************************************************/ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract NightmareOnFantomSt is ERC721Enumerable, ERC721Burnable, ReentrancyGuard, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; /********************************************* * Haunting (Minting starts): * Saturday, October 30, 2021 12:00:00 AM EST * Friday, October 29, 2021 9:00:00 PM PST * Saturday, October 30, 2021 4:00:00 AM GMT *********************************************/ uint256 public haunting = 1635480000; /********************************************* * Exorcism (Minting ends): * Monday, November 1, 2021 3:00:00 AM EST * Monday, November 1, 2021 12:00:00 PM PST * Monday, November 1, 2021 7:00:00 AM GMT *********************************************/ uint256 public exorcism = 1635750000; // Mint Price 1 FTM uint256 public price = 1000000000000000000; // Trick Rarities string[] private tricks; string[] private rare_tricks; string[] private legendary_tricks; // Treat Rarities string[] private treats; string[] private rare_treats; string[] private legendary_treats; address public beneficiary; //Free mints mapping (address => uint256) public winner; event NaughtyList(address indexed _winner, uint256 _tokenId, uint256 _date); constructor(address _beneficiary) ERC721("Nightmare On Fantom St", "NOFS") { beneficiary = _beneficiary; } function setTrickBag(string[] memory _common, string[] memory _rare, string[] memory _legendary) public onlyOwner { tricks = _common; rare_tricks = _rare; legendary_tricks = _legendary; } function setTreatBag(string[] memory _common, string[] memory _rare, string[] memory _legendary) public onlyOwner { treats = _common; rare_treats = _rare; legendary_treats = _legendary; } /************************************************************* * Desc: If you won * After using your freebie, you can use claimHandfull. ***********************************************************/ function contestWinner() public nonReentrant { uint8 result; bool _haunting = witchingHour(); require(_haunting, "This Contract is no longer Haunted"); require(winner[msg.sender] > 0, "Your name is not on the list, rejected."); for(uint256 i = 1; i <= winner[msg.sender]; i++) { _tokenIds.increment(); _safeMint(_msgSender(), _tokenIds.current()); result = bowlGrab(_tokenIds.current()); if(result == 1 || result == 2){ emit NaughtyList(msg.sender, _tokenIds.current(), block.timestamp); } } delete winner[msg.sender]; } /************************************************************* * Desc: If you won * After using your freebie, you can use claimHandfull. ***********************************************************/ function claim(uint256 _mintAmount) public payable nonReentrant { uint8 result; bool _haunting = witchingHour(); require(_haunting, "This Contract is no longer Haunted"); uint256 _bundle = _mintAmount * price; require(_bundle == msg.value, "Incorrect payment amount"); for(uint256 i = 0; i < _mintAmount; i++) { _tokenIds.increment(); _safeMint(_msgSender(), _tokenIds.current()); result = bowlGrab(_tokenIds.current()); if(result == 1 || result == 2){ emit NaughtyList(msg.sender, _tokenIds.current(), block.timestamp); } } payable(beneficiary).transfer(_bundle); } function tokenURI(uint256 _tokenId) override public view returns (string memory) { require(_tokenId <= _tokenIds.current(), "TokenID Has not been minted yet"); return reveal(_tokenId); } /*********************************************************** * random function found in $LOOT. ***********************************************************/ function random(uint256 _tokenId, string memory _keyPrefix) internal pure returns (uint256) { bytes memory abiEncoded = abi.encodePacked(_keyPrefix, toString(_tokenId)); return uint256(keccak256(abiEncoded)); } /************************************************* * Desc: Inspired by $FLOOT ($LOOT derivative) * Dice Roll 1: * 1/4 change of a trick * 3/4 change of a treat * Dice Roll 2: * 1/8 change of upgrade to RARE * Dice Roll 3(if got RARE): * 1/12 change of LEGENDARY **************************************************/ function bowlGrab(uint256 _tokenId) internal pure returns (uint8) { uint256 diceRoll = random(_tokenId, "Trick-Or-Treat"); if(diceRoll % 4 == 0) { diceRoll = random(_tokenId, "Smell-My-Feet"); //Trick if(diceRoll % 8 == 0) // Rare { diceRoll = random(_tokenId, "Good-To-Eat"); if(diceRoll % 12 == 0) //legendary Trick return 1; return 3; } return 5; } else { diceRoll = random(_tokenId, "Smell-My-Feet"); //Treat if(diceRoll % 8 == 0) //Rare Treat { diceRoll = random(_tokenId, "Good-To-Eat"); if(diceRoll % 12 == 0) return 2; return 4; } return 6; } } /************************************ * Desc: Determine Type and Rarity ************************************/ function reveal(uint256 _tokenId) internal view returns (string memory) { uint8 result = bowlGrab(_tokenId); if(result == 5) return tricks[_tokenId % tricks.length]; else if (result == 3) return rare_tricks[_tokenId % tricks.length]; else if (result == 1) return legendary_tricks[_tokenId % legendary_tricks.length]; else if (result == 2) return legendary_treats[_tokenId % legendary_treats.length]; else if (result == 4) return rare_treats[_tokenId % rare_treats.length]; else return treats[_tokenId % treats.length]; } // From $FLOOT function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } /********************************************************** * Desc: All of the minting functions, will only operate * during Halloween weekend 2021 *********************************************************/ function witchingHour() public view returns (bool) { if(block.timestamp >= haunting && block.timestamp < exorcism) {return true;} else {return false;} } /********************************************** * Desc: Contest Winners and Partnerships *********************************************/ function assignWinners(address[] memory _winners, uint256 winnings) public onlyOwner { for (uint i=0; i < _winners.length; i++) { winner[_winners[i]] = winnings; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); // do stuff before every transfer // e.g. check that vote (other than when minted) // being transferred to registered candidate } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } }
Desc: Contest Winners and Partnerships/
function assignWinners(address[] memory _winners, uint256 winnings) public onlyOwner { for (uint i=0; i < _winners.length; i++) { winner[_winners[i]] = winnings; } }
952,364
./full_match/1/0x0056f9784305699F8fAb8f48893c761Afbc7C4F3/sources/contracts/xGTO.sol
Sets jailed address/
function setJailedAddress(address jailedAddress) public onlyOwner { _jailedAddress = jailedAddress; }
8,350,509
// SPDX-License-Identifier: MIT /** * @authors: [@ferittuncer] * @reviewers: [@remedcu] * @auditors: [] * @bounties: [] * @deployments: [0xeF6F9665B3aAC2894Ea4c458F93aBA5BB8f8b86d, 0xc7e49251807780dFBbCA72778890B80bd946590B] */ pragma solidity >=0.7; import "@kleros/erc-792/contracts/IArbitrable.sol"; import "@kleros/erc-792/contracts/erc-1497/IEvidence.sol"; import "@kleros/erc-792/contracts/IArbitrator.sol"; import "@kleros/ethereum-libraries/contracts/CappedMath.sol"; /** * @title BinaryArbitrableProxy * This contract acts as a general purpose dispute creator. */ contract BinaryArbitrableProxy is IArbitrable, IEvidence { using CappedMath for uint256; // Operations bounded between 0 and 2**256 - 1. address public governor = msg.sender; IArbitrator public arbitrator; // The required fee stake that a party must pay depends on who won the previous round and is proportional to the arbitration cost such that the fee stake for a round is stake multiplier * arbitration cost for that round. // Multipliers are in basis points. uint256 public winnerStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that won the previous round. uint256 public loserStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that lost the previous round. uint256 public sharedStakeMultiplier; // Multiplier for calculating the fee stake that must be paid in the case where there isn't a winner and loser (e.g. when it's the first round or the arbitrator ruled "refused to rule"/"could not rule"). uint256 public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. uint256 constant NUMBER_OF_CHOICES = 2; enum Party {None, Requester, Respondent} /** @dev Constructor * @param _arbitrator Target global arbitrator for any disputes. * @param _winnerStakeMultiplier Multiplier of the arbitration cost that the winner has to pay as fee stake for a round in basis points. * @param _loserStakeMultiplier Multiplier of the arbitration cost that the loser has to pay as fee stake for a round in basis points. * @param _sharedStakeMultiplier Multiplier of the arbitration cost that each party must pay as fee stake for a round when there isn't a winner/loser in the previous round (e.g. when it's the first round or the arbitrator refused to or did not rule). In basis points. */ constructor( IArbitrator _arbitrator, uint256 _winnerStakeMultiplier, uint256 _loserStakeMultiplier, uint256 _sharedStakeMultiplier ) public { arbitrator = _arbitrator; winnerStakeMultiplier = _winnerStakeMultiplier; loserStakeMultiplier = _loserStakeMultiplier; sharedStakeMultiplier = _sharedStakeMultiplier; } struct Round { uint256[3] paidFees; // Tracks the fees paid by each side in this round. bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise. uint256 feeRewards; // Sum of reimbursable appeal fees available to the parties that made contributions to the side that ultimately wins a dispute. mapping(address => uint256[3]) contributions; // Maps contributors to their contributions for each side. } struct DisputeStruct { bytes arbitratorExtraData; bool isRuled; Party ruling; uint256 disputeIDOnArbitratorSide; } DisputeStruct[] public disputes; mapping(uint256 => uint256) public externalIDtoLocalID; mapping(uint256 => Round[]) public disputeIDRoundIDtoRound; mapping(uint256 => mapping(address => bool)) public withdrewAlready; /** @dev TRUSTED. Calls createDispute function of the specified arbitrator to create a dispute. Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract. * @param _arbitratorExtraData Extra data for the arbitrator of prospective dispute. * @param _metaevidenceURI Link to metaevidence of prospective dispute. */ function createDispute(bytes calldata _arbitratorExtraData, string calldata _metaevidenceURI) external payable returns (uint256 disputeID) { disputeID = arbitrator.createDispute{value: msg.value}(NUMBER_OF_CHOICES, _arbitratorExtraData); disputes.push(DisputeStruct({arbitratorExtraData: _arbitratorExtraData, isRuled: false, ruling: Party.None, disputeIDOnArbitratorSide: disputeID})); uint256 localDisputeID = disputes.length - 1; externalIDtoLocalID[disputeID] = localDisputeID; disputeIDRoundIDtoRound[localDisputeID].push(); emit MetaEvidence(localDisputeID, _metaevidenceURI); emit Dispute(arbitrator, disputeID, localDisputeID, localDisputeID); } /** @dev Returns the contribution value and remainder from available ETH and required amount. * @param _available The amount of ETH available for the contribution. * @param _requiredAmount The amount of ETH required for the contribution. * @return taken The amount of ETH taken. * @return remainder The amount of ETH left from the contribution. */ function calculateContribution(uint256 _available, uint256 _requiredAmount) internal pure returns (uint256 taken, uint256 remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Make a fee contribution. * @param _round The round to contribute. * @param _side The side for which to contribute. * @param _contributor The contributor. * @param _amount The amount contributed. * @param _totalRequired The total amount required for this side. */ function contribute( Round storage _round, Party _side, address payable _contributor, uint256 _amount, uint256 _totalRequired ) internal { // Take up to the amount necessary to fund the current round at the current costs. uint256 contribution; // Amount contributed. uint256 remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint256(_side)])); _round.contributions[_contributor][uint256(_side)] += contribution; _round.paidFees[uint256(_side)] += contribution; _round.feeRewards += contribution; // Reimburse leftover ETH. _contributor.send(remainingETH); // Deliberate use of send in order to not block the contract in case of reverting fallback. } /** @dev TRUSTED. Manages contributions and calls appeal function of the specified arbitrator to appeal a dispute. This function lets appeals be crowdfunded. Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract. * @param _localDisputeID Index of the dispute in disputes array. * @param _side The side to which the caller wants to contribute. */ function fundAppeal(uint256 _localDisputeID, Party _side) external payable { require(_side != Party.None, "You can't fund an appeal in favor of refusing to arbitrate."); DisputeStruct storage dispute = disputes[_localDisputeID]; (uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(dispute.disputeIDOnArbitratorSide); require(block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Funding must be made within the appeal period."); Party winner = Party(arbitrator.currentRuling(dispute.disputeIDOnArbitratorSide)); Party loser; if (winner == Party.Requester) loser = Party.Respondent; else if (winner == Party.Respondent) loser = Party.Requester; require(!(_side == loser) || (block.timestamp - appealPeriodStart < (appealPeriodEnd - appealPeriodStart) / 2), "The loser must contribute during the first half of the appeal period."); uint256 multiplier; if (_side == winner) { multiplier = winnerStakeMultiplier; } else if (_side == loser) { multiplier = loserStakeMultiplier; } else { multiplier = sharedStakeMultiplier; } uint256 appealCost = arbitrator.appealCost(dispute.disputeIDOnArbitratorSide, dispute.arbitratorExtraData); uint256 totalCost = appealCost.addCap(appealCost.mulCap(multiplier) / MULTIPLIER_DIVISOR); Round[] storage rounds = disputeIDRoundIDtoRound[_localDisputeID]; Round storage lastRound = disputeIDRoundIDtoRound[_localDisputeID][rounds.length - 1]; contribute(lastRound, _side, msg.sender, msg.value, totalCost); if (lastRound.paidFees[uint256(_side)] >= totalCost) lastRound.hasPaid[uint256(_side)] = true; if (lastRound.hasPaid[uint8(Party.Requester)] && lastRound.hasPaid[uint8(Party.Respondent)]) { rounds.push(); lastRound.feeRewards = lastRound.feeRewards.subCap(appealCost); arbitrator.appeal{value: appealCost}(dispute.disputeIDOnArbitratorSide, dispute.arbitratorExtraData); } } /** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets solved. * @param _localDisputeID Index of the dispute in disputes array. * @param _contributor The address to withdraw its rewards. * @param _roundNumber The number of the round caller wants to withdraw from. */ function withdrawFeesAndRewards( uint256 _localDisputeID, address payable _contributor, uint256 _roundNumber ) public { DisputeStruct storage dispute = disputes[_localDisputeID]; Round storage round = disputeIDRoundIDtoRound[_localDisputeID][_roundNumber]; uint8 ruling = uint8(dispute.ruling); require(dispute.isRuled, "The dispute should be solved"); uint256 reward; if (!round.hasPaid[uint8(Party.Requester)] || !round.hasPaid[uint8(Party.Respondent)]) { // Allow to reimburse if funding was unsuccessful. reward = round.contributions[_contributor][uint8(Party.Requester)] + round.contributions[_contributor][uint8(Party.Respondent)]; round.contributions[_contributor][uint8(Party.Requester)] = 0; round.contributions[_contributor][uint8(Party.Respondent)] = 0; } else if (Party(ruling) == Party.None) { // Reimburse unspent fees proportionally if there is no winner and loser. uint256 rewardRequester = round.paidFees[uint8(Party.Requester)] > 0 ? (round.contributions[_contributor][uint8(Party.Requester)] * round.feeRewards) / (round.paidFees[uint8(Party.Requester)] + round.paidFees[uint8(Party.Respondent)]) : 0; uint256 rewardRespondent = round.paidFees[uint8(Party.Respondent)] > 0 ? (round.contributions[_contributor][uint8(Party.Respondent)] * round.feeRewards) / (round.paidFees[uint8(Party.Requester)] + round.paidFees[uint8(Party.Respondent)]) : 0; reward = rewardRequester + rewardRespondent; round.contributions[_contributor][uint8(Party.Requester)] = 0; round.contributions[_contributor][uint8(Party.Respondent)] = 0; } else { // Reward the winner. reward = round.paidFees[ruling] > 0 ? (round.contributions[_contributor][ruling] * round.feeRewards) / round.paidFees[ruling] : 0; round.contributions[_contributor][ruling] = 0; } _contributor.send(reward); // User is responsible for accepting the reward. } /** @dev Allows to withdraw any rewards or reimbursable fees after the dispute gets resolved, for all rounds. * @param _localDisputeID Index of the dispute in disputes array. * @param _contributor The address to withdraw its rewards. */ function withdrawFeesAndRewardsForAllRounds(uint256 _localDisputeID, address payable _contributor) external { require(withdrewAlready[_localDisputeID][_contributor] == false, "This contributor withdrew all already."); for (uint256 roundNumber = 0; roundNumber < disputeIDRoundIDtoRound[_localDisputeID].length; roundNumber++) { withdrawFeesAndRewards(_localDisputeID, _contributor, roundNumber); } withdrewAlready[_localDisputeID][_contributor] = true; } /** @dev To be called by the arbitrator of the dispute, to declare winning side. * @param _externalDisputeID ID of the dispute in arbitrator contract. * @param _ruling The ruling choice of the arbitration. */ function rule(uint256 _externalDisputeID, uint256 _ruling) external override { uint256 _localDisputeID = externalIDtoLocalID[_externalDisputeID]; DisputeStruct storage dispute = disputes[_localDisputeID]; require(msg.sender == address(arbitrator), "Only the arbitrator can execute this."); require(_ruling <= NUMBER_OF_CHOICES, "Invalid ruling."); require(dispute.isRuled == false, "Is ruled already."); dispute.isRuled = true; dispute.ruling = Party(_ruling); Round[] storage rounds = disputeIDRoundIDtoRound[_localDisputeID]; Round storage round = disputeIDRoundIDtoRound[_localDisputeID][rounds.length - 1]; if (round.hasPaid[uint8(Party.Requester)] == true) // If one side paid its fees, the ruling is in its favor. Note that if the other side had also paid, an appeal would have been created. dispute.ruling = Party.Requester; else if (round.hasPaid[uint8(Party.Respondent)] == true) dispute.ruling = Party.Respondent; emit Ruling(IArbitrator(msg.sender), _externalDisputeID, uint256(dispute.ruling)); } /** @dev Allows to submit evidence for a given dispute. * @param _localDisputeID Index of the dispute in disputes array. * @param _evidenceURI Link to evidence. */ function submitEvidence(uint256 _localDisputeID, string calldata _evidenceURI) external { DisputeStruct storage dispute = disputes[_localDisputeID]; require(dispute.isRuled == false, "Cannot submit evidence to a resolved dispute."); emit Evidence(arbitrator, _localDisputeID, msg.sender, _evidenceURI); } /** @dev Changes the proportion of appeal fees that must be paid when there is no winner or loser. * @param _sharedStakeMultiplier The new tie multiplier value respect to MULTIPLIER_DIVISOR. */ function changeSharedStakeMultiplier(uint256 _sharedStakeMultiplier) external { require(msg.sender == governor, "Only the governor can execute this."); sharedStakeMultiplier = _sharedStakeMultiplier; } /** @dev Changes the proportion of appeal fees that must be paid by winner. * @param _winnerStakeMultiplier The new winner multiplier value respect to MULTIPLIER_DIVISOR. */ function changeWinnerStakeMultiplier(uint256 _winnerStakeMultiplier) external { require(msg.sender == governor, "Only the governor can execute this."); winnerStakeMultiplier = _winnerStakeMultiplier; } /** @dev Changes the proportion of appeal fees that must be paid by loser. * @param _loserStakeMultiplier The new loser multiplier value respect to MULTIPLIER_DIVISOR. */ function changeLoserStakeMultiplier(uint256 _loserStakeMultiplier) external { require(msg.sender == governor, "Only the governor can execute this."); loserStakeMultiplier = _loserStakeMultiplier; } /** @dev Gets the information of a round of a dispute. * @param _localDisputeID ID of the dispute. * @param _round The round to be queried. * @return appealed Whether the round is appealed or not. * @return paidFees Total fees paid for each party. * @return hasPaid Whether given party paid required amount or not, for each party. * @return feeRewards Total fees collected for parties excluding appeal cost. */ function getRoundInfo(uint256 _localDisputeID, uint256 _round) external view returns ( bool appealed, uint256[3] memory paidFees, bool[3] memory hasPaid, uint256 feeRewards ) { Round storage round = disputeIDRoundIDtoRound[_localDisputeID][_round]; return (_round != (disputeIDRoundIDtoRound[_localDisputeID].length - 1), round.paidFees, round.hasPaid, round.feeRewards); } /** @dev Returns stake multipliers. * @return winner Winners stake multiplier. * @return loser Losers stake multiplier. * @return shared Multiplier when it's tied. * @return divisor Multiplier divisor. */ function getMultipliers() external view returns ( uint256 winner, uint256 loser, uint256 shared, uint256 divisor ) { return (winnerStakeMultiplier, loserStakeMultiplier, sharedStakeMultiplier, MULTIPLIER_DIVISOR); } /** @dev Returns crowdfunding status, useful for user interfaces. * @param _localDisputeID Dispute ID as in this contract. * @param _participant Address of crowdfunding participant to get details of. * @return paidFees Total fees paid for each party in the last round. * @return hasPaid Whether given party paid required amount or not, for each party, in the last round. * @return feeRewards Total fees collected for parties excluding appeal cost, in the last round. * @return contributions Contributions of given participant in the last round. */ function crowdfundingStatus(uint256 _localDisputeID, address _participant) external view returns ( uint256[3] memory paidFees, bool[3] memory hasPaid, uint256 feeRewards, uint256[3] memory contributions ) { Round[] storage rounds = disputeIDRoundIDtoRound[_localDisputeID]; Round storage round = disputeIDRoundIDtoRound[_localDisputeID][rounds.length - 1]; return (round.paidFees, round.hasPaid, round.feeRewards, round.contributions[_participant]); } /** @dev Proxy getter for arbitration cost. * @param _arbitratorExtraData Extra data for arbitration cost calculation. See arbitrator for details. * @return arbitrationFee Arbitration cost of the arbitrator of this contract. */ function getArbitrationCost(bytes calldata _arbitratorExtraData) external view returns (uint256 arbitrationFee) { arbitrationFee = arbitrator.arbitrationCost(_arbitratorExtraData); } /** @dev Returns active disputes. * @param _cursor Starting point for search. * @param _count Number of items to return. * @return openDisputes Dispute identifiers of open disputes, as in arbitrator. * @return hasMore Whether the search was exhausted (has no more) or not (has more). */ function getOpenDisputes(uint256 _cursor, uint256 _count) external view returns (uint256[] memory openDisputes, bool hasMore) { uint256 noOfOpenDisputes = 0; for (uint256 i = 0; i < disputes.length; i++) { if (disputes[i].isRuled == false) { noOfOpenDisputes++; } } openDisputes = new uint256[](noOfOpenDisputes); uint256 count = 0; hasMore = true; uint256 i; for (i = _cursor; i < disputes.length && (count < _count || 0 == _count); i++) { if (disputes[i].isRuled == false) { openDisputes[count++] = disputes[i].disputeIDOnArbitratorSide; } } if (i == disputes.length) hasMore = false; } }
_arbitratorExtraData Extra data for the arbitrator of prospective dispute. _metaevidenceURI Link to metaevidence of prospective dispute./
function createDispute(bytes calldata _arbitratorExtraData, string calldata _metaevidenceURI) external payable returns (uint256 disputeID) { uint256 localDisputeID = disputes.length - 1; externalIDtoLocalID[disputeID] = localDisputeID; disputeIDRoundIDtoRound[localDisputeID].push(); emit MetaEvidence(localDisputeID, _metaevidenceURI); emit Dispute(arbitrator, disputeID, localDisputeID, localDisputeID); }
1,001,199
./partial_match/3/0x7270187150D440643064aa9739239bA80CD8fE97/sources/contracts/ExampleToken.sol
locks transfers to the CapTable/
function lockCapTable() external onlyTransferAgent whenTokenIsActive onlyAfterLaunch whenCapTableIsUnlocked { isCapTableLocked = true; emit CapTableLocked(msg.sender); }
5,051,787
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > 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-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/property/Reclaimable.sol /** * @title Reclaimable * @dev This contract gives owner right to recover any ERC20 tokens accidentally sent to * the token contract. The recovered token will be sent to the owner of token. * @author Validity Labs AG <[email protected]> */ // solhint-disable-next-line compiler-fixed, compiler-gt-0_5 pragma solidity ^0.5.0; contract Reclaimable is Ownable { using SafeERC20 for IERC20; /** * @notice Let the owner to retrieve other tokens accidentally sent to this contract. * @dev This function is suitable when no token of any kind shall be stored under * the address of the inherited contract. * @param tokenToBeRecovered address of the token to be recovered. */ function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner { uint256 balance = tokenToBeRecovered.balanceOf(address(this)); tokenToBeRecovered.safeTransfer(owner(), balance); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } // File: openzeppelin-solidity/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.0; /** * @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See `ERC20._mint`. * * Requirements: * * - the caller must have the `MinterRole`. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Capped.sol pragma solidity ^0.5.0; /** * @dev Extension of `ERC20Mintable` that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See `ERC20Mintable.mint`. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.0; /** * @dev Extension of `ERC20` that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is ERC20 { /** * @dev Destoys `amount` tokens from the caller. * * See `ERC20._burn`. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev See `ERC20._burnFrom`. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: contracts/token/Snapshots.sol /** * @title Snapshot * @dev Utility library of the Snapshot structure, including getting value. * @author Validity Labs AG <[email protected]> */ // solhint-disable-next-line compiler-fixed, compiler-gt-0_5 pragma solidity ^0.5.0; library Snapshots { using Math for uint256; using SafeMath for uint256; /** * @notice This structure stores the historical value associate at a particular blocknumber * @param fromBlock The blocknumber of the creation of the snapshot * @param value The value to be recorded */ struct Snapshot { uint256 fromBlock; uint256 value; } struct SnapshotList { Snapshot[] history; } /** * @notice This function creates snapshots for certain value... * @dev To avoid having two Snapshots with the same block.number, we check if the last * existing one is the current block.number, we update the last Snapshot * @param item The SnapshotList to be operated * @param _value The value associated the the item that is going to have a snapshot */ function createSnapshot(SnapshotList storage item, uint256 _value) internal { uint256 length = item.history.length; if (length == 0 || (item.history[length.sub(1)].fromBlock < block.number)) { item.history.push(Snapshot(block.number, _value)); } else { // When the last existing snapshot is ready to be updated item.history[length.sub(1)].value = _value; } } /** * @notice Find the index of the item in the SnapshotList that contains information * corresponding to the blockNumber. (FindLowerBond of the array) * @dev The binary search logic is inspired by the Arrays.sol from Openzeppelin * @param item The list of Snapshots to be queried * @param blockNumber The block number of the queried moment * @return The index of the Snapshot array */ function findBlockIndex( SnapshotList storage item, uint256 blockNumber ) internal view returns (uint256) { // Find lower bound of the array uint256 length = item.history.length; // Return value for extreme cases: If no snapshot exists and/or the last snapshot if (item.history[length.sub(1)].fromBlock <= blockNumber) { return length.sub(1); } else { // Need binary search for the value uint256 low = 0; uint256 high = length.sub(1); while (low < high.sub(1)) { uint256 mid = Math.average(low, high); // mid will always be strictly less than high and it rounds down if (item.history[mid].fromBlock <= blockNumber) { low = mid; } else { high = mid; } } return low; } } /** * @notice This function returns the value of the corresponding Snapshot * @param item The list of Snapshots to be queried * @param blockNumber The block number of the queried moment * @return The value of the queried moment */ function getValueAt( SnapshotList storage item, uint256 blockNumber ) internal view returns (uint256) { if (item.history.length == 0 || blockNumber < item.history[0].fromBlock) { return 0; } else { uint256 index = findBlockIndex(item, blockNumber); return item.history[index].value; } } } // File: contracts/token/IERC20Snapshot.sol /** * @title Snapshot Token Interface * @dev This is the interface of the ERC20Snapshot * @author Validity Labs AG <[email protected]> */ // solhint-disable-next-line compiler-fixed, compiler-gt-0_5 pragma solidity ^0.5.0; contract IERC20Snapshot { /** * @notice Return the historical supply of the token at a certain time * @param blockNumber The block number of the moment when token supply is queried * @return The total supply at "blockNumber" */ function totalSupplyAt(uint256 blockNumber) public view returns (uint256); /** * @notice Return the historical balance of an account at a certain time * @param owner The address of the token holder * @param blockNumber The block number of the moment when token supply is queried * @return The balance of the queried token holder at "blockNumber" */ function balanceOfAt(address owner, uint256 blockNumber) public view returns (uint256); } // File: contracts/token/ERC20Snapshot.sol /** * @title Snapshot Token * @dev This is an ERC20 compatible token that takes snapshots of account balances. * @author Validity Labs AG <[email protected]> */ // solhint-disable-next-line compiler-fixed, compiler-gt-0_5 pragma solidity ^0.5.0; contract ERC20Snapshot is ERC20, IERC20Snapshot { using Snapshots for Snapshots.SnapshotList; mapping(address => Snapshots.SnapshotList) private _snapshotBalances; Snapshots.SnapshotList private _snapshotTotalSupply; event AccountSnapshotCreated(address indexed account, uint256 indexed blockNumber, uint256 value); event TotalSupplySnapshotCreated(uint256 indexed blockNumber, uint256 value); /** * @notice Return the historical supply of the token at a certain time * @param blockNumber The block number of the moment when token supply is queried * @return The total supply at "blockNumber" */ function totalSupplyAt(uint256 blockNumber) public view returns (uint256) { return _snapshotTotalSupply.getValueAt(blockNumber); } /** * @notice Return the historical balance of an account at a certain time * @param owner The address of the token holder * @param blockNumber The block number of the moment when token supply is queried * @return The balance of the queried token holder at "blockNumber" */ function balanceOfAt(address owner, uint256 blockNumber) public view returns (uint256) { return _snapshotBalances[owner].getValueAt(blockNumber); } /** OVERRIDE * @notice Transfer tokens between two accounts while enforcing the update of Snapshots * @param from The address to transfer from * @param to The address to transfer to * @param value The amount to be transferred */ function _transfer(address from, address to, uint256 value) internal { super._transfer(from, to, value); _snapshotBalances[from].createSnapshot(balanceOf(from)); _snapshotBalances[to].createSnapshot(balanceOf(to)); emit AccountSnapshotCreated(from, block.number, balanceOf(from)); emit AccountSnapshotCreated(to, block.number, balanceOf(to)); } /** OVERRIDE * @notice Mint tokens to one account while enforcing the update of Snapshots * @param account The address that receives tokens * @param value The amount of tokens to be created */ function _mint(address account, uint256 value) internal { super._mint(account, value); _snapshotBalances[account].createSnapshot(balanceOf(account)); _snapshotTotalSupply.createSnapshot(totalSupply()); emit AccountSnapshotCreated(account, block.number, balanceOf(account)); emit TotalSupplySnapshotCreated(block.number, totalSupply()); } /** OVERRIDE * @notice Burn tokens of one account * @param account The address whose tokens will be burnt * @param value The amount of tokens to be burnt */ function _burn(address account, uint256 value) internal { super._burn(account, value); _snapshotBalances[account].createSnapshot(balanceOf(account)); _snapshotTotalSupply.createSnapshot(totalSupply()); emit AccountSnapshotCreated(account, block.number, balanceOf(account)); emit TotalSupplySnapshotCreated(block.number, totalSupply()); } } // File: contracts/membership/ManagerRole.sol /** * @title Manager Role * @dev This contract is developed based on the Manager contract of OpenZeppelin. * The key difference is the management of the manager roles is restricted to one owner * account. At least one manager should exist in any situation. * @author Validity Labs AG <[email protected]> */ // solhint-disable-next-line compiler-fixed, compiler-gt-0_5 pragma solidity ^0.5.0; contract ManagerRole is Ownable { using Roles for Roles.Role; using SafeMath for uint256; event ManagerAdded(address indexed account); event ManagerRemoved(address indexed account); Roles.Role private managers; uint256 private _numManager; constructor() internal { _addManager(msg.sender); _numManager = 1; } /** * @notice Only manager can take action */ modifier onlyManager() { require(isManager(msg.sender), "The account is not a manager"); _; } /** * @notice This function allows to add managers in batch with control of the number of * interations * @param accounts The accounts to be added in batch */ // solhint-disable-next-line function addManagers(address[] calldata accounts) external onlyOwner { uint256 length = accounts.length; require(length <= 256, "too many accounts"); for (uint256 i = 0; i < length; i++) { _addManager(accounts[i]); } } /** * @notice Add an account to the list of managers, * @param account The account address whose manager role needs to be removed. */ function removeManager(address account) external onlyOwner { _removeManager(account); } /** * @notice Check if an account is a manager * @param account The account to be checked if it has a manager role * @return true if the account is a manager. Otherwise, false */ function isManager(address account) public view returns (bool) { return managers.has(account); } /** *@notice Get the number of the current managers */ function numManager() public view returns (uint256) { return _numManager; } /** * @notice Add an account to the list of managers, * @param account The account that needs to tbe added as a manager */ function addManager(address account) public onlyOwner { require(account != address(0), "account is zero"); _addManager(account); } /** * @notice Renounce the manager role * @dev This function was not explicitly required in the specs. There should be at * least one manager at any time. Therefore, at least two when one manage renounces * themselves. */ function renounceManager() public { require(_numManager >= 2, "Managers are fewer than 2"); _removeManager(msg.sender); } /** OVERRIDE * @notice Allows the current owner to relinquish control of the contract. * @dev 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 { revert("Cannot renounce ownership"); } /** * @notice Internal function to be called when adding a manager * @param account The address of the manager-to-be */ function _addManager(address account) internal { _numManager = _numManager.add(1); managers.add(account); emit ManagerAdded(account); } /** * @notice Internal function to remove one account from the manager list * @param account The address of the to-be-removed manager */ function _removeManager(address account) internal { _numManager = _numManager.sub(1); managers.remove(account); emit ManagerRemoved(account); } } // File: contracts/membership/PausableManager.sol /** * @title Pausable Manager Role * @dev This manager can also pause a contract. This contract is developed based on the * Pause contract of OpenZeppelin. * @author Validity Labs AG <[email protected]> */ // solhint-disable-next-line compiler-fixed, compiler-gt-0_5 pragma solidity ^0.5.0; contract PausableManager is ManagerRole { event BePaused(address manager); event BeUnpaused(address manager); bool private _paused; // If the crowdsale contract is paused, controled by the manager... constructor() internal { _paused = false; } /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "not paused"); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "paused"); _; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns(bool) { return _paused; } /** * @notice called by the owner to pause, triggers stopped state */ function pause() public onlyManager whenNotPaused { _paused = true; emit BePaused(msg.sender); } /** * @notice called by the owner to unpause, returns to normal state */ function unpause() public onlyManager whenPaused { _paused = false; emit BeUnpaused(msg.sender); } } // File: contracts/vault/IVault.sol /* * @title Interface for basic vaults * @author Validity Labs AG <[email protected]> */ // solhint-disable-next-line compiler-fixed, compiler-gt-0_5 pragma solidity ^0.5.0; contract IVault { /** * @notice Adding beneficiary to the vault * @param beneficiary The account that receives token * @param value The amount of token allocated */ function receiveFor(address beneficiary, uint256 value) public; /** * @notice Update the releaseTime for vaults * @param roundEndTime The new releaseTime */ function updateReleaseTime(uint256 roundEndTime) public; } // File: contracts/property/CounterGuard.sol /** * @title modifier contract that guards certain properties only triggered once * @author Validity Labs AG <[email protected]> */ // solhint-disable-next-line compiler-fixed, compiler-gt-0_5 pragma solidity ^0.5.0; contract CounterGuard { /** * @notice Controle if a boolean attribute (false by default) was updated to true. * @dev This attribute is designed specifically for recording an action. * @param criterion The boolean attribute that records if an action has taken place */ modifier onlyOnce(bool criterion) { require(criterion == false, "Already been set"); _; } } // File: contracts/token/IvoToken.sol /** * @title IVO token * @author Validity Labs AG <[email protected]> */ // solhint-disable-next-line compiler-fixed, compiler-gt-0_5 pragma solidity ^0.5.0; contract IvoToken is CounterGuard, Reclaimable, ERC20Detailed, ERC20Snapshot, ERC20Capped, ERC20Burnable, PausableManager { // /* solhint-disable */ uint256 private constant SAFT_ALLOCATION = 22500000 ether; uint256 private constant RESERVE_ALLOCATION = 10000000 ether; uint256 private constant ADVISOR_ALLOCATION = 1500000 ether; uint256 private constant TEAM_ALLOCATION = 13500000 ether; address private _saftVaultAddress; address private _reserveVaultAddress; address private _advisorVestingAddress; address private _teamVestingAddress; mapping(address=>bool) private _listOfVaults; bool private _setRole; /** * @notice Constructor of the token contract * @param name The complete name of the token: "INVAO token" * @param symbol The abbreviation of the token, to be searched for on exchange: "IVO" * @param decimals The decimals of the token: 18 * @param cap The max cap of the token supply: 100000000000000000000000000 */ constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap ) public ERC20Detailed(name, symbol, decimals) ERC20Capped(cap) { pause(); } /** * @notice Pausable transfer function, with exception of letting vaults/vesting * contracts transfer tokens to beneficiaries, when beneficiaries claim their token * from vaults or vesting contracts. * @param to The recipient address * @param value The amount of token to be transferred */ function transfer(address to, uint256 value) public returns (bool) { require(!this.paused() || _listOfVaults[msg.sender], "The token is paused and you are not a valid vault/vesting contract"); return super.transfer(to, value); } /** * @notice Pausable transferFrom function * @param from The address from which tokens are sent * @param to The recipient address * @param value The amount of token to be transferred. * @return If the transaction was successful in bool. */ function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } /** * @notice Pausable approve function * @param spender The authorized account to spend a certain amount of token on behalf of the holder * @param value The amount of token that is allowed to spent * @return If the transaction was successful in bool. */ function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } /** * @notice Pausable increaseAllowance function * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. * @return If the action was successful in bool. */ function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } /** * @notice Pausable decreaseAllowance function * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. * @return If the action was successful in bool. */ function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } /** * @notice setup roles and contract addresses for the new token * @param newOwner Address of the owner who is also a manager * @param crowdsaleContractAddress crowdsal address: can mint and pause token * @param saftVaultAddress Address of the SAFT vault contract. * @param privateVaultAddress Address of the private sale vault contract * @param presaleVaultAddress Address of the presale vault contract * @param advisorVestingAddress Address of the advisor vesting contract. * @param teamVestingAddress Address of the team vesting contract. * @param reserveVaultAddress Address of the reserve vault contract. */ function roleSetup( address newOwner, address crowdsaleContractAddress, IVault saftVaultAddress, IVault privateVaultAddress, IVault presaleVaultAddress, IVault advisorVestingAddress, IVault teamVestingAddress, IVault reserveVaultAddress ) public onlyOwner onlyOnce(_setRole) { _setRole = true; // set vault and vesting contract addresses _saftVaultAddress = address(saftVaultAddress); _reserveVaultAddress = address(reserveVaultAddress); _advisorVestingAddress = address(advisorVestingAddress); _teamVestingAddress = address(teamVestingAddress); _listOfVaults[_saftVaultAddress] = true; _listOfVaults[address(privateVaultAddress)] = true; _listOfVaults[address(presaleVaultAddress)] = true; _listOfVaults[_advisorVestingAddress] = true; _listOfVaults[_teamVestingAddress] = true; //After setting adresses of vaults, manager can trigger the allocation of tokens // to vaults. No need to mint to the private vault nor the presale vault because // it's been minted dynamicly. mint(_saftVaultAddress, SAFT_ALLOCATION); mint(_reserveVaultAddress, RESERVE_ALLOCATION); mint(_advisorVestingAddress, ADVISOR_ALLOCATION); mint(_teamVestingAddress, TEAM_ALLOCATION); addManager(newOwner); addManager(crowdsaleContractAddress); addMinter(crowdsaleContractAddress); _removeManager(msg.sender); _removeMinter(msg.sender); transferOwnership(newOwner); } }
Return the historical balance of an account at a certain time owner The address of the token holder blockNumber The block number of the moment when token supply is queried return The balance of the queried token holder at "blockNumber"/
function balanceOfAt(address owner, uint256 blockNumber) public view returns (uint256) { return _snapshotBalances[owner].getValueAt(blockNumber); }
15,846,193
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./ERC1155.sol"; import "../../utils/LibBytes.sol"; import "../../utils/SignatureValidator.sol"; /** * @dev ERC-1155 with native metatransaction methods. These additional functions allow users * to presign function calls and allow third parties to execute these on their behalf. * * TO DO: * - Add 1 tx wrap (via CREATE2) * - Split contract for better oganization * - Review function descriptions * - Review error messages in 1155 * - Add meta-withdraw * - Signature 0x19 pre-fix? * - EIP-712 encoding * * COULD DO: * - Async nonces * - Cancellable nonces * - Support contract validator signature type * */ contract ERC1155Meta is ERC1155, SignatureValidator { using LibBytes for bytes; /***********************************| | Variables and Structs | |__________________________________*/ // Gas Receipt struct GasReceipt { uint256 gasLimit; // Max amount of gas that can be reimbursed uint256 baseGas; // Base gas cost (includes things like 21k, data encoding, etc.) uint256 gasPrice; // Price denominated in token X per gas unit uint256 feeToken; // Token to pay for gas as `uint256(tokenAddress)`, where 0x0 is MetaETH address payable feeRecipient; // Address to send payment to } // Signature nonce per address mapping (address => uint256) internal nonces; // Meta transfer identifier (no gas reimbursement): // bytes4(keccak256("metaSafeTransferFrom(address,address,uint256,uint256,bytes)")); bytes4 internal constant METATRANSFER_FLAG = 0xebc71fa5; // Meta transfer identifier (with gas reimbursement): // bytes4(keccak256("metaSafeTransferFromWithGasReceipt(address,address,uint256,uint256,bytes)")); bytes4 internal constant METATRANSFER_WITHOUT_GAS_RECEIPT_FLAG = 0x3fed7708; /****************************************| | Public Meta Transfer Functions | |_______________________________________*/ /** * @dev Allow anyone with a valid signature to transfer on the bahalf of _from * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _id Token id to update balance of - For this implementation, via `uint256(tokenAddress)`. * @param _value The amount of tokens of provided token ID to be transferred * @param _data Encodes a meta transfer indicator, signature, gas payment receipt and extra transfer data. * _data should be encoded as (bytes4 METATRANSFER_FLAG, (bytes32 r, bytes32 s, uint8 v, SignatureType sigType), (GasReceipt g, bytes data)) * i.e. high level encoding should be (bytes4, bytes, bytes), where the latter bytes array is a nested bytes array * METATRANSFER_FLAG should be 0xebc71fa5 for meta transfer with gas reimbursement * METATRANSFER_FLAG should be 0x3fed7708 for meta transfer WITHOUT gas reimbursement (and hence without gasReceipt) */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) public { require(_to != address(0), "ERC1155Meta#safeTransferFrom: INVALID_RECIPIENT"); // Starting gas value uint256 startGas = gasleft(); if (_data.length < 4) { super.safeTransferFrom(_from, _to, _id, _value, _data); } else { // Get metatransaction tag bytes4 metaTag = _data.readBytes4(0); // Is NOT metaTransfer - (explicit check) if (metaTag != METATRANSFER_FLAG && metaTag != METATRANSFER_WITHOUT_GAS_RECEIPT_FLAG) { super.safeTransferFrom(_from, _to, _id, _value, _data); } else { bytes memory signedData; bytes memory transferData; GasReceipt memory gasReceipt; // If Gas receipt is being passed if (metaTag == METATRANSFER_FLAG) { signedData = _validateTransferSignature(_from, _to, _id, _value, _data); (gasReceipt, transferData) = abi.decode(signedData, (GasReceipt, bytes)); _safeTransferFrom(_from, _to, _id, _value, transferData); _transferGasFee(_from, startGas, gasReceipt); } else { transferData = _validateTransferSignature(_from, _to, _id, _value, _data); _safeTransferFrom(_from, _to, _id, _value, transferData); } } } } /** * @dev transfer objects from different ids to specified address * @param _from The address to batchTransfer objects from. * @param _to The address to batchTransfer objects to. * @param _ids Array of ids to update balance of - For this implementation, via `uint256(tokenAddress)` * @param _values Array of amount of object per id to be transferred. * @param _data Encodes a meta transfer indicator, signature, gas payment receipt and extra transfer data. * _data should be encoded as (bytes4 METATRANSFER_FLAG, (bytes32 r, bytes32 s, uint8 v, SignatureType sigType), (GasReceipt g, bytes data)) * i.e. high level encoding should be (bytes4, bytes, bytes), where the latter bytes array is a nested bytes array * METATRANSFER_FLAG should be 0xebc71fa5 for meta transfer with gas reimbursement * METATRANSFER_FLAG should be 0x3fed7708 for meta transfer WITHOUT gas reimbursement (and hence without gasReceipt) */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) public { // Requirements require(_to != address(0), "ERC1155Meta#safeBatchTransferFrom: INVALID_RECIPIENT"); // Starting gas value uint256 startGas = gasleft(); if (_data.length < 4) { super.safeBatchTransferFrom(_from, _to, _ids, _values, _data); } else { // Get metatransaction tag bytes4 metaTag = _data.readBytes4(0); // Is NOT metaTransfer - (explicit check) if (metaTag != METATRANSFER_FLAG && metaTag != METATRANSFER_WITHOUT_GAS_RECEIPT_FLAG) { super.safeBatchTransferFrom(_from, _to, _ids, _values, _data); } else { bytes memory signedData; bytes memory transferData; GasReceipt memory gasReceipt; // If Gas receipt is being passed if (metaTag == METATRANSFER_FLAG) { signedData = _validateBatchTransferSignature(_from, _to, _ids, _values, _data); (gasReceipt, transferData) = abi.decode(signedData, (GasReceipt, bytes)); // Update balances _safeBatchTransferFrom(_from, _to, _ids, _values, transferData); // Handle gas reimbursement _transferGasFee(_from, startGas, gasReceipt); } else { transferData = _validateBatchTransferSignature(_from, _to, _ids, _values, _data); _safeBatchTransferFrom(_from, _to, _ids, _values, transferData); } } } } /****************************************| | Signture Validation Functions | |_______________________________________*/ /** * @dev Verifies if a transfer signature is valid based on data and update nonce * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _id Token id to update balance of - For this implementation, via `uint256(tokenAddress)`. * @param _value The amount of tokens of provided token ID to be transferred * @param _data Encodes a meta transfer indicator, signature, gas payment receipt and extra transfer data. * _data should be encoded as (bytes4 METATRANSFER_FLAG, (bytes32 r, bytes32 s, uint8 v, SignatureType sigType), (GasReceipt g, bytes data)) * i.e. high level encoding should be (bytes4, bytes, bytes), where the latter bytes array is a nested bytes array */ function _validateTransferSignature( address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) internal returns (bytes memory signedData) { // Get signature and data to sign (bytes4 tag, bytes memory sig, bytes memory signedData) = abi.decode(_data, (bytes4, bytes, bytes)); // Get signer's currently available nonce uint256 nonce = nonces[_from]; // Get data that formed the hash bytes memory data = abi.encodePacked(address(this), _from, _to, _id, _value, nonce, signedData); // Verify if _from is the signer require(isValidSignature(_from, data, sig), "ERC1155Meta#_validateTransferSignature: INVALID_SIGNATURE"); //Update signature nonce nonces[_from] += 1; return signedData; } /** * @dev Verifies if a batch transfer signature is valid based on data and update nonce * @param _from The address to batchTransfer objects from. * @param _to The address to batchTransfer objects to. * @param _ids Array of ids to update balance of - For this implementation, via `uint256(tokenAddress)` * @param _values Array of amount of object per id to be transferred. * @param _data Encodes a meta transfer indicator, signature, gas payment receipt and extra transfer data. * _data should be encoded as (bytes4 METATRANSFER_FLAG, (bytes32 r, bytes32 s, uint8 v, SignatureType sigType), (GasReceipt g, bytes data)) * i.e. high level encoding should be (bytes4, bytes, bytes), where the latter bytes array is a nested bytes array */ function _validateBatchTransferSignature( address _from, address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) internal returns (bytes memory signedData) { // Get signature and data to sign (bytes4 tag, bytes memory sig, bytes memory signedData) = abi.decode(_data, (bytes4, bytes, bytes)); // Get signer's currently available nonce uint256 nonce = nonces[_from]; // Get data that formed the hash bytes memory data = abi.encodePacked(address(this), _from, _to, _ids, _values, nonce, signedData); // Verify if _from is the signer require(isValidSignature(_from, data, sig), "ERC1155Meta#_validateBatchTransferSignature: INVALID_SIGNATURE"); //Update signature nonce nonces[_from] += 1; return signedData; } /** * @dev Verifies if an approval is a signature is valid based on data * @param _owner Address that wants to set operator status _spender. * @param _operator The address which will act as an operator for _owner. * @param _approved _operator"s new operator status (true or false). * @param _data Encodes signature and gas payment receipt * _data should be encoded as ((bytes32 r, bytes32 s, uint8 v, SignatureType sigType), (GasReceipt g)) * i.e. high level encoding should be (bytes, bytes), where the latter bytes array is a nested bytes array */ function _validateApprovalSignature( address _owner, address _operator, bool _approved, bytes memory _data) internal returns (bytes memory signedData) { // Get signature and data to sign (bytes memory sig, bytes memory signedData) = abi.decode(_data, (bytes, bytes)); // Get signer's currently available nonce uint256 nonce = nonces[_owner]; // Get data that formed the hash bytes memory data = abi.encodePacked(address(this), _owner, _operator, _approved, nonce, signedData); // Verify if _owner is the signer require(isValidSignature(_owner, data, sig), "ERC1155Meta#_validateApprovalSignature: INVALID_SIGNATURE"); //Update signature nonce nonces[_owner] += 1; return signedData; } /** * @dev Returns the current nonce associated with a given address * @param _signer Address to query signature nonce for */ function getNonce(address _signer) external view returns (uint256 nonce) { return nonces[_signer]; } /***********************************| | Operator Functions | |__________________________________*/ /** * @dev Approve the passed address to spend on behalf of _from if valid signature is provided. * @param _owner Address that wants to set operator status _spender. * @param _operator The address which will act as an operator for _owner. * @param _approved _operator"s new operator status (true or false). * @param _isGasReimbursed Whether gas will be reimbursed or not, with vlid signature * @param _data Encodes signature and gas payment receipt * _data should be encoded as ((bytes32 r, bytes32 s, uint8 v, SignatureType sigType), (GasReceipt g)) * i.e. high level encoding should be (bytes, bytes), where the latter bytes array is a nested bytes array */ function metaSetApprovalForAll( address _owner, address _operator, bool _approved, bool _isGasReimbursed, bytes memory _data) public { // Starting gas value uint256 startGas = gasleft(); GasReceipt memory gasReceipt; // If gas reimbursement or not if (_isGasReimbursed) { bytes memory signedData = _validateApprovalSignature(_owner, _operator, _approved, _data); gasReceipt = abi.decode(signedData, (GasReceipt)); } else { _validateApprovalSignature(_owner, _operator, _approved, _data); } // Update operator status operators[_owner][_operator] = _approved; // Emit event emit ApprovalForAll(_owner, _operator, _approved); // Handle gas reimbursement if (_isGasReimbursed) { _transferGasFee(_owner, startGas, gasReceipt); } } /***********************************| | Gas Reimbursement Functions | |__________________________________*/ /** * @dev Will reimburse tx.origin or fee recipient for the gas spent execution a transaction * @param _from Address from which the payment will be made from * @param _startGas The gas amount left when gas counter started * @param _g GasReceipt object that contains gas reimbursement information */ function _transferGasFee(address _from, uint256 _startGas, GasReceipt memory _g) internal { // Amount of gas consumed uint256 gasUsed = _startGas.sub(gasleft()).add(_g.baseGas); // Reimburse up to gasLimit (instead of throwing) uint256 fee = gasUsed > _g.gasLimit ? _g.gasLimit.mul(_g.gasPrice): gasUsed.mul(_g.gasPrice); // If receiver is 0x0, then anyone can claim, otherwise, refund addresse provided address payable feeRecipient = _g.feeRecipient == address(0) ? tx.origin : _g.feeRecipient; // Paying back in MetaERC20 _safeTransferFrom(_from, feeRecipient, _g.feeToken, fee, ''); } }
Verifies if an approval is a signature is valid based on data _owner Address that wants to set operator status _spender. _operator The address which will act as an operator for _owner. _approved _operator"s new operator status (true or false). _data Encodes signature and gas payment receipt _data should be encoded as ((bytes32 r, bytes32 s, uint8 v, SignatureType sigType), (GasReceipt g)) i.e. high level encoding should be (bytes, bytes), where the latter bytes array is a nested bytes array/ Get signature and data to sign Get signer's currently available nonce Get data that formed the hash Verify if _owner is the signerUpdate signature nonce
function _validateApprovalSignature( address _owner, address _operator, bool _approved, bytes memory _data) internal returns (bytes memory signedData) { (bytes memory sig, bytes memory signedData) = abi.decode(_data, (bytes, bytes)); uint256 nonce = nonces[_owner]; bytes memory data = abi.encodePacked(address(this), _owner, _operator, _approved, nonce, signedData); require(isValidSignature(_owner, data, sig), "ERC1155Meta#_validateApprovalSignature: INVALID_SIGNATURE"); nonces[_owner] += 1; return signedData; }
7,239,195
pragma solidity ^0.5.11; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title Finalizable contract * @dev Lifecycle extension where an owner can do extra work after finishing. */ contract Finalizable is Ownable { using SafeMath for uint256; event Finalized(); bool private _isFinalized = false; /// @dev Throws if called before the contract is finalized. modifier onlyFinalized() { require(_isFinalized, "Finalizable: Contract not finalized"); _; } /// @dev Throws if called after the contract is finalized. modifier onlyNotFinalized() { require(!_isFinalized, "Finalizable: Contract already finalized"); _; } /// @return Whether contract is finalized. function isFinalized() public view returns (bool) { return _isFinalized; } /** * @dev Called by owner to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public onlyOwner onlyNotFinalized { _finalization(); emit Finalized(); _isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function _finalization() internal { // solhint-disable-line no-empty-blocks // override } }
solhint-disable-line no-empty-blocks
function _finalization() internal {
12,911,659
// King of the Ether Throne Contracts. // Copyright (c) 2016 Kieran Elby. Released under the MIT License. // Version 0.9.9.2, July 2016. // // See also http://www.kingoftheether.com and // https://github.com/kieranelby/KingOfTheEtherThrone . // // This file contains a number of contracts, of which only // these three are normally created: // // - Kingdom = maintains the throne for a kingdom // - World = runs the world, which is a collection of kingdoms // - KingdomFactory = used internally by the World contract // // The "Mixin" contracts (ThroneRulesMixin, ReentryProtectorMixin, // CarefulSenderMixin, FundsHolderMixin, MoneyRounderMixin, // NameableMixin) contain functions / data / structures used // by the three main contracts. // The ExposedInternalsForTesting contract is used by automated tests. /// @title Mixin to help avoid recursive-call attacks. contract ReentryProtectorMixin { // true if we are inside an external function bool reentryProtector; // Mark contract as having entered an external function. // Throws an exception if called twice with no externalLeave(). // For this to work, Contracts MUST: // - call externalEnter() at the start of each external function // - call externalLeave() at the end of each external function // - never use return statements in between enter and leave // - never call an external function from another function // WARN: serious risk of contract getting stuck if used wrongly. function externalEnter() internal { if (reentryProtector) { throw; } reentryProtector = true; } // Mark contract as having left an external function. // Do this after each call to externalEnter(). function externalLeave() internal { reentryProtector = false; } } /// @title Mixin to help send ether to untrusted addresses. contract CarefulSenderMixin { // Seems a reasonable amount for a well-written fallback function. uint constant suggestedExtraGasToIncludeWithSends = 23000; // Send `_valueWei` of our ether to `_toAddress`, including // `_extraGasIncluded` gas above the usual 2300 gas stipend // with the send call. // // This needs care because there is no way to tell if _toAddress // is externally owned or is another contract - and sending ether // to a contract address will invoke its fallback function; this // has three implications: // // 1) Danger of recursive attack. // The destination contract's fallback function (or another // contract it calls) may call back into this contract (including // our fallback function and external functions inherited, or into // other contracts in our stack), leading to unexpected behaviour. // Mitigations: // - protect all external functions against re-entry into // any of them (see ReentryProtectorMixin); // - program very defensively (e.g. debit balance before send). // // 2) Destination fallback function can fail. // If the destination contract's fallback function fails, ether // will not be sent and may be locked into the sending contract. // Unlike most errors, it will NOT cause this contract to throw. // Mitigations: // - check the return value from this function (see below). // // 3) Gas usage. // The destination fallback function will consume the gas supplied // in this transaction (which is fixed and set by the transaction // starter, though some clients do a good job of estimating it. // This is a problem for lottery-type contracts where one very // expensive-to-call receiving contract could 'poison' the lottery // contract by preventing it being invoked by another person who // cannot supply enough gas. // Mitigations: // - choose sensible value for _extraGasIncluded (by default // only 2300 gas is supplied to the destination function); // - if call fails consider whether to throw or to ring-fence // funds for later withdrawal. // // Returns: // // True if-and-only-if the send call was made and did not throw // an error. In this case, we will no longer own the _valueWei // ether. Note that we cannot get the return value of the fallback // function called (if any). // // False if the send was made but the destination fallback function // threw an error (or ran out of gas). If this hapens, we still own // _valueWei ether and the destination's actions were undone. // // This function should not normally throw an error unless: // - not enough gas to make the send/call // - max call stack depth reached // - insufficient ether // function carefulSendWithFixedGas( address _toAddress, uint _valueWei, uint _extraGasIncluded ) internal returns (bool success) { return _toAddress.call.value(_valueWei).gas(_extraGasIncluded)(); } } /// @title Mixin to help track who owns our ether and allow withdrawals. contract FundsHolderMixin is ReentryProtectorMixin, CarefulSenderMixin { // Record here how much wei is owned by an address. // Obviously, the entries here MUST be backed by actual ether // owned by the contract - we cannot enforce that in this mixin. mapping (address => uint) funds; event FundsWithdrawnEvent( address fromAddress, address toAddress, uint valueWei ); /// @notice Amount of ether held for `_address`. function fundsOf(address _address) constant returns (uint valueWei) { return funds[_address]; } /// @notice Send the caller (`msg.sender`) all ether they own. function withdrawFunds() { externalEnter(); withdrawFundsRP(); externalLeave(); } /// @notice Send `_valueWei` of the ether owned by the caller /// (`msg.sender`) to `_toAddress`, including `_extraGas` gas /// beyond the normal stipend. function withdrawFundsAdvanced( address _toAddress, uint _valueWei, uint _extraGas ) { externalEnter(); withdrawFundsAdvancedRP(_toAddress, _valueWei, _extraGas); externalLeave(); } /// @dev internal version of withdrawFunds() function withdrawFundsRP() internal { address fromAddress = msg.sender; address toAddress = fromAddress; uint allAvailableWei = funds[fromAddress]; withdrawFundsAdvancedRP( toAddress, allAvailableWei, suggestedExtraGasToIncludeWithSends ); } /// @dev internal version of withdrawFundsAdvanced(), also used /// by withdrawFundsRP(). function withdrawFundsAdvancedRP( address _toAddress, uint _valueWei, uint _extraGasIncluded ) internal { if (msg.value != 0) { throw; } address fromAddress = msg.sender; if (_valueWei > funds[fromAddress]) { throw; } funds[fromAddress] -= _valueWei; bool sentOk = carefulSendWithFixedGas( _toAddress, _valueWei, _extraGasIncluded ); if (!sentOk) { throw; } FundsWithdrawnEvent(fromAddress, _toAddress, _valueWei); } } /// @title Mixin to help make nicer looking ether amounts. contract MoneyRounderMixin { /// @notice Make `_rawValueWei` into a nicer, rounder number. /// @return A value that: /// - is no larger than `_rawValueWei` /// - is no smaller than `_rawValueWei` * 0.999 /// - has no more than three significant figures UNLESS the /// number is very small or very large in monetary terms /// (which we define as < 1 finney or > 10000 ether), in /// which case no precision will be lost. function roundMoneyDownNicely(uint _rawValueWei) constant internal returns (uint nicerValueWei) { if (_rawValueWei < 1 finney) { return _rawValueWei; } else if (_rawValueWei < 10 finney) { return 10 szabo * (_rawValueWei / 10 szabo); } else if (_rawValueWei < 100 finney) { return 100 szabo * (_rawValueWei / 100 szabo); } else if (_rawValueWei < 1 ether) { return 1 finney * (_rawValueWei / 1 finney); } else if (_rawValueWei < 10 ether) { return 10 finney * (_rawValueWei / 10 finney); } else if (_rawValueWei < 100 ether) { return 100 finney * (_rawValueWei / 100 finney); } else if (_rawValueWei < 1000 ether) { return 1 ether * (_rawValueWei / 1 ether); } else if (_rawValueWei < 10000 ether) { return 10 ether * (_rawValueWei / 10 ether); } else { return _rawValueWei; } } /// @notice Convert `_valueWei` into a whole number of finney. /// @return The smallest whole number of finney which is equal /// to or greater than `_valueWei` when converted to wei. /// WARN: May be incorrect if `_valueWei` is above 2**254. function roundMoneyUpToWholeFinney(uint _valueWei) constant internal returns (uint valueFinney) { return (1 finney + _valueWei - 1 wei) / 1 finney; } } /// @title Mixin to help allow users to name things. contract NameableMixin { // String manipulation is expensive in the EVM; keep things short. uint constant minimumNameLength = 1; uint constant maximumNameLength = 25; string constant nameDataPrefix = "NAME:"; /// @notice Check if `_name` is a reasonable choice of name. /// @return True if-and-only-if `_name_` meets the criteria /// below, or false otherwise: /// - no fewer than 1 character /// - no more than 25 characters /// - no characters other than: /// - "roman" alphabet letters (A-Z and a-z) /// - western digits (0-9) /// - "safe" punctuation: ! ( ) - . _ SPACE /// - at least one non-punctuation character /// Note that we deliberately exclude characters which may cause /// security problems for websites and databases if escaping is /// not performed correctly, such as < > " and '. /// Apologies for the lack of non-English language support. function validateNameInternal(string _name) constant internal returns (bool allowed) { bytes memory nameBytes = bytes(_name); uint lengthBytes = nameBytes.length; if (lengthBytes < minimumNameLength || lengthBytes > maximumNameLength) { return false; } bool foundNonPunctuation = false; for (uint i = 0; i < lengthBytes; i++) { byte b = nameBytes[i]; if ( (b >= 48 && b <= 57) || // 0 - 9 (b >= 65 && b <= 90) || // A - Z (b >= 97 && b <= 122) // a - z ) { foundNonPunctuation = true; continue; } if ( b == 32 || // space b == 33 || // ! b == 40 || // ( b == 41 || // ) b == 45 || // - b == 46 || // . b == 95 // _ ) { continue; } return false; } return foundNonPunctuation; } // Extract a name from bytes `_data` (presumably from `msg.data`), // or throw an exception if the data is not in the expected format. // // We want to make it easy for people to name things, even if // they're not comfortable calling functions on contracts. // // So we allow names to be sent to the fallback function encoded // as message data. // // Unfortunately, the way the Ethereum Function ABI works means we // must be careful to avoid clashes between message data that // represents our names and message data that represents a call // to an external function - otherwise: // a) some names won't be usable; // b) small possibility of a phishing attack where users are // tricked into using certain names which cause an external // function call - e.g. if the data sent to the contract is // keccak256("withdrawFunds()") then a withdrawal will occur. // // So we require a prefix "NAME:" at the start of the name (encoded // in ASCII) when sent via the fallback function - this prefix // doesn't clash with any external function signature hashes. // // e.g. web3.fromAscii('NAME:' + 'Joe Bloggs') // // WARN: this does not check the name for "reasonableness"; // use validateNameInternal() for that. // function extractNameFromData(bytes _data) constant internal returns (string extractedName) { // check prefix present uint expectedPrefixLength = (bytes(nameDataPrefix)).length; if (_data.length < expectedPrefixLength) { throw; } uint i; for (i = 0; i < expectedPrefixLength; i++) { if ((bytes(nameDataPrefix))[i] != _data[i]) { throw; } } // copy data after prefix uint payloadLength = _data.length - expectedPrefixLength; if (payloadLength < minimumNameLength || payloadLength > maximumNameLength) { throw; } string memory name = new string(payloadLength); for (i = 0; i < payloadLength; i++) { (bytes(name))[i] = _data[expectedPrefixLength + i]; } return name; } // Turn a short name into a "fuzzy hash" with the property // that extremely similar names will have the same fuzzy hash. // // This is useful to: // - stop people choosing names which differ only in case or // punctuation and would lead to confusion. // - faciliate searching by name without needing exact match // // For example, these names all have the same fuzzy hash: // // "Banana" // "BANANA" // "Ba-na-na" // " banana " // "Banana .. so long the end is ignored" // // On the other hand, "Banana1" and "A Banana" are different to // the above. // // WARN: this is likely to work poorly on names that do not meet // the validateNameInternal() test. // function computeNameFuzzyHash(string _name) constant internal returns (uint fuzzyHash) { bytes memory nameBytes = bytes(_name); uint h = 0; uint len = nameBytes.length; if (len > maximumNameLength) { len = maximumNameLength; } for (uint i = 0; i < len; i++) { uint mul = 128; byte b = nameBytes[i]; uint ub = uint(b); if (b >= 48 && b <= 57) { // 0-9 h = h * mul + ub; } else if (b >= 65 && b <= 90) { // A-Z h = h * mul + ub; } else if (b >= 97 && b <= 122) { // fold a-z to A-Z uint upper = ub - 32; h = h * mul + upper; } else { // ignore others } } return h; } } /// @title Mixin to help define the rules of a throne. contract ThroneRulesMixin { // See World.createKingdom(..) for documentation. struct ThroneRules { uint startingClaimPriceWei; uint maximumClaimPriceWei; uint claimPriceAdjustPercent; uint curseIncubationDurationSeconds; uint commissionPerThousand; } } /// @title Maintains the throne of a kingdom. contract Kingdom is ReentryProtectorMixin, CarefulSenderMixin, FundsHolderMixin, MoneyRounderMixin, NameableMixin, ThroneRulesMixin { // e.g. "King of the Ether" string public kingdomName; // The World contract used to create this kingdom, or 0x0 if none. address public world; // The rules that govern this kingdom - see ThroneRulesMixin. ThroneRules public rules; // Someone who has ruled (or is ruling) our kingdom. struct Monarch { // where to send their compensation address compensationAddress; // their name string name; // when they became our ruler uint coronationTimestamp; // the claim price paid (excluding any over-payment) uint claimPriceWei; // the compensation sent to or held for them so far uint compensationWei; } // The first ruler is number 1; the zero-th entry is a dummy entry. Monarch[] public monarchsByNumber; // The topWizard earns half the commission. // They are normally the owner of the World contract. address public topWizard; // The subWizard earns half the commission. // They are normally the creator of this Kingdom. // The topWizard and subWizard can be the same address. address public subWizard; // NB: we also have a `funds` mapping from FundsHolderMixin, // and a rentryProtector from ReentryProtectorMixin. event ThroneClaimedEvent(uint monarchNumber); event CompensationSentEvent(address toAddress, uint valueWei); event CompensationFailEvent(address toAddress, uint valueWei); event CommissionEarnedEvent(address byAddress, uint valueWei); event WizardReplacedEvent(address oldWizard, address newWizard); // NB: we also have a `FundsWithdrawnEvent` from FundsHolderMixin // WARN - does NOT validate arguments; you MUST either call // KingdomFactory.validateProposedThroneRules() or create // the Kingdom via KingdomFactory/World's createKingdom(). // See World.createKingdom(..) for parameter documentation. function Kingdom( string _kingdomName, address _world, address _topWizard, address _subWizard, uint _startingClaimPriceWei, uint _maximumClaimPriceWei, uint _claimPriceAdjustPercent, uint _curseIncubationDurationSeconds, uint _commissionPerThousand ) { kingdomName = _kingdomName; world = _world; topWizard = _topWizard; subWizard = _subWizard; rules = ThroneRules( _startingClaimPriceWei, _maximumClaimPriceWei, _claimPriceAdjustPercent, _curseIncubationDurationSeconds, _commissionPerThousand ); // We number the monarchs starting from 1; it's sometimes useful // to use zero = invalid, so put in a dummy entry for number 0. monarchsByNumber.push( Monarch( 0, "", 0, 0, 0 ) ); } function numberOfMonarchs() constant returns (uint totalCount) { // zero-th entry is invalid return monarchsByNumber.length - 1; } // False if either there are no monarchs, or if the latest monarch // has reigned too long and been struck down by the curse. function isLivingMonarch() constant returns (bool alive) { if (numberOfMonarchs() == 0) { return false; } uint reignStartedTimestamp = latestMonarchInternal().coronationTimestamp; if (now < reignStartedTimestamp) { // Should not be possible, think miners reject blocks with // timestamps that go backwards? But some drift possible and // it needs handling for unsigned overflow audit checks ... return true; } uint elapsedReignDurationSeconds = now - reignStartedTimestamp; if (elapsedReignDurationSeconds > rules.curseIncubationDurationSeconds) { return false; } else { return true; } } /// @notice How much you must pay to claim the throne now, in wei. function currentClaimPriceWei() constant returns (uint priceInWei) { if (!isLivingMonarch()) { return rules.startingClaimPriceWei; } else { uint lastClaimPriceWei = latestMonarchInternal().claimPriceWei; // no danger of overflow because claim price never gets that high uint newClaimPrice = (lastClaimPriceWei * (100 + rules.claimPriceAdjustPercent)) / 100; newClaimPrice = roundMoneyDownNicely(newClaimPrice); if (newClaimPrice < rules.startingClaimPriceWei) { newClaimPrice = rules.startingClaimPriceWei; } if (newClaimPrice > rules.maximumClaimPriceWei) { newClaimPrice = rules.maximumClaimPriceWei; } return newClaimPrice; } } /// @notice How much you must pay to claim the throne now, in finney. function currentClaimPriceInFinney() constant returns (uint priceInFinney) { uint valueWei = currentClaimPriceWei(); return roundMoneyUpToWholeFinney(valueWei); } /// @notice Check if a name can be used as a monarch name. /// @return True if the name satisfies the criteria of: /// - no fewer than 1 character /// - no more than 25 characters /// - no characters other than: /// - "roman" alphabet letters (A-Z and a-z) /// - western digits (0-9) /// - "safe" punctuation: ! ( ) - . _ SPACE function validateProposedMonarchName(string _monarchName) constant returns (bool allowed) { return validateNameInternal(_monarchName); } // Get details of the latest monarch (even if they are dead). // // We don't expose externally because returning structs is not well // supported in the ABI (strange that monarchsByNumber array works // fine though). Note that the reference returned is writable - it // can be used to update details of the latest monarch. // WARN: you should check numberOfMonarchs() > 0 first. function latestMonarchInternal() constant internal returns (Monarch storage monarch) { return monarchsByNumber[monarchsByNumber.length - 1]; } /// @notice Claim throne by sending funds to the contract. /// Any future compensation earned will be sent to the sender's /// address (`msg.sender`). /// Sending from a contract is not recommended unless you know /// what you're doing (and you've tested it). /// If no message data is supplied, the throne will be claimed in /// the name of "Anonymous". To supply a name, send data encoded /// using web3.fromAscii('NAME:' + 'your_chosen_valid_name'). /// Sender must include payment equal to currentClaimPriceWei(). /// Will consume up to ~300,000 gas. /// Will throw an error if: /// - name is invalid (see `validateProposedMonarchName(string)`) /// - payment is too low or too high /// Produces events: /// - `ThroneClaimedEvent` /// - `CompensationSentEvent` / `CompensationFailEvent` /// - `CommissionEarnedEvent` function () { externalEnter(); fallbackRP(); externalLeave(); } /// @notice Claim throne in the given `_monarchName`. /// Any future compensation earned will be sent to the caller's /// address (`msg.sender`). /// Caller must include payment equal to currentClaimPriceWei(). /// Calling from a contract is not recommended unless you know /// what you're doing (and you've tested it). /// Will consume up to ~300,000 gas. /// Will throw an error if: /// - name is invalid (see `validateProposedMonarchName(string)`) /// - payment is too low or too high /// Produces events: /// - `ThroneClaimedEvent /// - `CompensationSentEvent` / `CompensationFailEvent` /// - `CommissionEarnedEvent` function claimThrone(string _monarchName) { externalEnter(); claimThroneRP(_monarchName); externalLeave(); } /// @notice Used by either the topWizard or subWizard to transfer /// all rights to future commissions to the `_replacement` wizard. /// WARN: The original wizard retains ownership of any past /// commission held for them in the `funds` mapping, which they /// can still withdraw. /// Produces event WizardReplacedEvent. function replaceWizard(address _replacement) { externalEnter(); replaceWizardRP(_replacement); externalLeave(); } function fallbackRP() internal { if (msg.data.length == 0) { claimThroneRP("Anonymous"); } else { string memory _monarchName = extractNameFromData(msg.data); claimThroneRP(_monarchName); } } function claimThroneRP( string _monarchName ) internal { address _compensationAddress = msg.sender; if (!validateNameInternal(_monarchName)) { throw; } if (_compensationAddress == 0 || _compensationAddress == address(this)) { throw; } uint paidWei = msg.value; uint priceWei = currentClaimPriceWei(); if (paidWei < priceWei) { throw; } // Make it easy for people to pay using a whole number of finney, // which could be a teeny bit higher than the raw wei value. uint excessWei = paidWei - priceWei; if (excessWei > 1 finney) { throw; } uint compensationWei; uint commissionWei; if (!isLivingMonarch()) { // dead men get no compensation commissionWei = paidWei; compensationWei = 0; } else { commissionWei = (paidWei * rules.commissionPerThousand) / 1000; compensationWei = paidWei - commissionWei; } if (commissionWei != 0) { recordCommissionEarned(commissionWei); } if (compensationWei != 0) { compensateLatestMonarch(compensationWei); } // In case of any teeny excess, we use the official price here // since that should determine the new claim price, not paidWei. monarchsByNumber.push(Monarch( _compensationAddress, _monarchName, now, priceWei, 0 )); ThroneClaimedEvent(monarchsByNumber.length - 1); } function replaceWizardRP(address replacement) internal { if (msg.value != 0) { throw; } bool replacedOk = false; address oldWizard; if (msg.sender == topWizard) { oldWizard = topWizard; topWizard = replacement; WizardReplacedEvent(oldWizard, replacement); replacedOk = true; } // Careful - topWizard and subWizard can be the same address, // in which case we must replace both. if (msg.sender == subWizard) { oldWizard = subWizard; subWizard = replacement; WizardReplacedEvent(oldWizard, replacement); replacedOk = true; } if (!replacedOk) { throw; } } // Allow commission funds to build up in contract for the wizards // to withdraw (carefully ring-fenced). function recordCommissionEarned(uint _commissionWei) internal { // give the subWizard any "odd" single wei uint topWizardWei = _commissionWei / 2; uint subWizardWei = _commissionWei - topWizardWei; funds[topWizard] += topWizardWei; CommissionEarnedEvent(topWizard, topWizardWei); funds[subWizard] += subWizardWei; CommissionEarnedEvent(subWizard, subWizardWei); } // Send compensation to latest monarch (or hold funds for them // if cannot through no fault of current caller). function compensateLatestMonarch(uint _compensationWei) internal { address compensationAddress = latestMonarchInternal().compensationAddress; // record that we compensated them latestMonarchInternal().compensationWei = _compensationWei; // WARN: if the latest monarch is a contract whose fallback // function needs more 25300 gas than then they will NOT // receive compensation automatically. bool sentOk = carefulSendWithFixedGas( compensationAddress, _compensationWei, suggestedExtraGasToIncludeWithSends ); if (sentOk) { CompensationSentEvent(compensationAddress, _compensationWei); } else { // This should only happen if the latest monarch is a contract // whose fallback-function failed or ran out of gas (despite // us including a fair amount of gas). // We do not throw since we do not want the throne to get // 'stuck' (it's not the new usurpers fault) - instead save // the funds we could not send so can be claimed later. // Their monarch contract would need to have been designed // to call our withdrawFundsAdvanced(..) function mind you. funds[compensationAddress] += _compensationWei; CompensationFailEvent(compensationAddress, _compensationWei); } } } /// @title Used by the World contract to create Kingdom instances. /// @dev Mostly exists so topWizard can potentially replace this /// contract to modify the Kingdom contract and/or rule validation /// logic to be used for *future* Kingdoms created by the World. /// We do not implement rentry protection because we don't send/call. /// We do not charge a fee here - but if you bypass the World then /// you won't be listed on the official World page of course. contract KingdomFactory { function KingdomFactory() { } function () { // this contract should never have a balance throw; } // See World.createKingdom(..) for parameter documentation. function validateProposedThroneRules( uint _startingClaimPriceWei, uint _maximumClaimPriceWei, uint _claimPriceAdjustPercent, uint _curseIncubationDurationSeconds, uint _commissionPerThousand ) constant returns (bool allowed) { // I suppose there is a danger that massive deflation/inflation could // change the real-world sanity of these checks, but in that case we // can deploy a new factory and update the world. if (_startingClaimPriceWei < 1 finney || _startingClaimPriceWei > 100 ether) { return false; } if (_maximumClaimPriceWei < 1 ether || _maximumClaimPriceWei > 100000 ether) { return false; } if (_startingClaimPriceWei * 20 > _maximumClaimPriceWei) { return false; } if (_claimPriceAdjustPercent < 1 || _claimPriceAdjustPercent > 900) { return false; } if (_curseIncubationDurationSeconds < 2 hours || _curseIncubationDurationSeconds > 10000 days) { return false; } if (_commissionPerThousand < 10 || _commissionPerThousand > 100) { return false; } return true; } /// @notice Create a new Kingdom. Normally called by World contract. /// WARN: Does NOT validate the _kingdomName or _world arguments. /// Will consume up to 1,800,000 gas (!) /// Will throw an error if: /// - rules invalid (see validateProposedThroneRules) /// - wizard addresses "obviously" wrong /// - out of gas quite likely (perhaps in future should consider /// using solidity libraries to reduce Kingdom size?) // See World.createKingdom(..) for parameter documentation. function createKingdom( string _kingdomName, address _world, address _topWizard, address _subWizard, uint _startingClaimPriceWei, uint _maximumClaimPriceWei, uint _claimPriceAdjustPercent, uint _curseIncubationDurationSeconds, uint _commissionPerThousand ) returns (Kingdom newKingdom) { if (msg.value > 0) { // this contract should never have a balance throw; } // NB: topWizard and subWizard CAN be the same as each other. if (_topWizard == 0 || _subWizard == 0) { throw; } if (_topWizard == _world || _subWizard == _world) { throw; } if (!validateProposedThroneRules( _startingClaimPriceWei, _maximumClaimPriceWei, _claimPriceAdjustPercent, _curseIncubationDurationSeconds, _commissionPerThousand )) { throw; } return new Kingdom( _kingdomName, _world, _topWizard, _subWizard, _startingClaimPriceWei, _maximumClaimPriceWei, _claimPriceAdjustPercent, _curseIncubationDurationSeconds, _commissionPerThousand ); } } /// @title Runs the world, which is a collection of Kingdoms. contract World is ReentryProtectorMixin, NameableMixin, MoneyRounderMixin, FundsHolderMixin, ThroneRulesMixin { // The topWizard runs the world. They charge for the creation of // kingdoms and become the topWizard in each kingdom created. address public topWizard; // How much one must pay to create a new kingdom (in wei). // Can be changed by the topWizard. uint public kingdomCreationFeeWei; struct KingdomListing { uint kingdomNumber; string kingdomName; address kingdomContract; address kingdomCreator; uint creationTimestamp; address kingdomFactoryUsed; } // The first kingdom is number 1; the zero-th entry is a dummy. KingdomListing[] public kingdomsByNumber; // For safety, we cap just how high the price can get. // Can be changed by the topWizard, though it will only affect // kingdoms created after that. uint public maximumClaimPriceWei; // Helper contract for creating Kingdom instances. Can be // upgraded by the topWizard (won't affect existing ones). KingdomFactory public kingdomFactory; // Avoids duplicate kingdom names and allows searching by name. mapping (uint => uint) kingdomNumbersByfuzzyHash; // NB: we also have a `funds` mapping from FundsHolderMixin, // and a rentryProtector from ReentryProtectorMixin. event KingdomCreatedEvent(uint kingdomNumber); event CreationFeeChangedEvent(uint newFeeWei); event FactoryChangedEvent(address newFactory); event WizardReplacedEvent(address oldWizard, address newWizard); // NB: we also have a `FundsWithdrawnEvent` from FundsHolderMixin // Create the world with no kingdoms yet. // Costs about 1.9M gas to deploy. function World( address _topWizard, uint _kingdomCreationFeeWei, KingdomFactory _kingdomFactory, uint _maximumClaimPriceWei ) { if (_topWizard == 0) { throw; } if (_maximumClaimPriceWei < 1 ether) { throw; } topWizard = _topWizard; kingdomCreationFeeWei = _kingdomCreationFeeWei; kingdomFactory = _kingdomFactory; maximumClaimPriceWei = _maximumClaimPriceWei; // We number the kingdoms starting from 1 since it's sometimes // useful to use zero = invalid. Create dummy zero-th entry. kingdomsByNumber.push(KingdomListing(0, "", 0, 0, 0, 0)); } function numberOfKingdoms() constant returns (uint totalCount) { return kingdomsByNumber.length - 1; } /// @return index into kingdomsByNumber if found, or zero if not. function findKingdomCalled(string _kingdomName) constant returns (uint kingdomNumber) { uint fuzzyHash = computeNameFuzzyHash(_kingdomName); return kingdomNumbersByfuzzyHash[fuzzyHash]; } /// @notice Check if a name can be used as a kingdom name. /// @return True if the name satisfies the criteria of: /// - no fewer than 1 character /// - no more than 25 characters /// - no characters other than: /// - "roman" alphabet letters (A-Z and a-z) /// - western digits (0-9) /// - "safe" punctuation: ! ( ) - . _ SPACE /// /// WARN: does not check if the name is already in use; /// use `findKingdomCalled(string)` for that afterwards. function validateProposedKingdomName(string _kingdomName) constant returns (bool allowed) { return validateNameInternal(_kingdomName); } // Check if rules would be allowed for a new custom Kingdom. // Typically used before calling `createKingdom(...)`. function validateProposedThroneRules( uint _startingClaimPriceWei, uint _claimPriceAdjustPercent, uint _curseIncubationDurationSeconds, uint _commissionPerThousand ) constant returns (bool allowed) { return kingdomFactory.validateProposedThroneRules( _startingClaimPriceWei, maximumClaimPriceWei, _claimPriceAdjustPercent, _curseIncubationDurationSeconds, _commissionPerThousand ); } // How much one must pay to create a new kingdom (in finney). // Can be changed by the topWizard. function kingdomCreationFeeInFinney() constant returns (uint feeInFinney) { return roundMoneyUpToWholeFinney(kingdomCreationFeeWei); } // Reject funds sent to the contract - wizards who cannot interact // with it via the API won't be able to withdraw their commission. function () { throw; } /// @notice Create a new kingdom using custom rules. /// @param _kingdomName \ /// e.g. "King of the Ether Throne" /// @param _startingClaimPriceWei \ /// How much it will cost the first monarch to claim the throne /// (and also the price after the death of a monarch). /// @param _claimPriceAdjustPercent \ /// Percentage increase after each claim - e.g. if claim price /// was 200 ETH, and `_claimPriceAdjustPercent` is 50, the next /// claim price will be 200 ETH + (50% of 200 ETH) => 300 ETH. /// @param _curseIncubationDurationSeconds \ /// The maximum length of a time a monarch can rule before the /// curse strikes and they are removed without compensation. /// @param _commissionPerThousand \ /// How much of each payment is given to the wizards to share, /// expressed in parts per thousand - e.g. 25 means 25/1000, /// or 2.5%. /// /// Caller must include payment equal to kingdomCreationFeeWei. /// The caller will become the 'sub-wizard' and will earn half /// any commission charged by the Kingdom. Note however they /// will need to call withdrawFunds() on the Kingdom contract /// to get their commission - it's not send automatically. /// /// Will consume up to 1,900,000 gas (!) /// Will throw an error if: /// - name is invalid (see `validateProposedKingdomName(string)`) /// - name is already in use (see `findKingdomCalled(string)`) /// - rules are invalid (see `validateProposedKingdomRules(...)`) /// - payment is too low or too high /// - insufficient gas (quite likely!) /// Produces event KingdomCreatedEvent. function createKingdom( string _kingdomName, uint _startingClaimPriceWei, uint _claimPriceAdjustPercent, uint _curseIncubationDurationSeconds, uint _commissionPerThousand ) { externalEnter(); createKingdomRP( _kingdomName, _startingClaimPriceWei, _claimPriceAdjustPercent, _curseIncubationDurationSeconds, _commissionPerThousand ); externalLeave(); } /// @notice Used by topWizard to transfer all rights to future /// fees and future kingdom wizardships to `_replacement` wizard. /// WARN: The original wizard retains ownership of any past fees /// held for them in the `funds` mapping, which they can still /// withdraw. They also remain topWizard in any existing Kingdoms. /// Produces event WizardReplacedEvent. function replaceWizard(address _replacement) { externalEnter(); replaceWizardRP(_replacement); externalLeave(); } /// @notice Used by topWizard to vary the fee for creating kingdoms. function setKingdomCreationFeeWei(uint _kingdomCreationFeeWei) { externalEnter(); setKingdomCreationFeeWeiRP(_kingdomCreationFeeWei); externalLeave(); } /// @notice Used by topWizard to vary the cap on claim price. function setMaximumClaimPriceWei(uint _maximumClaimPriceWei) { externalEnter(); setMaximumClaimPriceWeiRP(_maximumClaimPriceWei); externalLeave(); } /// @notice Used by topWizard to vary the factory contract which /// will be used to create future Kingdoms. function setKingdomFactory(KingdomFactory _kingdomFactory) { externalEnter(); setKingdomFactoryRP(_kingdomFactory); externalLeave(); } function createKingdomRP( string _kingdomName, uint _startingClaimPriceWei, uint _claimPriceAdjustPercent, uint _curseIncubationDurationSeconds, uint _commissionPerThousand ) internal { address subWizard = msg.sender; if (!validateNameInternal(_kingdomName)) { throw; } uint newKingdomNumber = kingdomsByNumber.length; checkUniqueAndRegisterNewKingdomName( _kingdomName, newKingdomNumber ); uint paidWei = msg.value; if (paidWei < kingdomCreationFeeWei) { throw; } // Make it easy for people to pay using a whole number of finney, // which could be a teeny bit higher than the raw wei value. uint excessWei = paidWei - kingdomCreationFeeWei; if (excessWei > 1 finney) { throw; } funds[topWizard] += paidWei; // This will perform rule validation. Kingdom kingdomContract = kingdomFactory.createKingdom( _kingdomName, address(this), topWizard, subWizard, _startingClaimPriceWei, maximumClaimPriceWei, _claimPriceAdjustPercent, _curseIncubationDurationSeconds, _commissionPerThousand ); kingdomsByNumber.push(KingdomListing( newKingdomNumber, _kingdomName, kingdomContract, msg.sender, now, kingdomFactory )); } function replaceWizardRP(address replacement) internal { if (msg.sender != topWizard) { throw; } if (msg.value != 0) { throw; } address oldWizard = topWizard; topWizard = replacement; WizardReplacedEvent(oldWizard, replacement); } function setKingdomCreationFeeWeiRP(uint _kingdomCreationFeeWei) internal { if (msg.sender != topWizard) { throw; } if (msg.value != 0) { throw; } kingdomCreationFeeWei = _kingdomCreationFeeWei; CreationFeeChangedEvent(kingdomCreationFeeWei); } function setMaximumClaimPriceWeiRP(uint _maximumClaimPriceWei) internal { if (msg.sender != topWizard) { throw; } if (_maximumClaimPriceWei < 1 ether) { throw; } maximumClaimPriceWei = _maximumClaimPriceWei; } function setKingdomFactoryRP(KingdomFactory _kingdomFactory) internal { if (msg.sender != topWizard) { throw; } if (msg.value != 0) { throw; } kingdomFactory = _kingdomFactory; FactoryChangedEvent(kingdomFactory); } // If there is no existing kingdom called `_kingdomName`, create // a record mapping that name to kingdom no. `_newKingdomNumber`. // Throws an error if an existing kingdom with the same (or // fuzzily similar - see computeNameFuzzyHash) name exists. function checkUniqueAndRegisterNewKingdomName( string _kingdomName, uint _newKingdomNumber ) internal { uint fuzzyHash = computeNameFuzzyHash(_kingdomName); if (kingdomNumbersByfuzzyHash[fuzzyHash] != 0) { throw; } kingdomNumbersByfuzzyHash[fuzzyHash] = _newKingdomNumber; } } /// @title Used on the testnet to allow automated testing of internals. contract ExposedInternalsForTesting is MoneyRounderMixin, NameableMixin { function roundMoneyDownNicelyET(uint _rawValueWei) constant returns (uint nicerValueWei) { return roundMoneyDownNicely(_rawValueWei); } function roundMoneyUpToWholeFinneyET(uint _valueWei) constant returns (uint valueFinney) { return roundMoneyUpToWholeFinney(_valueWei); } function validateNameInternalET(string _name) constant returns (bool allowed) { return validateNameInternal(_name); } function extractNameFromDataET(bytes _data) constant returns (string extractedName) { return extractNameFromData(_data); } function computeNameFuzzyHashET(string _name) constant returns (uint fuzzyHash) { return computeNameFuzzyHash(_name); } }
Careful - topWizard and subWizard can be the same address, in which case we must replace both.
function replaceWizardRP(address replacement) internal { if (msg.value != 0) { throw; } bool replacedOk = false; address oldWizard; if (msg.sender == topWizard) { oldWizard = topWizard; topWizard = replacement; WizardReplacedEvent(oldWizard, replacement); replacedOk = true; } if (msg.sender == subWizard) { oldWizard = subWizard; subWizard = replacement; WizardReplacedEvent(oldWizard, replacement); replacedOk = true; } if (!replacedOk) { throw; } }
5,425,048
pragma solidity ^0.4.14; contract TravellingFreeToken { /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function TravellingFreeToken( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /* Send coins */ function transfer(address _to, uint256 _value) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } }
Allow another contract to spend some tokens in your behalf /
function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; return true; }
7,971,320
/** *Submitted for verification at Etherscan.io on 2021-03-15 */ /** *Submitted for verification at Etherscan.io on 2021-03-15 */ // Sources flattened with hardhat v2.0.11 https://hardhat.org // File contracts/interfaces/Realitio.sol interface Realitio { // mapping(bytes32 => Question) public questions; /// @notice Ask a new question without a bounty and return the ID /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @dev Calling without the token param will only work if there is no arbitrator-set question fee. /// @dev This has the same function signature as askQuestion() in the non-ERC20 version, which is optionally payable. /// @param template_id The ID number of the template the question will use /// @param question A string containing the parameters that will be passed into the template to make the question /// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute /// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer /// @param opening_ts If set, the earliest time it should be possible to answer the question. /// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question. /// @return The ID of the newly-created question, created deterministically. function askQuestion( uint256 template_id, string calldata question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce ) external returns (bytes32); /// @notice Report whether the answer to the specified question is finalized /// @param question_id The ID of the question /// @return Return true if finalized function isFinalized(bytes32 question_id) view external returns (bool); /// @notice Return the final answer to the specified question, or revert if there isn't one /// @param question_id The ID of the question /// @return The answer formatted as a bytes32 function resultFor(bytes32 question_id) external view returns (bytes32); /// @notice Returns the timestamp at which the question will be/was finalized /// @param question_id The ID of the question function getFinalizeTS(bytes32 question_id) external view returns (uint32); /// @notice Returns whether the question is pending arbitration /// @param question_id The ID of the question function isPendingArbitration(bytes32 question_id) external view returns (bool); /// @notice Create a reusable template, which should be a JSON document. /// Placeholders should use gettext() syntax, eg %s. /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @param content The template content /// @return The ID of the newly-created template, which is created sequentially. function createTemplate(string calldata content) external returns (uint256); /// @notice Returns the highest bond posted so far for a question /// @param question_id The ID of the question function getBond(bytes32 question_id) external view returns (uint256); /// @notice Returns the questions's content hash, identifying the question content /// @param question_id The ID of the question function getContentHash(bytes32 question_id) external view returns (bytes32); } // File contracts/DaoModule.sol // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.8.0; contract Enum { enum Operation { Call, DelegateCall } } interface Executor { /// @dev Allows a Module to execute a transaction. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule(address to, uint256 value, bytes calldata data, Enum.Operation operation) external returns (bool success); } contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
mapping(bytes32 => Question) public questions;
interface Realitio { function askQuestion( uint256 template_id, string calldata question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce ) external returns (bytes32); function isFinalized(bytes32 question_id) view external returns (bool); function resultFor(bytes32 question_id) external view returns (bytes32); function getFinalizeTS(bytes32 question_id) external view returns (uint32); function isPendingArbitration(bytes32 question_id) external view returns (bool); function createTemplate(string calldata content) external returns (uint256); function getBond(bytes32 question_id) external view returns (uint256); function getContentHash(bytes32 question_id) external view returns (bytes32); }
15,003,368
./full_match/42220/0x17a68574119ec182B4d290fEC1e1435eCF1B573e/sources/project_/contracts/swappa/PairUniswapV3.sol
the active tick bitmap index did not change, fetching only the current word is enough set the populated ticks from the bitmap word below to the bitmap word above
function getSpotTicksIfChanged( IUniswapV3Pool pool, int256 previousTickBitmapIndex ) public view returns ( uint160 sqrtPriceX96, uint128 liquidity, int24 tick, int16 tickBitmapIndex, TickLens.PopulatedTick[] memory populatedTicks ) { (sqrtPriceX96, liquidity, tick, tickBitmapIndex) = TickLens.getSpotInfo( pool ); if (int256(tickBitmapIndex) == previousTickBitmapIndex) { populatedTicks = TickLens.getPopulatedTicksInWord( pool, tickBitmapIndex ); populatedTicks = TickLens.getPopulatedTicksInWords( pool, tickBitmapIndex - 1, tickBitmapIndex + 1 ); } }
16,325,405
/** *Submitted for verification at Etherscan.io on 2021-09-04 */ /** *Submitted for verification at Etherscan.io on 2021-09-01 */ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /// @title Neuro Credits for gear holders! /// Original author: Will Papper <https://twitter.com/WillPapper> /// @notice This contract mints Neuro Credits for gear holders and provides /// administrative functions to the gear DAO. It allows: /// * gear holders to claim Neuro Credits /// * A DAO to set seasons for new opportunities to claim Neuro Credits /// * A DAO to mint Neuro Credits for use within the gear ecosystem /// @custom:unaudited This contract has not been audited. Use at your own risk. contract NeuroCredit is Context, Ownable, ERC20 { // gear contract is available at https://etherscan.io/address/0xff796cbbe32b2150a4585a3791cadb213d0f35a3 address public gearContractAddress = 0xFf796cbbe32B2150A4585a3791CADb213D0F35A3; IERC721Enumerable public gearContract; // Give out 25,000 Neuro Credit for every gear Bag that a user holds uint256 public NeuroCreditPerTokenId = 25000 * (10**decimals()); // tokenIdStart of 1 is based on the following lines in the gear contract: /** function claim(uint256 tokenId) public nonReentrant { require(tokenId > 0 && tokenId < 7778, "Token ID invalid"); _safeMint(_msgSender(), tokenId); } */ uint256 public tokenIdStart = 1; // tokenIdEnd of 7777 is based on the following lines in the gear contract: /** function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner { require(tokenId > 7777 && tokenId < 8001, "Token ID invalid"); _safeMint(owner(), tokenId); } */ uint256 public tokenIdEnd = 7777; // Seasons are used to allow users to claim tokens regularly. Seasons are // decided by the DAO. uint256 public season = 0; // Track claimed tokens within a season // IMPORTANT: The format of the mapping is: // claimedForSeason[season][tokenId][claimed] mapping(uint256 => mapping(uint256 => bool)) public seasonClaimedByTokenId; constructor() Ownable() ERC20("Neuro Credits", "NEURO") { // Transfer ownership to the gear DAO // Ownable by OpenZeppelin automatically sets owner to msg.sender, but // we're going to be using a separate wallet for deployment transferOwnership(_msgSender()); gearContract = IERC721Enumerable(gearContractAddress); } /// @notice Claim Neuro Credits for a given gear ID /// @param tokenId The tokenId of the gear NFT function claimById(uint256 tokenId) external { // Follow the Checks-Effects-Interactions pattern to prevent reentrancy // attacks // Checks // Check that the msgSender owns the token that is being claimed require( _msgSender() == gearContract.ownerOf(tokenId), "MUST_OWN_TOKEN_ID" ); // Further Checks, Effects, and Interactions are contained within the // _claim() function _claim(tokenId, _msgSender()); } /// @notice Claim Neuro Credits for all tokens owned by the sender /// @notice This function will run out of gas if you have too much gear! If /// this is a concern, you should use claimRangeForOwner and claim Neuro /// Credits in batches. function claimAllForOwner() external { uint256 tokenBalanceOwner = gearContract.balanceOf(_msgSender()); // Checks require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED"); // i < tokenBalanceOwner because tokenBalanceOwner is 1-indexed for (uint256 i = 0; i < tokenBalanceOwner; i++) { // Further Checks, Effects, and Interactions are contained within // the _claim() function _claim( gearContract.tokenOfOwnerByIndex(_msgSender(), i), _msgSender() ); } } /// @notice Claim Neuro Credits for all tokens owned by the sender within a /// given range /// @notice This function is useful if you own too much gear to claim all at /// once or if you want to leave some gear unclaimed. If you leave gear /// unclaimed, however, you cannot claim it once the next season starts. function claimRangeForOwner(uint256 ownerIndexStart, uint256 ownerIndexEnd) external { uint256 tokenBalanceOwner = gearContract.balanceOf(_msgSender()); // Checks require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED"); // We use < for ownerIndexEnd and tokenBalanceOwner because // tokenOfOwnerByIndex is 0-indexed while the token balance is 1-indexed require( ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner, "INDEX_OUT_OF_RANGE" ); // i <= ownerIndexEnd because ownerIndexEnd is 0-indexed for (uint256 i = ownerIndexStart; i <= ownerIndexEnd; i++) { // Further Checks, Effects, and Interactions are contained within // the _claim() function _claim( gearContract.tokenOfOwnerByIndex(_msgSender(), i), _msgSender() ); } } /// @dev Internal function to mint gear upon claiming function _claim(uint256 tokenId, address tokenOwner) internal { // Checks // Check that the token ID is in range // We use >= and <= to here because all of the token IDs are 0-indexed require( tokenId >= tokenIdStart && tokenId <= tokenIdEnd, "TOKEN_ID_OUT_OF_RANGE" ); // Check that Neuro Credits have not already been claimed this season // for a given tokenId require( !seasonClaimedByTokenId[season][tokenId], "CREDIT_CLAIMED_FOR_TOKEN_ID" ); // Effects // Mark that Neuro Credits has been claimed for this season for the // given tokenId seasonClaimedByTokenId[season][tokenId] = true; // Interactions // Send Neuro Credits to the owner of the token ID _mint(tokenOwner, NeuroCreditPerTokenId); } /// @notice Allows the DAO to mint new tokens for use within the gear /// Ecosystem /// @param amountDisplayValue The amount of gear to mint. This should be /// input as the display value, not in raw decimals. If you want to mint /// 100 gear, you should enter "100" rather than the value of 100 * 10^18. function daoMint(uint256 amountDisplayValue) external onlyOwner { _mint(owner(), amountDisplayValue * (10**decimals())); } /// @notice Allows the DAO to set a new contract address for gear. This is /// relevant in the event that gear migrates to a new contract. /// @param gearContractAddress_ The new contract address for gear function daoSetgearContractAddress(address gearContractAddress_) external onlyOwner { gearContractAddress = gearContractAddress_; gearContract = IERC721Enumerable(gearContractAddress); } /// @notice Allows the DAO to set the token IDs that are eligible to claim /// gear /// @param tokenIdStart_ The start of the eligible token range /// @param tokenIdEnd_ The end of the eligible token range /// @dev This is relevant in case a future gear contract has a different /// total supply of gear function daoSetTokenIdRange(uint256 tokenIdStart_, uint256 tokenIdEnd_) external onlyOwner { tokenIdStart = tokenIdStart_; tokenIdEnd = tokenIdEnd_; } /// @notice Allows the DAO to set a season for new Neuro Credits claims /// @param season_ The season to use for claiming gear function daoSetSeason(uint256 season_) public onlyOwner { season = season_; } /// @notice Allows the DAO to set the amount of Neuro Credits that is /// claimed per token ID /// @param NeuroCreditDisplayValue The amount of gear a user can claim. /// This should be input as the display value, not in raw decimals. If you /// want to mint 100 gear, you should enter "100" rather than the value of /// 100 * 10^18. function daoSetNeuroCreditPerTokenId(uint256 NeuroCreditDisplayValue) public onlyOwner { NeuroCreditPerTokenId = NeuroCreditDisplayValue * (10**decimals()); } /// @notice Allows the DAO to set the season and Neuro Credits per token ID /// in one transaction. This ensures that there is not a gap where a user /// can claim more Neuro Credits than others /// @param season_ The season to use for claiming gear /// @param NeuroCreditDisplayValue The amount of gear a user can claim. /// This should be input as the display value, not in raw decimals. If you /// want to mint 100 gear, you should enter "100" rather than the value of /// 100 * 10^18. /// @dev We would save a tiny amount of gas by modifying the season and /// NeuroCredit variables directly. It is better practice for security, /// however, to avoid repeating code. This function is so rarely used that /// it's not worth moving these values into their own internal function to /// skip the gas used on the modifier check. function daoSetSeasonAndNeuroCreditPerTokenID( uint256 season_, uint256 NeuroCreditDisplayValue ) external onlyOwner { daoSetSeason(season_); daoSetNeuroCreditPerTokenId(NeuroCreditDisplayValue); } }
Claim Neuro Credits for all tokens owned by the sender within a given range This function is useful if you own too much gear to claim all at once or if you want to leave some gear unclaimed. If you leave gear unclaimed, however, you cannot claim it once the next season starts. Checks We use < for ownerIndexEnd and tokenBalanceOwner because tokenOfOwnerByIndex is 0-indexed while the token balance is 1-indexed i <= ownerIndexEnd because ownerIndexEnd is 0-indexed Further Checks, Effects, and Interactions are contained within the _claim() function
function claimRangeForOwner(uint256 ownerIndexStart, uint256 ownerIndexEnd) external { uint256 tokenBalanceOwner = gearContract.balanceOf(_msgSender()); require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED"); require( ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner, "INDEX_OUT_OF_RANGE" ); for (uint256 i = ownerIndexStart; i <= ownerIndexEnd; i++) { _claim( gearContract.tokenOfOwnerByIndex(_msgSender(), i), _msgSender() ); } }
10,181,390
./full_match/1/0x4E99b8dC5c5b24b8904b640Ea9342dcEa233818A/sources/src/v2-config-engine/V2RateStrategyFactory.sol
@inheritdoc IV2RateStrategyFactory
function getStrategyData(IDefaultInterestRateStrategy strategy) public view returns (RateStrategyParams memory) { return RateStrategyParams({ optimalUtilizationRate: strategy.OPTIMAL_UTILIZATION_RATE(), baseVariableBorrowRate: strategy.baseVariableBorrowRate(), variableRateSlope1: strategy.variableRateSlope1(), variableRateSlope2: strategy.variableRateSlope2(), stableRateSlope1: strategy.stableRateSlope1(), stableRateSlope2: strategy.stableRateSlope2() }); }
2,990,816
// File: contracts/ErrorReporter.sol pragma solidity 0.4.24; contract ErrorReporter { /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. */ event Failure(uint256 error, uint256 info, uint256 detail); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, ETHER_AMOUNT_MISMATCH_ERROR } /** * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, SEND_ETHER_ADMIN_CHECK_FAILED, ETHER_AMOUNT_MISMATCH_ERROR } /** * @dev use this when reporting a known error from the Alkemi Earn Verified or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(FailureInfo info, uint256 opaqueError) internal returns (uint256) { emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError); return uint256(Error.OPAQUE_ERROR); } } // File: contracts/CarefulMath.sol // Cloned from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol -> Commit id: 24a0bc2 // and added custom functions related to Alkemi pragma solidity 0.4.24; /** * @title Careful Math * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol */ contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (a == 0) { return (Error.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint256 a, uint256 b) internal pure returns (Error, uint256) { uint256 c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub( uint256 a, uint256 b, uint256 c ) internal pure returns (Error, uint256) { (Error err0, uint256 sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } } // File: contracts/Exponential.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; contract Exponential is ErrorReporter, CarefulMath { // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint256 constant expScale = 10**18; uint256 constant halfExpScale = expScale / 2; struct Exp { uint256 mantissa; } uint256 constant mantissaOne = 10**18; // Though unused, the below variable cannot be deleted as it will hinder upgradeability // Will be cleared during the next compiler version upgrade uint256 constant mantissaOneTenth = 10**17; /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (Error err1, uint256 rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = add(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = sub(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp divisor) internal pure returns (Error, Exp memory) { /* We are doing this as: getExp(mul(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (Error err0, uint256 numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (Error err1, uint256 doubleScaledProductWithHalfScale) = add( halfExpScale, doubleScaledProduct ); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (Error err2, uint256 product) = div( doubleScaledProductWithHalfScale, expScale ); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({mantissa: product})); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if first Exp is greater than second Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } // File: contracts/InterestRateModel.sol pragma solidity 0.4.24; /** * @title InterestRateModel Interface * @notice Any interest rate model should derive from this contract. * @dev These functions are specifically not marked `pure` as implementations of this * contract may read from storage variables. */ contract InterestRateModel { /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); } // File: contracts/EIP20Interface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; contract EIP20Interface { /* 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; // token decimals uint8 public decimals; // maximum is 18 decimals /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view 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) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/EIP20NonStandardInterface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ contract EIP20NonStandardInterface { /* 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) public view returns (uint256 balance); /** * !!!!!!!!!!!!!! * !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @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; /** * * !!!!!!!!!!!!!! * !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @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; /// @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) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/SafeToken.sol pragma solidity 0.4.24; contract SafeToken is ErrorReporter { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn( address asset, address from, uint256 amount ) internal view returns (Error) { EIP20Interface token = EIP20Interface(asset); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn( address asset, address from, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_FAILED; } return Error.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } function doApprove( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.approve(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } } // File: contracts/AggregatorV3Interface.sol pragma solidity 0.4.24; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: contracts/ChainLink.sol pragma solidity 0.4.24; contract ChainLink { mapping(address => AggregatorV3Interface) internal priceContractMapping; address public admin; bool public paused = false; address public wethAddressVerified; address public wethAddressPublic; AggregatorV3Interface public USDETHPriceFeed; uint256 constant expScale = 10**18; uint8 constant eighteen = 18; /** * Sets the admin * Add assets and set Weth Address using their own functions */ constructor() public { admin = msg.sender; } /** * Modifier to restrict functions only by admins */ modifier onlyAdmin() { require( msg.sender == admin, "Only the Admin can perform this operation" ); _; } /** * Event declarations for all the operations of this contract */ event assetAdded( address indexed assetAddress, address indexed priceFeedContract ); event assetRemoved(address indexed assetAddress); event adminChanged(address indexed oldAdmin, address indexed newAdmin); event verifiedWethAddressSet(address indexed wethAddressVerified); event publicWethAddressSet(address indexed wethAddressPublic); event contractPausedOrUnpaused(bool currentStatus); /** * Allows admin to add a new asset for price tracking */ function addAsset(address assetAddress, address priceFeedContract) public onlyAdmin { require( assetAddress != address(0) && priceFeedContract != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface( priceFeedContract ); emit assetAdded(assetAddress, priceFeedContract); } /** * Allows admin to remove an existing asset from price tracking */ function removeAsset(address assetAddress) public onlyAdmin { require( assetAddress != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface(address(0)); emit assetRemoved(assetAddress); } /** * Allows admin to change the admin of the contract */ function changeAdmin(address newAdmin) public onlyAdmin { require( newAdmin != address(0), "Asset or Price Feed address cannot be 0x00" ); emit adminChanged(admin, newAdmin); admin = newAdmin; } /** * Allows admin to set the weth address for verified protocol */ function setWethAddressVerified(address _wethAddressVerified) public onlyAdmin { require(_wethAddressVerified != address(0), "WETH address cannot be 0x00"); wethAddressVerified = _wethAddressVerified; emit verifiedWethAddressSet(_wethAddressVerified); } /** * Allows admin to set the weth address for public protocol */ function setWethAddressPublic(address _wethAddressPublic) public onlyAdmin { require(_wethAddressPublic != address(0), "WETH address cannot be 0x00"); wethAddressPublic = _wethAddressPublic; emit publicWethAddressSet(_wethAddressPublic); } /** * Allows admin to pause and unpause the contract */ function togglePause() public onlyAdmin { if (paused) { paused = false; emit contractPausedOrUnpaused(false); } else { paused = true; emit contractPausedOrUnpaused(true); } } /** * Returns the latest price scaled to 1e18 scale */ function getAssetPrice(address asset) public view returns (uint256, uint8) { // Return 1 * 10^18 for WETH, otherwise return actual price if (!paused) { if ( asset == wethAddressVerified || asset == wethAddressPublic ){ return (expScale, eighteen); } } // Capture the decimals in the ERC20 token uint8 assetDecimals = EIP20Interface(asset).decimals(); if (!paused && priceContractMapping[asset] != address(0)) { ( uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound ) = priceContractMapping[asset].latestRoundData(); startedAt; // To avoid compiler warnings for unused local variable // If the price data was not refreshed for the past 1 day, prices are considered stale // This threshold is the maximum Chainlink uses to update the price feeds require(timeStamp > (now - 86500 seconds), "Stale data"); // If answeredInRound is less than roundID, prices are considered stale require(answeredInRound >= roundID, "Stale Data"); if (price > 0) { // Magnify the result based on decimals return (uint256(price), assetDecimals); } else { return (0, assetDecimals); } } else { return (0, assetDecimals); } } function() public payable { require( msg.sender.send(msg.value), "Fallback function initiated but refund failed" ); } } // File: contracts/AlkemiWETH.sol // Cloned from https://github.com/gnosis/canonical-weth/blob/master/contracts/WETH9.sol -> Commit id: 0dd1ea3 pragma solidity 0.4.24; contract AlkemiWETH { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); emit Transfer(address(0), msg.sender, msg.value); } function withdraw(address user, uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; user.transfer(wad); emit Withdrawal(msg.sender, wad); emit Transfer(msg.sender, address(0), wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } // File: contracts/RewardControlInterface.sol pragma solidity 0.4.24; contract RewardControlInterface { /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external; /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external; /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external; /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address market, bool isVerified ) external; } // File: contracts/AlkemiEarnVerified.sol pragma solidity 0.4.24; contract AlkemiEarnVerified is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnVerified` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: 125 * (10**16)}); originationFee = Exp({mantissa: (10**15)}); liquidationDiscount = Exp({mantissa: (10**17)}); // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnVerified, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Modifier to check if the caller is the admin of the contract */ modifier onlyOwner() { require(msg.sender == admin, "Owner check failed"); _; } /** * @dev Modifier to check if the caller is KYC verified */ modifier onlyCustomerWithKYC() { require( customersWithKYC[msg.sender], "KYC_CUSTOMER_VERIFICATION_CHECK_FAILED" ); _; } /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * @dev Mapping to identify the list of KYC Admins */ mapping(address => bool) public KYCAdmins; /** * @dev Mapping to identify the list of customers with verified KYC */ mapping(address => bool) public customersWithKYC; /** * @dev Mapping to identify the list of customers with Liquidator roles */ mapping(address => bool) public liquidators; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp borrowTotalValue; Exp sumBorrows; Exp supplyTotalValue; Exp sumSupplies; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev Events to notify the frontend of all the functions below */ event LiquidatorChanged(address indexed Liquidator, bool newStatus); /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address account, address asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev KYC Integration */ /** * @dev Events to notify the frontend of all the functions below */ event KYCAdminChanged(address indexed KYCAdmin, bool newStatus); event KYCCustomerChanged(address indexed KYCCustomer, bool newStatus); /** * @dev Function for use by the admin of the contract to add or remove KYC Admins */ function _changeKYCAdmin(address KYCAdmin, bool newStatus) public onlyOwner { KYCAdmins[KYCAdmin] = newStatus; emit KYCAdminChanged(KYCAdmin, newStatus); } /** * @dev Function for use by the KYC admins to add or remove KYC Customers */ function _changeCustomerKYC(address customer, bool newStatus) public { require(KYCAdmins[msg.sender], "KYC_ADMIN_CHECK_FAILED"); customersWithKYC[customer] = newStatus; emit KYCCustomerChanged(customer, newStatus); } /** * @dev Liquidator Integration */ /** * @dev Function for use by the admin of the contract to add or remove Liquidators */ function _changeLiquidator(address liquidator, bool newStatus) public onlyOwner { liquidators[liquidator] = newStatus; emit LiquidatorChanged(liquidator, newStatus); } /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @dev Calculates a new supply index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount( address asset, uint256 assetAmount, bool mulCollatRatio ) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } if (mulCollatRatio) { Exp memory scaledPrice; // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @param newCloseFactorMantissa new Close Factor, scaled by 1e18 * @param wethContractAddress WETH Contract Address * @param _rewardControl Reward Control Address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa, address wethContractAddress, address _rewardControl ) public onlyOwner returns (uint256) { // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; originationFee = Exp({mantissa: originationFeeMantissa}); closeFactorMantissa = newCloseFactorMantissa; require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function _acceptAdmin() public { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public onlyOwner returns (uint256) { // Hard cap on the maximum number of markets allowed require( interestRateModel != address(0) && collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "INPUT_VALIDATION_FAILED" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public onlyOwner returns (uint256) { // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public onlyOwner returns (uint256) { // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); revertIfError(err); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public onlyOwner returns (uint256) { require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public onlyOwner returns (uint256) { // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint256 cash = getCash(asset); // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate(asset, cash - amount, markets[asset].totalSupply); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate(asset, cash - amount, markets[asset].totalBorrows); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH */ function supplyEther(uint256 etherAmount) internal returns (uint256) { require(wethAddress != address(0), "WETH_ADDRESS_NOT_SET_ERROR"); WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount, false ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); revertIfError(err); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); revertIfError(err); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent, false ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent, false ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, false, true); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(localResults.repayAmount); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } require(liquidators[msg.sender], "LIQUIDATOR_CHECK_FAILED"); refreshAlkIndex(assetCollateral, targetAccount, true, true); refreshAlkIndex(assetCollateral, msg.sender, true, true); refreshAlkIndex(assetBorrow, targetAccount, false, true); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice revertIfError(err); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow revertIfError(err); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. revertIfError(err); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET revertIfError(err); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either revertIfError(err); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. revertIfError(err); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, false, true); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmount( asset, localResults.borrowAmountWithFee, true ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkIndex(asset, admin, true, true); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyReceived( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param user The address of the supplier/borrower to accrue rewards * @param isSupply Specifies if Supply or Borrow Index need to be updated * @param isVerified Verified / Public protocol */ function refreshAlkIndex( address market, address user, bool isSupply, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } if (isSupply) { rewardControl.refreshAlkSupplyIndex(market, user, isVerified); } else { rewardControl.refreshAlkBorrowIndex(market, user, isVerified); } } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/AlkemiEarnPublic.sol pragma solidity 0.4.24; contract AlkemiEarnPublic is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnPublic` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; defaultOriginationFee = (10**15); // default is 0.1% defaultCollateralRatio = 125 * (10**16); // default is 125% or 1.25 defaultLiquidationDiscount = (10**17); // default is 10% or 0.1 minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: defaultCollateralRatio}); originationFee = Exp({mantissa: defaultOriginationFee}); liquidationDiscount = Exp({mantissa: defaultLiquidationDiscount}); _guardCounter = 1; // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnPublic, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp supplyTotalValue; Exp sumSupplies; Exp borrowTotalValue; Exp sumBorrows; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a origination fee supply is received as admin * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyOrgFeeAsAdmin( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address indexed oldAdmin, address indexed newAdmin); /** * @dev emitted when new market is supported by admin */ event SupportedMarket( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when risk parameters are changed by admin */ event NewRiskParameters( uint256 oldCollateralRatioMantissa, uint256 newCollateralRatioMantissa, uint256 oldLiquidationDiscountMantissa, uint256 newLiquidationDiscountMantissa ); /** * @dev emitted when origination fee is changed by admin */ event NewOriginationFee( uint256 oldOriginationFeeMantissa, uint256 newOriginationFeeMantissa ); /** * @dev emitted when market has new interest rate model set */ event SetMarketInterestRateModel( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @notice return the number of elements in `collateralMarkets` * @dev you can then externally call `collateralMarkets(uint)` to pull each market address * @return the length of `collateralMarkets` */ function getCollateralMarketsLength() public view returns (uint256) { return collateralMarkets.length; } /** * @dev Calculates a new supply/borrow index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply/borrow index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount(address asset, uint256 assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmountMulCollatRatio( address asset, uint256 assetAmount ) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_PENDING_ADMIN_OWNER_CHECK"); // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee( oldOriginationFee.mantissa, originationFeeMantissa ); closeFactorMantissa = newCloseFactorMantissa; return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint256) { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Save current value for inclusion in log address oldAdmin = admin; // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; emit NewAdmin(oldAdmin, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUPPORT_MARKET_OWNER_CHECK"); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Hard cap on the maximum number of markets allowed require( collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "Exceeding the max number of markets allowed" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUSPEND_MARKET_OWNER_CHECK"); // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_RISK_PARAMETERS_OWNER_CHECK"); // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Save current values so we can emit them in log. Exp memory oldCollateralRatio = collateralRatio; Exp memory oldLiquidationDiscount = liquidationDiscount; // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; emit NewRiskParameters( oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa ); return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK" ); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK"); // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate( asset, getCash(asset) - amount, markets[asset].totalSupply ); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate( asset, getCash(asset) - amount, markets[asset].totalBorrows ); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Set WETH token contract address * @param wethContractAddress Enter the WETH token address */ function setWethAddress(address wethContractAddress) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_WETH_ADDRESS_ADMIN_CHECK_FAILED"); require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); return uint256(Error.NO_ERROR); } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function supplyEther(address user, uint256 etherAmount) internal returns (uint256) { user; // To silence the warning of unused local variable if (wethAddress != address(0)) { WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } else { return uint256(Error.WETH_ADDRESS_NOT_SET_ERROR); } } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.sender, msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkBorrowIndex(asset, msg.sender, false); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther( msg.sender, localResults.repayAmount ); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(assetCollateral, targetAccount, false); refreshAlkSupplyIndex(assetCollateral, msg.sender, false); refreshAlkBorrowIndex(assetBorrow, targetAccount, false); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice assert(err == Error.NO_ERROR); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow assert(err == Error.NO_ERROR); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. assert(err == Error.NO_ERROR); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET assert(err == Error.NO_ERROR); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either assert(err == Error.NO_ERROR); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkBorrowIndex(asset, msg.sender, false); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmountMulCollatRatio( asset, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkSupplyIndex(asset, admin, false); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyOrgFeeAsAdmin( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Set the address of the Reward Control contract to be triggered to accrue ALK rewards for participants * @param _rewardControl The address of the underlying reward control contract * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function setRewardControlAddress(address _rewardControl) external returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_REWARD_CONTROL_ADDRESS_ADMIN_CHECK_FAILED" ); require( address(rewardControl) != _rewardControl, "The same Reward Control address" ); require( _rewardControl != address(0), "RewardControl address cannot be empty" ); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); // success } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param supplier The address of the supplier to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkSupplyIndex(market, supplier, isVerified); } /** * @notice Trigger the underlying Reward Control contract to accrue ALK borrow rewards for the borrower on the specified market * @param market The address of the market to accrue rewards * @param borrower The address of the borrower to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkBorrowIndex(market, borrower, isVerified); } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/RewardControlStorage.sol pragma solidity 0.4.24; contract RewardControlStorage { struct MarketState { // @notice The market's last updated alkSupplyIndex or alkBorrowIndex uint224 index; // @notice The block number the index was last updated at uint32 block; } // @notice A list of all markets in the reward program mapped to respective verified/public protocols // @notice true => address[] represents Verified Protocol markets // @notice false => address[] represents Public Protocol markets mapping(bool => address[]) public allMarkets; // @notice The index for checking whether a market is already in the reward program // @notice The first mapping represents verified / public market and the second gives the existence of the market mapping(bool => mapping(address => bool)) public allMarketsIndex; // @notice The rate at which the Reward Control distributes ALK per block uint256 public alkRate; // @notice The portion of alkRate that each market currently receives // @notice The first mapping represents verified / public market and the second gives the alkSpeeds mapping(bool => mapping(address => uint256)) public alkSpeeds; // @notice The ALK market supply state for each market // @notice The first mapping represents verified / public market and the second gives the supplyState mapping(bool => mapping(address => MarketState)) public alkSupplyState; // @notice The ALK market borrow state for each market // @notice The first mapping represents verified / public market and the second gives the borrowState mapping(bool => mapping(address => MarketState)) public alkBorrowState; // @notice The snapshot of ALK index for each market for each supplier as of the last time they accrued ALK // @notice verified/public => market => supplier => supplierIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkSupplierIndex; // @notice The snapshot of ALK index for each market for each borrower as of the last time they accrued ALK // @notice verified/public => market => borrower => borrowerIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkBorrowerIndex; // @notice The ALK accrued but not yet transferred to each participant mapping(address => uint256) public alkAccrued; // @notice To make sure initializer is called only once bool public initializationDone; // @notice The address of the current owner of this contract address public owner; // @notice The proposed address of the new owner of this contract address public newOwner; // @notice The underlying AlkemiEarnVerified contract AlkemiEarnVerified public alkemiEarnVerified; // @notice The underlying AlkemiEarnPublic contract AlkemiEarnPublic public alkemiEarnPublic; // @notice The ALK token address address public alkAddress; // Hard cap on the maximum number of markets uint8 public MAXIMUM_NUMBER_OF_MARKETS; } // File: contracts/ExponentialNoError.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // File: contracts/RewardControl.sol pragma solidity 0.4.24; contract RewardControl is RewardControlStorage, RewardControlInterface, ExponentialNoError { /** * Events */ /// @notice Emitted when a new ALK speed is calculated for a market event AlkSpeedUpdated( address indexed market, uint256 newSpeed, bool isVerified ); /// @notice Emitted when ALK is distributed to a supplier event DistributedSupplierAlk( address indexed market, address indexed supplier, uint256 supplierDelta, uint256 supplierAccruedAlk, uint256 supplyIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is distributed to a borrower event DistributedBorrowerAlk( address indexed market, address indexed borrower, uint256 borrowerDelta, uint256 borrowerAccruedAlk, uint256 borrowIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is transferred to a participant event TransferredAlk( address indexed participant, uint256 participantAccrued, address market, bool isVerified ); /// @notice Emitted when the owner of the contract is updated event OwnerUpdate(address indexed owner, address indexed newOwner); /// @notice Emitted when a market is added event MarketAdded( address indexed market, uint256 numberOfMarkets, bool isVerified ); /// @notice Emitted when a market is removed event MarketRemoved( address indexed market, uint256 numberOfMarkets, bool isVerified ); /** * Constants */ /** * Constructor */ /** * @notice `RewardControl` is the contract to calculate and distribute reward tokens * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only in a derived contract of RewardControlStorage, inherited by this contract * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer( address _owner, address _alkemiEarnVerified, address _alkemiEarnPublic, address _alkAddress ) public { require( _owner != address(0) && _alkemiEarnVerified != address(0) && _alkemiEarnPublic != address(0) && _alkAddress != address(0), "Inputs cannot be 0x00" ); if (initializationDone == false) { initializationDone = true; owner = _owner; alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); alkAddress = _alkAddress; // Total Liquidity rewards for 4 years = 70,000,000 // Liquidity per year = 70,000,000/4 = 17,500,000 // Divided by blocksPerYear (assuming 13.3 seconds avg. block time) = 17,500,000/2,371,128 = 7.380453522542860000 // 7380453522542860000 (Tokens scaled by token decimals of 18) divided by 2 (half for lending and half for borrowing) alkRate = 3690226761271430000; MAXIMUM_NUMBER_OF_MARKETS = 16; } } /** * Modifiers */ /** * @notice Make sure that the sender is only the owner of the contract */ modifier onlyOwner() { require(msg.sender == owner, "non-owner"); _; } /** * Public functions */ /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, supplier, isVerified); } /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, borrower, isVerified); } /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external { claimAlk(holder, allMarkets[true], true); claimAlk(holder, allMarkets[false], false); } /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Specifies if the market is from verified or public protocol */ function claimAlk( address holder, address market, bool isVerified ) external { require(allMarketsIndex[isVerified][market], "Market does not exist"); address[] memory markets = new address[](1); markets[0] = market; claimAlk(holder, markets, isVerified); } /** * Private functions */ /** * @notice Recalculate and update ALK speeds for all markets */ function refreshMarketLiquidity() internal view returns (Exp[] memory, Exp memory) { Exp memory totalLiquidity = Exp({mantissa: 0}); Exp[] memory marketTotalLiquidity = new Exp[]( add_(allMarkets[true].length, allMarkets[false].length) ); address currentMarket; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; uint256 currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); uint256 currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); Exp memory currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[i] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[ verifiedMarketsLength + j ] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } return (marketTotalLiquidity, totalLiquidity); } /** * @notice Recalculate and update ALK speeds for all markets */ function refreshAlkSpeeds() public { address currentMarket; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 newSpeed; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; alkSpeeds[true][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, true); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; newSpeed = totalLiquidity.mantissa > 0 ? mul_( alkRate, div_( marketTotalLiquidity[verifiedMarketsLength + j], totalLiquidity ) ) : 0; alkSpeeds[false][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, false); } } /** * @notice Accrue ALK to the market by updating the supply index * @param market The market whose supply index to update * @param isVerified Verified / Public protocol */ function updateAlkSupplyIndex(address market, bool isVerified) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(supplyState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalSupply = getMarketTotalSupply( market, isVerified ); uint256 supplyAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalSupply > 0 ? fraction(supplyAlkAccrued, marketTotalSupply) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: supplyState.index}), ratio ); alkSupplyState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Accrue ALK to the market by updating the borrow index * @param market The market whose borrow index to update * @param isVerified Verified / Public protocol */ function updateAlkBorrowIndex(address market, bool isVerified) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalBorrows = getMarketTotalBorrows( market, isVerified ); uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalBorrows > 0 ? fraction(borrowAlkAccrued, marketTotalBorrows) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: borrowState.index}), ratio ); alkBorrowState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Calculate ALK accrued by a supplier and add it on top of alkAccrued[supplier] * @param market The market in which the supplier is interacting * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeSupplierAlk( address market, address supplier, bool isVerified ) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: alkSupplierIndex[isVerified][market][supplier] }); alkSupplierIndex[isVerified][market][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa > 0) { Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierBalance = getSupplyBalance( market, supplier, isVerified ); uint256 supplierDelta = mul_(supplierBalance, deltaIndex); alkAccrued[supplier] = add_(alkAccrued[supplier], supplierDelta); emit DistributedSupplierAlk( market, supplier, supplierDelta, alkAccrued[supplier], supplyIndex.mantissa, isVerified ); } } /** * @notice Calculate ALK accrued by a borrower and add it on top of alkAccrued[borrower] * @param market The market in which the borrower is interacting * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeBorrowerAlk( address market, address borrower, bool isVerified ) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: alkBorrowerIndex[isVerified][market][borrower] }); alkBorrowerIndex[isVerified][market][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerBalance = getBorrowBalance( market, borrower, isVerified ); uint256 borrowerDelta = mul_(borrowerBalance, deltaIndex); alkAccrued[borrower] = add_(alkAccrued[borrower], borrowerDelta); emit DistributedBorrowerAlk( market, borrower, borrowerDelta, alkAccrued[borrower], borrowIndex.mantissa, isVerified ); } } /** * @notice Claim all the ALK accrued by holder in the specified markets * @param holder The address to claim ALK for * @param markets The list of markets to claim ALK in * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address[] memory markets, bool isVerified ) internal { for (uint256 i = 0; i < markets.length; i++) { address market = markets[i]; updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, holder, isVerified); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, holder, isVerified); alkAccrued[holder] = transferAlk( holder, alkAccrued[holder], market, isVerified ); } } /** * @notice Transfer ALK to the participant * @dev Note: If there is not enough ALK, we do not perform the transfer all. * @param participant The address of the participant to transfer ALK to * @param participantAccrued The amount of ALK to (possibly) transfer * @param market Market for which ALK is transferred * @param isVerified Verified / Public Protocol * @return The amount of ALK which was NOT transferred to the participant */ function transferAlk( address participant, uint256 participantAccrued, address market, bool isVerified ) internal returns (uint256) { if (participantAccrued > 0) { EIP20Interface alk = EIP20Interface(getAlkAddress()); uint256 alkRemaining = alk.balanceOf(address(this)); if (participantAccrued <= alkRemaining) { alk.transfer(participant, participantAccrued); emit TransferredAlk( participant, participantAccrued, market, isVerified ); return 0; } } return participantAccrued; } /** * Getters */ /** * @notice Get the current block number * @return The current block number */ function getBlockNumber() public view returns (uint256) { return block.number; } /** * @notice Get the current accrued ALK for a participant * @param participant The address of the participant * @return The amount of accrued ALK for the participant */ function getAlkAccrued(address participant) public view returns (uint256) { return alkAccrued[participant]; } /** * @notice Get the address of the ALK token * @return The address of ALK token */ function getAlkAddress() public view returns (address) { return alkAddress; } /** * @notice Get the address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract * @return The address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract */ function getAlkemiEarnAddress() public view returns (address, address) { return (address(alkemiEarnVerified), address(alkemiEarnPublic)); } /** * @notice Get market statistics from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market statistics for the given market */ function getMarketStats(address market, bool isVerified) public view returns ( bool isSupported, uint256 blockNumber, address interestRateModel, uint256 totalSupply, uint256 supplyRateMantissa, uint256 supplyIndex, uint256 totalBorrows, uint256 borrowRateMantissa, uint256 borrowIndex ) { if (isVerified) { return (alkemiEarnVerified.markets(market)); } else { return (alkemiEarnPublic.markets(market)); } } /** * @notice Get market total supply from the AlkemiEarnVerified / AlkemiEarnPublic contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total supply for the given market */ function getMarketTotalSupply(address market, bool isVerified) public view returns (uint256) { uint256 totalSupply; (, , , totalSupply, , , , , ) = getMarketStats(market, isVerified); return totalSupply; } /** * @notice Get market total borrows from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total borrows for the given market */ function getMarketTotalBorrows(address market, bool isVerified) public view returns (uint256) { uint256 totalBorrows; (, , , , , , totalBorrows, , ) = getMarketStats(market, isVerified); return totalBorrows; } /** * @notice Get supply balance of the specified market and supplier * @param market The address of the market * @param supplier The address of the supplier * @param isVerified Verified / Public protocol * @return Supply balance of the specified market and supplier */ function getSupplyBalance( address market, address supplier, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getSupplyBalance(supplier, market); } else { return alkemiEarnPublic.getSupplyBalance(supplier, market); } } /** * @notice Get borrow balance of the specified market and borrower * @param market The address of the market * @param borrower The address of the borrower * @param isVerified Verified / Public protocol * @return Borrow balance of the specified market and borrower */ function getBorrowBalance( address market, address borrower, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getBorrowBalance(borrower, market); } else { return alkemiEarnPublic.getBorrowBalance(borrower, market); } } /** * Admin functions */ /** * @notice Transfer the ownership of this contract to the new owner. The ownership will not be transferred until the new owner accept it. * @param _newOwner The address of the new owner */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != owner, "TransferOwnership: the same owner."); newOwner = _newOwner; } /** * @notice Accept the ownership of this contract by the new owner */ function acceptOwnership() external { require( msg.sender == newOwner, "AcceptOwnership: only new owner do this." ); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } /** * @notice Add new market to the reward program * @param market The address of the new market to be added to the reward program * @param isVerified Verified / Public protocol */ function addMarket(address market, bool isVerified) external onlyOwner { require(!allMarketsIndex[isVerified][market], "Market already exists"); require( allMarkets[isVerified].length < uint256(MAXIMUM_NUMBER_OF_MARKETS), "Exceeding the max number of markets allowed" ); allMarketsIndex[isVerified][market] = true; allMarkets[isVerified].push(market); emit MarketAdded( market, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Remove a market from the reward program based on array index * @param id The index of the `allMarkets` array to be removed * @param isVerified Verified / Public protocol */ function removeMarket(uint256 id, bool isVerified) external onlyOwner { if (id >= allMarkets[isVerified].length) { return; } allMarketsIndex[isVerified][allMarkets[isVerified][id]] = false; address removedMarket = allMarkets[isVerified][id]; for (uint256 i = id; i < allMarkets[isVerified].length - 1; i++) { allMarkets[isVerified][i] = allMarkets[isVerified][i + 1]; } allMarkets[isVerified].length--; // reset the ALK speeds for the removed market and refresh ALK speeds alkSpeeds[isVerified][removedMarket] = 0; refreshAlkSpeeds(); emit MarketRemoved( removedMarket, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Set ALK token address * @param _alkAddress The ALK token address */ function setAlkAddress(address _alkAddress) external onlyOwner { require(alkAddress != _alkAddress, "The same ALK address"); require(_alkAddress != address(0), "ALK address cannot be empty"); alkAddress = _alkAddress; } /** * @notice Set AlkemiEarnVerified contract address * @param _alkemiEarnVerified The AlkemiEarnVerified contract address */ function setAlkemiEarnVerifiedAddress(address _alkemiEarnVerified) external onlyOwner { require( address(alkemiEarnVerified) != _alkemiEarnVerified, "The same AlkemiEarnVerified address" ); require( _alkemiEarnVerified != address(0), "AlkemiEarnVerified address cannot be empty" ); alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); } /** * @notice Set AlkemiEarnPublic contract address * @param _alkemiEarnPublic The AlkemiEarnVerified contract address */ function setAlkemiEarnPublicAddress(address _alkemiEarnPublic) external onlyOwner { require( address(alkemiEarnPublic) != _alkemiEarnPublic, "The same AlkemiEarnPublic address" ); require( _alkemiEarnPublic != address(0), "AlkemiEarnPublic address cannot be empty" ); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); } /** * @notice Set ALK rate * @param _alkRate The ALK rate */ function setAlkRate(uint256 _alkRate) external onlyOwner { alkRate = _alkRate; } /** * @notice Get latest ALK rewards * @param user the supplier/borrower */ function getAlkRewards(address user) external view returns (uint256) { // Refresh ALK speeds uint256 alkRewards = alkAccrued[user]; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ) ) ); } for (uint256 j = 0; j < allMarkets[false].length; j++) { uint256 index = verifiedMarketsLength + j; alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ) ) ); } return alkRewards; } /** * @notice Get latest Supply ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the supplier * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getSupplyAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory supplyState = alkSupplyState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(supplyState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: supplyState.index}), ( getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(supplyState.block) ), newSpeed ), getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); supplyState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(supplyState.block)) > 0) { supplyState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnVerified.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( !isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnPublic.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } /** * @notice Get latest Borrow ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the borrower * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getBorrowAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory borrowState = alkBorrowState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(borrowState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: borrowState.index}), ( getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(borrowState.block) ), newSpeed ), getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); borrowState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(borrowState.block)) > 0) { borrowState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && isVerified ) { return mul_( alkemiEarnVerified.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && !isVerified ) { return mul_( alkemiEarnPublic.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } }
Suspends a given supported market (asset) from use. Assets in this state do count for collateral, but users may only withdraw, payBorrow, and liquidate the asset. The liquidate function no longer checks collateralization. Admin function to suspend a market asset Asset to suspend return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Check caller = admin If the market is not configured at all, we don't want to add any configuration for it. If we find !markets[asset].isSupported then either the market is not configured at all, or it has already been marked as unsupported. We can just return without doing anything. Caller is responsible for knowing the difference between not-configured and already unsupported.
function _suspendMarket(address asset) public returns (uint256) { require(msg.sender == admin, "SUSPEND_MARKET_OWNER_CHECK"); if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } return uint256(Error.NO_ERROR); }
81,370
pragma solidity ^0.5.0; // Copyright © 2017, 2018 Weald Technology Trading Limited // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @title ERC777TokensSender * ERC777TokensSender is the interface for contracts that handle pre-send * of tokens from ERC777 token contracts * * @author Jim McDonald */ interface ERC777TokensSender { /** * Function to act prior to send of tokens for a given contract. * * @param operator is the address that carried out the transfer * @param from is the address from which the tokens will be transferred * @param to is the address to which the tokens will be transferred * @param amount is the amount of tokens that will be transferred * @param data is data supplied by the user for the transfer * @param operatorData is data supplied by the operator for the transfer */ function tokensToSend(address operator, address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData) external; }
ERC777TokensSender ERC777TokensSender is the interface for contracts that handle pre-send of tokens from ERC777 token contracts Jim McDonald/
interface ERC777TokensSender { function tokensToSend(address operator, address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData) external; }
974,372
./full_match/80001/0x54Bb7202A05fB694b2A7a19Bb17e4f22faA1a58c/sources/NftStaking.sol
check if we know this userReturn all tokens in the stakedToken array for this user that are not -1
function getStakedTokens(address _user) public view returns(StakedToken[] memory){ if(stakers[_user].amountStaked > 0 ){ StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for(uint256 j = 0 ;j < stakers[_user].stakedTokens.length;j++){ if(stakers[_user].stakedTokens[j].staker != (address(0))){ _stakedTokens[_index]=stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; return new StakedToken[](0); } }
9,483,312
/** *Submitted for verification at Etherscan.io on 2021-12-05 */ // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.0 (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/ERC721.sol // OpenZeppelin Contracts v4.4.0 (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 { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (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: contracts/GenerativeDungeon.sol pragma solidity ^0.8.9; /** * @title GenerativeDungeon contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract GenerativeDungeon is ERC721Enumerable, Ownable { string public NFT_PROVENANCE = ""; string public BASE_METADATA_URI = ""; string public CONTRACT_METADATA_URI = ""; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public PRICE = 0.07 ether; uint256 public PRICE_WHITELIST = 0.05 ether; uint256 public MAX_NFTS_PLUS_1; uint256 public WALLET_LIMIT = 4; // compare will use < to save gas, so actually 3/wallet uint256 public WALLET_LIMIT_WHITELIST = 3; // compare will use < to save gas, so actually 2/wallet bool public saleIsActive = false; bool private locked; // for re-entrancy guard struct AccountInfo { uint256 mintedNFTs; // number of NFTs this wallet address has minted } mapping(address => AccountInfo) public accountInfoList; constructor() ERC721("GenerativeDungeon", "GENDUN") { // in max tokens, leave some space for those tokens created for giveaways after the sale, which will be minted via reserveNfts below MAX_NFTS_PLUS_1 = 9911; // also, to save gas during 3rd "require" in main mint below, use "plus 1" for the compare BASE_METADATA_URI = "https://metadata.generativedungeon.com/"; CONTRACT_METADATA_URI = "https://generativedungeon.com/storefront-metadata.json"; } // from openzeppelin-contracts/contracts/security/ReentrancyGuard.sol modifier nonReentrant() { require(!locked, "Reentrant call"); locked = true; _; locked = false; } // for whitelisted mint modifier onlyWhitelisted(uint8 _v, bytes32 _r, bytes32 _s ) { require (owner() == ecrecover( keccak256( abi.encodePacked('\x19Ethereum Signed Message:\n32', keccak256( abi.encodePacked(address(this), msg.sender)))), _v, _r, _s), 'Not whitelisted'); _; } // to make OpenSea happy - returns a URL for the storefront-level metadata // https://docs.opensea.io/docs/contract-level-metadata function contractURI() public view returns (string memory) { return CONTRACT_METADATA_URI; } function _baseURI() internal view virtual override returns (string memory) { return BASE_METADATA_URI; } function setBaseURI(string memory _baseMetaDataURI) public onlyOwner { BASE_METADATA_URI = _baseMetaDataURI; } function setContractURI(string memory _contractMetaDataURI) public onlyOwner { CONTRACT_METADATA_URI = _contractMetaDataURI; } /* * in case market is volatile */ function setMaxNfts(uint _maxNfts) public onlyOwner { MAX_NFTS_PLUS_1 = _maxNfts; } /* * in case Eth is volatile */ function setPrice(uint256 _newPrice) public onlyOwner() { PRICE = _newPrice; } /* * in case Eth is volatile */ function setPriceWhitelist(uint256 _newPrice) public onlyOwner() { PRICE_WHITELIST = _newPrice; } /* * in case we need to adjust the wallet limit */ function setWalletLimit(uint256 _newLimit) public onlyOwner() { WALLET_LIMIT = _newLimit; } /* * in case we need to adjust the wallet limit */ function setWhitelistWalletLimit(uint256 _newLimit) public onlyOwner() { WALLET_LIMIT_WHITELIST = _newLimit; } function withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); } /** * Set some tokens aside for giveaways, etc */ function reserveNfts(uint256 _amt) public onlyOwner { uint256 supply = totalSupply(); uint256 finalAmt = _amt+1; for (uint256 i=1; i < finalAmt; i++) { // start at Token #1 _safeMint(msg.sender, supply+i); } } /* * Returns all the tokenIds owned by a user in one transaction * * (backup function in case The Graph is down/unreachable) */ function getNFTsByAddress(address _owner) public view returns (uint256[] memory) { uint256 totalItemCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](totalItemCount); for (uint256 i; i < totalItemCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } /* * Pause sale if active, make active if paused */ function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } /** * allows whitelisted addresses to mint NFTs */ function mintWhitelist(uint256 _numberOfTokens, uint8 _v, bytes32 _r, bytes32 _s) public payable nonReentrant onlyWhitelisted(_v, _r, _s) { uint256 supply = totalSupply(); // store to save gas require((_numberOfTokens + accountInfoList[msg.sender].mintedNFTs) < WALLET_LIMIT_WHITELIST, "Exceeds wallet limit"); // we hold the whitelist data off-chain and verify on-chain via onlyWhilelisted; // still have to check against max nft supply in case people whitelist late require(supply + _numberOfTokens < MAX_NFTS_PLUS_1, "Exceeds max NFT supply"); //use < rather than <= to save gas require(msg.value >= PRICE_WHITELIST * _numberOfTokens, "Ether sent is not correct"); _numberOfTokens++; // +1 once for our for loop comparison here, to save gas for(uint256 i=1; i < _numberOfTokens; i++) { // start at Token #1 so IDs aren't zero-based accountInfoList[msg.sender].mintedNFTs++; // nonReentrant above prevents this from messing up _safeMint(msg.sender, supply+i); } } /** * Mints NFTs */ function mint(uint256 _numberOfTokens) public payable nonReentrant { uint256 supply = totalSupply(); // store to save gas require(saleIsActive, "Sale paused"); require((_numberOfTokens + accountInfoList[msg.sender].mintedNFTs) < WALLET_LIMIT, "Exceeds wallet limit"); require(supply + _numberOfTokens < MAX_NFTS_PLUS_1, "Exceeds max NFT supply"); //use < rather than <= to save gas require(msg.value >= PRICE * _numberOfTokens, "Ether sent is not correct"); _numberOfTokens++; // +1 once for our for loop comparison here, to save gas for(uint256 i=1; i < _numberOfTokens; i++) { // start at Token #1 so IDs aren't zero-based accountInfoList[msg.sender].mintedNFTs++; // nonReentrant above prevents this from messing up _safeMint(msg.sender, supply+i); } // to save gas for minters, rather than automatically setting the starting block here, // we'll manually set it by calling setStartingIndex when either // 1) the last token has been sold, or 2) 9 days have passed since launch } /* * airdrops ignore wallet limits */ function airDrop(address _addr, uint256 _numberOfTokens) public onlyOwner { uint256 supply = totalSupply(); // store to save gas require(supply + _numberOfTokens < MAX_NFTS_PLUS_1, "Exceeds max NFT supply"); //use < rather than <= to save gas _numberOfTokens++; // +1 once for our for loop comparison here, to save gas for(uint256 i=1; i < _numberOfTokens; i++) { // start at Token #1 so IDs aren't zero-based _safeMint(_addr, supply+i); } } /** * Set the starting index for the collection after all tokens have sold or 9 days have passed since launch * we use that value to seed our deterministic random bit generator in the gaming code */ function setStartingIndex() public onlyOwner { require(startingIndex == 0, "Starting index is already set"); uint256 supply = totalSupply(); // store to save gas startingIndexBlock = block.number; startingIndex = uint256(blockhash(startingIndexBlock)) % supply; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number-startingIndexBlock > 255) { startingIndex = uint256(blockhash(block.number - 1)) % supply; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex+1; } } /* * Set overall provenance once it's calculated to prove we haven't touched the generated images+code */ function setProvenanceHash(string memory _provenanceHash) public onlyOwner { NFT_PROVENANCE = _provenanceHash; } }
in case we need to adjust the wallet limit/
function setWalletLimit(uint256 _newLimit) public onlyOwner() { WALLET_LIMIT = _newLimit; }
8,047,837
// "SPDX-License-Identifier: Apache-2.0" pragma solidity ^0.7.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "../../../external/math/SafeConversion.sol"; import "../FundsDistributionToken.sol"; import "../IFundsDistributionToken.sol"; /** * @title IContactable * @dev IContactable interface * @author Sébastien Krafft - <[email protected]> */ interface IContactable { /** * @notice Purpose: this event is emitted when the contact information is changed * @param contact - new contact information */ event LogContactSet(string contact); function setContact(string calldata _contact) external; function contact() external view returns (string memory); } /** * @title IDestroyable * @dev IDestroyable interface * @author Sébastien Krafft - <[email protected]> */ interface IDestroyable { /** * @notice Purpose: this event is emitted when issued tokens are destroyed. * @param shareholders - list of shareholders of destroyed tokens */ event LogDestroyed(address[] shareholders); /** * @notice Purpose: to destroy issued tokens. * Conditions: only issuer can execute this function. * @param shareholders - list of shareholders */ function destroy(address[] calldata shareholders) external; } /** * @title IIdentifiable * @dev IIdentifiable interface * @author Sébastien Krafft - <[email protected]> */ interface IIdentifiable { function setMyIdentity(bytes calldata _identity) external; function identity(address shareholder) external view returns (bytes memory); } /** * @title IIssuable * @dev IIssuable interface * @author Sébastien Krafft - <[email protected]> */ interface IIssuable { /** * @notice Purpose: this event is emitted when new tokens are issued. * @param value - amount of newly issued tokens */ event LogIssued(uint256 value); /** * @notice Purpose: this event is emitted when tokens are redeemed. * @param value - amount of redeemed tokens */ event LogRedeemed(uint256 value); function issue(uint256 value) external; function redeem(uint256 value) external; } /** * @title IReassignable * @dev IReassignable interface * @author Sébastien Krafft - <[email protected]> */ interface IReassignable { /** * @notice Purpose: to withdraw tokens from the original address and * transfer those tokens to the replacement address. * Use in cases when e.g. investor loses access to his account. * Conditions: * Throw error if the `original` address supplied is not a shareholder. * Throw error if the 'replacement' address already holds tokens. * Original address MUST NOT be reused again. * Only issuer can execute this function. * @param original - original address * @param replacement - replacement address */ function reassign(address original, address replacement) external; /** * @notice Purpose: this event is emitted when tokens are withdrawn from one address and issued to a new one. * @param original - original address * @param replacement - replacement address * @param value - amount transfered from original to replacement */ event LogReassigned(address indexed original, address indexed replacement, uint256 value); } /** * @title IRule * @dev IRule interface. */ interface IRule { function isTransferValid(address _from, address _to, uint256 _amount) external view returns (bool isValid); function detectTransferRestriction(address _from, address _to, uint256 _amount) external view returns (uint8); function canReturnTransferRestrictionCode(uint8 _restrictionCode) external view returns (bool); function messageForTransferRestriction(uint8 _restrictionCode) external view returns (string memory); } /** * @title IRuleEngine * @dev IRuleEngine */ interface IRuleEngine { function setRules(IRule[] calldata _rules) external; function ruleLength() external view returns (uint256); function rule(uint256 ruleId) external view returns (IRule); function rules() external view returns(IRule[] memory); function validateTransfer(address _from, address _to, uint256 _amount) external view returns (bool); function detectTransferRestriction(address _from, address _to, uint256 _value) external view returns (uint8); function messageForTransferRestriction (uint8 _restrictionCode) external view returns (string memory); } contract CMTA20FDT is IFundsDistributionToken, FundsDistributionToken, Ownable, Pausable, IContactable, IIdentifiable, IIssuable, IDestroyable, IReassignable { using SafeMath for uint256; using SignedSafeMath for int256; using SafeConversion for uint256; using SafeConversion for int256; // token in which the funds can be sent to the FundsDistributionToken IERC20 public fundsToken; // balance of fundsToken that the FundsDistributionToken currently holds uint256 public fundsTokenBalance; // CMTA20 params uint8 internal constant TRANSFER_OK = 0; uint8 internal constant TRANSFER_REJECTED_PAUSED = 1; string internal constant TEXT_TRANSFER_OK = "No restriction"; string internal constant TEXT_TRANSFER_REJECTED_PAUSED = "All transfers paused"; string public override contact; mapping (address => bytes) internal identities; IRuleEngine public ruleEngine; event LogRuleEngineSet(address indexed newRuleEngine); modifier onlyFundsToken() { require( msg.sender == address(fundsToken), "CMTA20FDT.onlyFundsToken: UNAUTHORIZED_SENDER" ); _; } constructor( string memory name, string memory symbol, IERC20 _fundsToken, address owner, uint256 initialAmount ) FundsDistributionToken(name, symbol) { require( address(_fundsToken) != address(0), "CMTA20FDT: INVALID_FUNDS_TOKEN_ADDRESS" ); fundsToken = _fundsToken; transferOwnership(owner); _mint(owner, initialAmount); } /** * @dev Triggers stopped state. */ function pause() external whenNotPaused onlyOwner { _pause(); } /** * @dev Returns to normal state. */ function unpause() external whenPaused onlyOwner { _unpause(); } /** * @notice Purpose: set optional rule engine by owner() * @param _ruleEngine - the rule engine that will approve/reject transfers */ function setRuleEngine(IRuleEngine _ruleEngine) external onlyOwner { ruleEngine = _ruleEngine; emit LogRuleEngineSet(address(_ruleEngine)); } /** * @notice Purpose: set contact point for shareholders * @param _contact - the contact information for the shareholders */ function setContact(string calldata _contact) external override onlyOwner { contact = _contact; emit LogContactSet(_contact); } /** * Purpose * Set identity of a potential/actual shareholder. Can only be called by the potential/actual shareholder himself. Has to be encrypted data. * * @param _identity - the potential/actual shareholder identity */ function setMyIdentity(bytes calldata _identity) external override { identities[msg.sender] = _identity; } /** * @notice Withdraws all available funds for a token holder */ function withdrawFunds() external override whenNotPaused { _withdrawFundsFor(msg.sender); } /** * @notice Register a payment of funds in tokens. May be called directly after a deposit is made. * @dev Calls _updateFundsTokenBalance(), whereby the contract computes the delta of the previous and the new * funds token balance and increments the total received funds (cumulative) by delta by calling _registerFunds() */ function updateFundsReceived() external whenNotPaused { int256 newFunds = _updateFundsTokenBalance(); if (newFunds > 0) { _distributeFunds(newFunds.toUint256Safe()); } } /** * @notice Purposee: to withdraw tokens from the original address and * transfer those tokens to the replacement address. * Use in cases when e.g. investor loses access to his account. * Conditions: throw error if the `original` address supplied is not a shareholder. * Only issuer can execute this function. * @param original - original address * @param replacement - replacement address */ function reassign(address original, address replacement) external override onlyOwner whenNotPaused { require(original != address(0), "CM01"); require(replacement != address(0), "CM02"); require(original != replacement, "CM03"); uint256 originalBalance = balanceOf(original); require(originalBalance != 0, "CM05"); _burn(original, originalBalance); _mint(replacement, originalBalance); emit LogReassigned(original, replacement, originalBalance); emit Transfer(original, replacement, originalBalance); } /** * @notice Purpose: to destroy issued tokens. * Conditions: only issuer can execute this function. * @param shareholders - list of shareholders */ function destroy(address[] calldata shareholders) external override whenNotPaused onlyOwner { for (uint256 i = 0; i < shareholders.length; i++) { require(shareholders[i] != owner(), "CM06"); uint256 shareholderBalance = balanceOf(shareholders[i]); _burn(shareholders[i], balanceOf(shareholders[i])); _mint(owner(), shareholderBalance); emit Transfer(shareholders[i], owner(), shareholderBalance); } emit LogDestroyed(shareholders); } /** * Purpose * Retrieve identity of a potential/actual shareholder */ function identity(address shareholder) external view override returns (bytes memory) { return identities[shareholder]; } /** * @notice Withdraws funds for a set of token holders */ function pushFunds(address[] memory owners) public whenNotPaused { for (uint256 i = 0; i < owners.length; i++) { _withdrawFundsFor(owners[i]); } } /** * @notice Overrides the parent class token transfer function to enforce restrictions. */ function transfer(address to, uint256 value) public override whenNotPaused returns (bool) { if (address(ruleEngine) != address(0)) { require(ruleEngine.validateTransfer(msg.sender, to, value), "CM04"); return super.transfer(to, value); } else { return super.transfer(to, value); } } /** * @notice Overrides the parent class token transferFrom function to enforce restrictions. */ function transferFrom(address from, address to, uint256 value) public override whenNotPaused returns (bool) { if (address(ruleEngine) != address(0)) { require(ruleEngine.validateTransfer(from, to, value), "CM04"); return super.transferFrom(from, to, value); } else { return super.transferFrom(from, to, value); } } /** * @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, uint256 _value) public override whenNotPaused returns (bool) { return super.approve(_spender, _value); } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address _spender, uint256 _addedValue) public override whenNotPaused returns (bool) { return super.increaseAllowance(_spender, _addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) public override whenNotPaused returns (bool) { return super.decreaseAllowance(_spender, _subtractedValue); } /** * @notice Purpose: Issue tokens on the owner() address * @param _value - amount of newly issued tokens */ function issue(uint256 _value) public override whenNotPaused onlyOwner { _mint(owner(), _value); emit Transfer(address(0), owner(), _value); emit LogIssued(_value); } /** * @notice Purpose: Redeem tokens on the owner() address * @param _value - amount of redeemed tokens */ function redeem(uint256 _value) public override whenNotPaused onlyOwner { _burn(owner(), _value); emit Transfer(owner(), address(0), _value); emit LogRedeemed(_value); } /** * @notice Exposes the ability to mint new FDTs for a given account. Caller has to be the owner of the FDT. */ function mint(address account, uint256 amount) public whenNotPaused onlyOwner returns (bool) { _mint(account, amount); return true; } /** * @notice Exposes the ability to burn exisiting FDTs for a given account. Caller has to be the owner of the FDT. */ function burn(address account, uint256 amount) public whenNotPaused onlyOwner returns (bool) { _burn(account, amount); return true; } /** * @dev check if _value token can be transferred from _from to _to * @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 canTransfer(address _from, address _to, uint256 _value) public view returns (bool) { if (paused()) return false; if (address(ruleEngine) != address(0)) return ruleEngine.validateTransfer(_from, _to, _value); return true; } /** * @dev check if _value token can be transferred from _from to _to * @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 * @return code of the rejection reason */ function detectTransferRestriction(address _from, address _to, uint256 _value) public view returns (uint8) { if (paused()) return TRANSFER_REJECTED_PAUSED; if (address(ruleEngine) != address(0)) return ruleEngine.detectTransferRestriction(_from, _to, _value); return TRANSFER_OK; } /** * @dev returns the human readable explaination corresponding to the error code returned by detectTransferRestriction * @param _restrictionCode The error code returned by detectTransferRestriction * @return The human readable explaination corresponding to the error code returned by detectTransferRestriction */ function messageForTransferRestriction(uint8 _restrictionCode) public view returns (string memory) { if (_restrictionCode == TRANSFER_OK) return TEXT_TRANSFER_OK; if (_restrictionCode == TRANSFER_REJECTED_PAUSED) return TEXT_TRANSFER_REJECTED_PAUSED; if (address(ruleEngine) != address(0)) return ruleEngine.messageForTransferRestriction(_restrictionCode); revert("CMTA20FDT.messageForTransferRestriction: INVALID_RESTRICTION_CODE"); } /** * @notice Withdraws all available funds for a token holder */ function _withdrawFundsFor(address owner) internal { uint256 withdrawableFunds = _prepareWithdrawFor(owner); require( fundsToken.transfer(owner, withdrawableFunds), "CMTA20FDT.withdrawFunds: TRANSFER_FAILED" ); _updateFundsTokenBalance(); } /** * @dev Updates the current funds token balance * and returns the difference of new and previous funds token balances * @return A int256 representing the difference of the new and previous funds token balance */ function _updateFundsTokenBalance() internal returns (int256) { uint256 prevFundsTokenBalance = fundsTokenBalance; fundsTokenBalance = fundsToken.balanceOf(address(this)); return int256(fundsTokenBalance).sub(int256(prevFundsTokenBalance)); } }
Purpose: Issue tokens on the owner() address _value - amount of newly issued tokens/
function issue(uint256 _value) public override whenNotPaused onlyOwner { _mint(owner(), _value); emit Transfer(address(0), owner(), _value); emit LogIssued(_value); }
5,474,370
/* Copyright 2018 Binod Nirvan Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; ///@title Custom Ownable ///@notice Custom ownable contract. contract CustomOwnable is Ownable { ///The trustee wallet. address private _trustee; event TrusteeAssigned(address indexed account); ///@notice Validates if the sender is actually the trustee. modifier onlyTrustee() { require(msg.sender == _trustee, "Access is denied."); _; } ///@notice Assigns or changes the trustee wallet. ///@param _account A wallet address which will become the new trustee. ///@return Returns true if the operation was successful. function assignTrustee(address _account) external onlyOwner returns(bool) { require(_account != address(0), "Please provide a valid address for trustee."); _trustee = _account; emit TrusteeAssigned(_account); return true; } ///@notice Changes the owner of this contract. ///@param _newOwner Specify a wallet address which will become the new owner. ///@return Returns true if the operation was successful. function reassignOwner(address _newOwner) external onlyTrustee returns(bool) { super._transferOwnership(_newOwner); return true; } ///@notice The trustee wallet has the power to change the owner in case of unforeseen or unavoidable situation. ///@return Wallet address of the trustee account. function getTrustee() external view returns(address) { return _trustee; } }
Changes the owner of this contract. _newOwner Specify a wallet address which will become the new owner.return Returns true if the operation was successful.
function reassignOwner(address _newOwner) external onlyTrustee returns(bool) { super._transferOwnership(_newOwner); return true; }
1,005,382
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/interfaces/IERC2981.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract Marketplace is OwnableUpgradeable, PausableUpgradeable, ERC721Holder { using SafeMath for uint256; using AddressUpgradeable for address; IERC20 private _tokenContract; event CollectionCreated(address indexed nftContractAddress); event CollectionRemoved(address indexed nftContractAddress); event CollectionUpdated(address indexed nftContractAddress, bool active); event FeeCollectorCreated( uint indexed index, address wallet, uint256 percentage ); event FeeCollectorRemoved( uint indexed index, address wallet ); event ItemCreated( bytes32 itemId, uint256 indexed tokenId, address indexed seller, address nftAddress, uint256 price, uint256 expiresAt, SaleType saleType ); event ItemCancelled(bytes32 indexed itemId, SaleStatus saleStatus, address user); event ItemSold(bytes32 indexed itemId, SaleStatus saleStatus, address user); event ItemBid(bytes32 indexed itemId, address user); event ItemExpired(bytes32 indexed itemId, SaleStatus saleStatus, address user); event SwapCreated( bytes32 indexed swapId, address fromCollection, uint256 fromTokenId, address fromUser, address toCollection, uint256 toTokenId, address toUser ); event SwapApproved(bytes32 indexed swapId, address user); event SwapRejected(bytes32 indexed swapId, address user); event SwapCancelled(bytes32 indexed swapId, address user); event AuctionExpiryExecuted(bytes32 _itemId, address user); enum SaleType { Direct, Auction } enum SaleStatus { Open, Sold, Cancel, Reject, Expired } struct Bid { address bidder; uint256 price; uint256 createdAt; bool selected; } struct Item { address nftAddress; uint256 tokenId; uint256 price; address seller; address buyer; uint256 createdAt; uint256 expiresAt; uint256 topBidIndex; uint256 topBidPrice; address topBidder; Bid[] bids; SaleType saleType; SaleStatus saleStatus; } mapping (bytes32 => Item) private _items; struct AuctionExpiry { bytes32 itemId; uint expiresAt; bool executed; } AuctionExpiry[] private _auctionExpiry; struct Collection { bool active; bool royaltySupported; string name; } mapping (address => Collection) public collections; struct FeeCollector { address wallet; uint256 percentage; } FeeCollector[] private _feeCollectors; struct Swap { address fromCollection; uint256 fromTokenId; address fromUser; address toCollection; uint256 toTokenId; address toUser; uint256 createdAt; SaleStatus saleStatus; } mapping (bytes32 => Swap) public swaps; address private jobExecutor; bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; address[] private _collectionIndex; uint256 public bidThreshold; /// mapping itemId => userAddress => amount mapping (bytes32 => mapping (address => uint256)) private _holdTokens; /// mapping collectionAddress => tokenId => ownerAddress mapping (address => mapping (uint256 => address)) private _holdNFTs; /// mapping saleType => percentage mapping (SaleType => uint256) public publicationFees; address private _publicationFeeWallet; bytes32[] private _itemIndex; mapping (bytes32 => Swap) private _swaps; bytes32[] private _swapIndex; /** * @dev Sets for token address * @param _tokenAddress Token address */ function initialize(address _tokenAddress) public initializer { _transferOwnership(_msgSender()); setTokenAddress(_tokenAddress); setJobExecutor(_msgSender()); bidThreshold = 50; } /** * @dev Only executor */ modifier onlyExecutor() { require(jobExecutor == _msgSender(), "Caller is not job executor"); _; } ///--------------------------------- PUBLIC FUNCTIONS --------------------------------- /** * @dev Seller of NFT * @param _nftContractAddress Collection address * @param _tokenId Token id * @return address Seller address */ function sellerOf( address _nftContractAddress, uint256 _tokenId ) public view returns(address) { return _holdNFTs[_nftContractAddress][_tokenId]; } /** * @dev Auction sell * @param _nftContractAddress NFT contract address * @param _tokenId NFT token id * @param _price NFT initial price * @param _expiresAt Expiry timestamp in UTC */ function auction( address _nftContractAddress, uint256 _tokenId, uint256 _price, uint256 _expiresAt ) public whenNotPaused { _isActiveCollection(_nftContractAddress); _createItem(_nftContractAddress, _tokenId, _price, _expiresAt, SaleType.Auction); } /** * @dev Direct sell * @param _nftContractAddress NFT contract address * @param _tokenId NFT token id * @param _price NFT price */ function sell( address _nftContractAddress, uint256 _tokenId, uint256 _price ) public whenNotPaused { _isActiveCollection(_nftContractAddress); _createItem(_nftContractAddress, _tokenId, _price, 0, SaleType.Direct); } /** * @dev Cancel market item * @param _itemId Item id */ function cancel(bytes32 _itemId) public whenNotPaused { Item storage item = _items[_itemId]; require(item.seller == _msgSender(), "Not token owner"); require(item.bids.length == 0, "Bid exists"); require(item.saleStatus == SaleStatus.Open || item.saleStatus == SaleStatus.Expired, "Item is unavailable"); /// release nft and transfer it to the seller IERC721 nftRegistry = IERC721(item.nftAddress); nftRegistry.safeTransferFrom(address(this), item.seller, item.tokenId); delete _holdNFTs[item.nftAddress][item.tokenId]; item.saleStatus = SaleStatus.Cancel; emit ItemCancelled(_itemId, SaleStatus.Cancel, _msgSender()); } /** * @dev Buy NFT from direct sales * @param _itemId Item ID */ function buy(bytes32 _itemId) public whenNotPaused { Item storage item = _items[_itemId]; require(item.seller != _msgSender(), "You are owner of this item"); _executePayment(_itemId, _msgSender()); item.buyer = _msgSender(); item.saleStatus = SaleStatus.Sold; IERC721(item.nftAddress).transferFrom(address(this), _msgSender(), item.tokenId); delete _holdNFTs[item.nftAddress][item.tokenId]; emit ItemSold(_itemId, SaleStatus.Sold, _msgSender()); } /** * @dev Bid to auction sales * @param _itemId Item ID */ function bid( bytes32 _itemId, uint256 _price ) public whenNotPaused { Item storage item = _items[_itemId]; require(item.seller != _msgSender(), "You are owner of this item"); require(_price >= (item.topBidPrice.add(item.topBidPrice.mul(bidThreshold).div(1000))), "Minimum bid price is required"); require(_tokenContract.balanceOf(_msgSender()) >= _price, "Not enough tokens"); require(_tokenContract.allowance(_msgSender(), address(this)) >= _price, "Not enough allowance"); if (item.saleType == SaleType.Auction && item.saleStatus == SaleStatus.Open) { uint256 bidIndex = 0; if (item.bids.length > 0) { bidIndex = item.bids.length - 1; if (_holdTokens[_itemId][item.topBidder] > 0) { _releaseHoldAmount(_itemId, item.topBidder, item.topBidder, item.topBidPrice); } } item.bids.push(Bid({ bidder: _msgSender(), price: _price, createdAt: block.timestamp, selected: false })); _putHoldAmount(_itemId, _msgSender(), _price); item.topBidIndex = bidIndex; item.topBidPrice = _price; item.topBidder = _msgSender(); if (item.expiresAt.sub(600) < block.timestamp && item.expiresAt > block.timestamp) { item.expiresAt = item.expiresAt.add(600); } emit ItemBid(_itemId, _msgSender()); } } /** * @dev Swap request * @param _fromCollection Collection ID * @param _fromTokenId Item ID * @param _toCollection Collection ID * @param _toTokenId Item ID */ function swap( address _fromCollection, uint256 _fromTokenId, address _toCollection, uint256 _toTokenId ) public whenNotPaused { _isActiveCollection(_fromCollection); _isActiveCollection(_toCollection); IERC721 fromCollection = IERC721(_fromCollection); IERC721 toCollection = IERC721(_toCollection); address fromTokenOwner = fromCollection.ownerOf(_fromTokenId); address toTokenOwner = toCollection.ownerOf(_toTokenId); require(_msgSender() == fromTokenOwner, "Not token owner"); require( (fromCollection.getApproved(_fromTokenId) == address(this) || fromCollection.isApprovedForAll(fromTokenOwner, address(this))) && (toCollection.getApproved(_toTokenId) == address(this) || toCollection.isApprovedForAll(toTokenOwner, address(this))), "The contract is not authorized" ); bytes32 swapId = keccak256( abi.encodePacked( block.timestamp, _fromCollection, _fromTokenId, _toCollection, _toTokenId ) ); _swaps[swapId] = Swap({ fromCollection: _fromCollection, fromTokenId: _fromTokenId, fromUser: fromTokenOwner, toCollection: _toCollection, toTokenId: _toTokenId, toUser: toTokenOwner, createdAt: block.timestamp, saleStatus: SaleStatus.Open }); _swapIndex.push(swapId); emit SwapCreated(swapId, _fromCollection, _fromTokenId, fromTokenOwner, _toCollection, _toTokenId, toTokenOwner); } /** * @dev Approve swap by receiver of NFT * @param _swapId Swap ID */ function approveSwap(bytes32 _swapId) public whenNotPaused { Swap storage _swap = _swaps[_swapId]; IERC721 fromCollection = IERC721(_swap.fromCollection); IERC721 toCollection = IERC721(_swap.toCollection); require(_swap.toUser == _msgSender(), "Not token owner"); require((fromCollection.ownerOf(_swap.fromTokenId) == _swap.fromUser) && (toCollection.ownerOf(_swap.toTokenId) == _msgSender()), "Not token owner"); require( (fromCollection.getApproved(_swap.fromTokenId) == address(this) || fromCollection.isApprovedForAll(_swap.fromUser, address(this))) && (toCollection.getApproved(_swap.toTokenId) == address(this) || toCollection.isApprovedForAll(_swap.toUser, address(this))), "The contract is not authorized" ); fromCollection.transferFrom(_swap.fromUser, _swap.toUser, _swap.fromTokenId); toCollection.transferFrom(_swap.toUser, _swap.fromUser, _swap.toTokenId); _swap.saleStatus = SaleStatus.Sold; emit SwapApproved(_swapId, _swap.toUser); } /** * @dev Reject swap by receiver of NFT * @param _swapId Swap ID */ function rejectSwap(bytes32 _swapId) public whenNotPaused { Swap storage _swap = _swaps[_swapId]; require(_swap.toUser == _msgSender(), "Not token owner"); _swap.saleStatus = SaleStatus.Reject; emit SwapRejected(_swapId, _swap.toUser); } /** * @dev Cancel swap by owner of NFT * @param _swapId Swap ID */ function cancelSwap(bytes32 _swapId) public whenNotPaused { Swap storage _swap = _swaps[_swapId]; require(_swap.fromUser == _msgSender(), "Not token owner"); _swap.saleStatus = SaleStatus.Cancel; emit SwapCancelled(_swapId, _swap.fromUser); } /** * @dev Get auction expiry * @return AuctionExpiry Array of auction expiry */ function getAuctionExpiry() public view returns(AuctionExpiry[] memory) { AuctionExpiry[] memory auctionData = new AuctionExpiry[](_auctionExpiry.length); for (uint256 i = 0; i < _auctionExpiry.length; i++) { AuctionExpiry storage auctionExpiry = _auctionExpiry[i]; if (auctionExpiry.expiresAt < block.timestamp && !auctionExpiry.executed) { auctionData[i] = auctionExpiry; } } return auctionData; } /** * @dev Get items with pagination supported * @param _startIndex Start with index number * @param _endIndex End with index number * @return uint256 Total of items * @return bytes32[] Array of item ids */ function getItems( uint _startIndex, uint _endIndex ) public view returns(uint256, bytes32[] memory) { bytes32[] memory itemData = new bytes32[](_itemIndex.length); if (_startIndex >= _itemIndex.length) { _startIndex = 0; } if (_endIndex >= _itemIndex.length) { _endIndex = _itemIndex.length.sub(1); } for (uint i = _startIndex; i <= _endIndex; i++) { itemData[i] = _itemIndex[i]; } return (_itemIndex.length, itemData); } /** * @dev Get item details * @param _itemId Item id * @return Item Item details */ function getItem(bytes32 _itemId) public view returns(Item memory) { Item storage item = _items[_itemId]; return item; } /** * @dev Get all bids of the item * @param _itemId Item id * @return Bid Array of bids */ function getBids(bytes32 _itemId) public view returns(Bid[] memory) { Item storage item = _items[_itemId]; Bid[] memory bidData = new Bid[](item.bids.length); for (uint256 i = 0; i < item.bids.length; i++) { Bid storage bidItem = item.bids[i]; bidData[i] = bidItem; } return bidData; } /** * @dev Get bid details * @param _itemId Sale item id * @param _bidIndex Index of bid * @return Bid Struct of bid */ function getBid(bytes32 _itemId, uint _bidIndex) public view returns(Bid memory) { Item storage item = _items[_itemId]; return item.bids[_bidIndex]; } /** * @dev Get list of swap ids * @param _startIndex Start with index number * @param _endIndex End with index number */ function getSwaps( uint _startIndex, uint _endIndex ) public view returns(uint256, bytes32[] memory) { bytes32[] memory itemData = new bytes32[](_swapIndex.length); if (_startIndex >= _swapIndex.length) { _startIndex = 0; } if (_endIndex >= _swapIndex.length) { _endIndex = _swapIndex.length.sub(1); } for (uint i = _startIndex; i <= _endIndex; i++) { itemData[i] = _swapIndex[i]; } return (_swapIndex.length, itemData); } /** * @dev Get swap details * @param _itemId Swap id */ function getSwap(bytes32 _itemId) public view returns(Swap memory) { Swap storage item = _swaps[_itemId]; return item; } /** * @dev Get royalty info * @param _tokenId Token id * @param _salePrice Token sale price */ function getRoyaltyInfo(address _nftContractAddress, uint256 _tokenId, uint256 _salePrice) external view returns(address receiverAddress, uint256 royaltyAmount) { return _getRoyaltyInfo(_nftContractAddress, _tokenId, _salePrice); } /** * @dev Tells wether royalty is supported or not * @param _nftContractAddress Collection address * @return bool */ function checkRoyalties(address _nftContractAddress) external view returns(bool) { return _isRoyaltiesSupport(_nftContractAddress); } ///--------------------------------- ADMINISTRATION FUNCTIONS --------------------------------- /** * @dev Set ERC20 contract address * @param _tokenAddress ERC20 contract address */ function setTokenAddress(address _tokenAddress) public onlyOwner { _tokenContract = IERC20(_tokenAddress); } /** * @dev Pause the public function */ function pause() public onlyOwner { _pause(); } /** * @dev Unpause the public function */ function unpause() public onlyOwner { _unpause(); } /** * @dev Get collections * @return Collection Collection array */ function getCollections() public view returns(Collection[] memory) { Collection[] memory collectionArray = new Collection[](_collectionIndex.length); for (uint256 i = 0; i < _collectionIndex.length; i++) { Collection storage collection = collections[_collectionIndex[i]]; collectionArray[i] = collection; } return collectionArray; } /** * @dev Create collection * @param _nftContractAddress NFT contract address for the collection * @param _active Active status of the collection */ function createCollection( address _nftContractAddress, bool _active, string memory _name ) public onlyOwner { _requireERC721(_nftContractAddress); collections[_nftContractAddress] = Collection({ active: _active, royaltySupported: _isRoyaltiesSupport(_nftContractAddress), name: _name }); _collectionIndex.push(_nftContractAddress); emit CollectionCreated(_nftContractAddress); } /** * @dev Remove collection * @param _nftContractAddress NFT contract address for the collection */ function removeCollection(address _nftContractAddress) public onlyOwner { delete collections[_nftContractAddress]; for (uint i = 0; i < _collectionIndex.length; i++) { if (_collectionIndex[i] == _nftContractAddress) { _collectionIndex[i] = _collectionIndex[_collectionIndex.length - 1]; } } _collectionIndex.pop(); emit CollectionRemoved(_nftContractAddress); } /** * @dev Update collection * @param _nftContractAddress NFT contract address * @param _active Active status of the collection */ function updateCollection( address _nftContractAddress, bool _active ) public onlyOwner { Collection storage collection = collections[_nftContractAddress]; collection.active = _active; emit CollectionUpdated( _nftContractAddress, _active ); } /** * @dev Get fee collectors * @return FeeCollector Array of fee collectors */ function getFeeCollectors() public view onlyOwner returns(FeeCollector[] memory) { FeeCollector[] memory feeCollectorArray = new FeeCollector[](_feeCollectors.length); for (uint256 i = 0; i < _feeCollectors.length; i++) { FeeCollector storage feeCollector = _feeCollectors[i]; feeCollectorArray[i] = feeCollector; } return feeCollectorArray; } /** * @dev Add fee collector * @param _wallet Wallet address * @param _percentage Percentage amount (dividing for 1000) */ function addFeeCollector( address _wallet, uint256 _percentage ) public onlyOwner { require(_percentage <= 30000, "Percentage must be less than 30%"); _feeCollectors.push(FeeCollector({ wallet: _wallet, percentage: _percentage })); uint index = _feeCollectors.length; emit FeeCollectorCreated( index, _wallet, _percentage ); } /** * @dev Remove fee collector * @param _wallet FeeCollector address */ function removeFeeCollector(address _wallet) public onlyOwner { FeeCollector memory removedFeeCollector; uint _index = 0; for (uint i = 0; i < _feeCollectors.length; i++) { if (_feeCollectors[i].wallet == _wallet) { _feeCollectors[i] = _feeCollectors[_feeCollectors.length - 1]; _feeCollectors[_feeCollectors.length - 1] = removedFeeCollector; _index = i; } } _feeCollectors.pop(); emit FeeCollectorRemoved( _index, _wallet ); } /** * @dev Owner can transfer NFT to the user for emergency purpose * @param _nftContractAddress NFT contract address * @param _tokenId Token id * @param _to Receiver address */ function emergencyTransferTo( address _nftContractAddress, address _to, uint256 _tokenId ) public onlyOwner { IERC721(_nftContractAddress).safeTransferFrom(address(this), _to, _tokenId); } /** * @dev Emergency cancel(de-listing) sale item by admin * @dev This cancellation is remove NFT from storage but still owned by this contract * @dev So we need to transfer out manually by calling emergencyTransferTo() function * @param _itemId Item id */ function emergencyCancel(bytes32 _itemId) public onlyOwner { Item storage item = _items[_itemId]; require(item.saleStatus == SaleStatus.Open, "Item is unavailable"); delete _holdNFTs[item.nftAddress][item.tokenId]; /// revoke last bid if exists if (item.bids.length > 0) { _releaseHoldAmount(_itemId, item.topBidder, item.topBidder, item.topBidPrice); } item.saleStatus = SaleStatus.Reject; emit ItemCancelled(_itemId, SaleStatus.Reject, _msgSender()); } /** * @dev Set job executor * @param _jobExecutor Job executor address */ function setJobExecutor(address _jobExecutor) public onlyOwner { jobExecutor = _jobExecutor; } /** * @dev Set bid threshold * @param _percentage Percentage */ function setBidThreshold(uint256 _percentage) public onlyOwner { bidThreshold = _percentage; } /** * @dev Set publication fee * @param _saleType Sales type * @param _amount Fixed amount */ function setPublicationFee(SaleType _saleType, uint256 _amount) public onlyOwner { publicationFees[_saleType] = _amount; } /** * @dev Set the address of publication fee * @param _wallet Wallet address */ function setPublicationFeeWallet(address _wallet) public onlyOwner { _publicationFeeWallet = _wallet; } /** * @dev Get the address of publication fee * @return address */ function getPublicationFeeWallet() public onlyOwner view returns(address) { return _publicationFeeWallet; } /** * @dev This function is used for executes all expired auctions * System will automatically select the highest price */ function executeJob() public onlyExecutor { for (uint256 i = 0; i < _auctionExpiry.length; i++) { AuctionExpiry storage auctionExpiry = _auctionExpiry[i]; if (auctionExpiry.expiresAt < block.timestamp && !auctionExpiry.executed) { Item storage item = _items[auctionExpiry.itemId]; if (item.saleStatus == SaleStatus.Open) { if (item.bids.length > 0) { item.buyer = item.topBidder; item.price = item.topBidPrice; item.saleStatus = SaleStatus.Sold; _executePayment(auctionExpiry.itemId, item.buyer); IERC721(item.nftAddress).transferFrom(address(this), item.buyer, item.tokenId); delete _holdNFTs[item.nftAddress][item.tokenId]; for (uint256 j = 0; j < item.bids.length; j++) { if (item.bids[j].price == item.topBidPrice && item.bids[j].bidder == item.topBidder) { item.bids[j].selected = true; break; } } emit ItemSold(auctionExpiry.itemId, SaleStatus.Sold, _msgSender()); } else { IERC721(item.nftAddress).transferFrom(address(this), item.seller, item.tokenId); delete _holdNFTs[item.nftAddress][item.tokenId]; item.saleStatus = SaleStatus.Expired; emit ItemExpired(auctionExpiry.itemId, SaleStatus.Expired, _msgSender()); } emit AuctionExpiryExecuted(auctionExpiry.itemId, _msgSender()); } } } } ///--------------------------------- INTERNAL FUNCTIONS --------------------------------- /** * @dev Hold tokens by transfer amount of the bidder to this contract */ function _putHoldAmount( bytes32 _itemId, address _user, uint256 _amount ) internal { _holdTokens[_itemId][_user] = _holdTokens[_itemId][_user].add(_amount); _tokenContract.transferFrom(_user, address(this), _amount); } /** * @dev Sent back the held amount of the previous loser to their wallet * @param _itemId Item id * @param _user Wallet address of the user * @param _to Receiver wallet * @param _amount Amount of tokens */ function _releaseHoldAmount( bytes32 _itemId, address _user, address _to, uint256 _amount ) internal { _holdTokens[_itemId][_user] = _holdTokens[_itemId][_user].sub(_amount); _tokenContract.transfer(_to, _amount); } function _isRoyaltiesSupport(address _nftContractAddress) private view returns(bool) { (bool success) = IERC2981(_nftContractAddress).supportsInterface(_INTERFACE_ID_ERC2981); return success; } function _getRoyaltyInfo(address _nftContractAddress, uint256 _tokenId, uint256 _salePrice) private view returns(address receiverAddress, uint256 royaltyAmount) { IERC2981 nftContract = IERC2981(_nftContractAddress); (address _royaltiesReceiver, uint256 _royalties) = nftContract.royaltyInfo(_tokenId, _salePrice); return(_royaltiesReceiver, _royalties); } /** * @dev Create sale item * @param _nftContractAddress Collection address * @param _tokenId Token id * @param _price Item price * @param _expiresAt Expiry date * @param _saleType Sales type */ function _createItem( address _nftContractAddress, uint256 _tokenId, uint256 _price, uint256 _expiresAt, SaleType _saleType ) internal { IERC721 nftRegistry = IERC721(_nftContractAddress); address sender = _msgSender(); address tokenOwner = nftRegistry.ownerOf(_tokenId); require(sender == tokenOwner, "Not token owner"); require(_price > 0, "Price should be bigger than 0"); require( nftRegistry.getApproved(_tokenId) == address(this) || nftRegistry.isApprovedForAll(tokenOwner, address(this)), "The contract is not authorized" ); /// charge publication fees if (publicationFees[_saleType] > 0 && _publicationFeeWallet != address(0)) { uint256 fees = publicationFees[_saleType]; require(_tokenContract.allowance(sender, address(this)) >= fees, "Insufficient allowance"); _tokenContract.transferFrom(sender, _publicationFeeWallet, fees); } bytes32 itemId = keccak256( abi.encodePacked( block.timestamp, tokenOwner, _tokenId, _nftContractAddress, _price, _saleType ) ); Item storage item = _items[itemId]; item.nftAddress = _nftContractAddress; item.tokenId = _tokenId; item.price = _price; item.seller = tokenOwner; item.createdAt = block.timestamp; item.expiresAt = _expiresAt; item.saleType = _saleType; item.saleStatus = SaleStatus.Open; if (_saleType == SaleType.Auction) { _auctionExpiry.push(AuctionExpiry({ itemId: itemId, expiresAt: item.expiresAt, executed: false })); } /// hold nft and transfer NFT to this cointract nftRegistry.safeTransferFrom(tokenOwner, address(this), _tokenId); _holdNFTs[_nftContractAddress][_tokenId] = tokenOwner; _itemIndex.push(itemId); emit ItemCreated(itemId, _tokenId, tokenOwner, _nftContractAddress, _price, _expiresAt, _saleType); } /** * @dev Required ERC721 implementation * @param _nftContractAddress NFT contract(collection) address */ function _requireERC721(address _nftContractAddress) internal view { require(_nftContractAddress.isContract(), "Invalid NFT Address"); require( IERC721(_nftContractAddress).supportsInterface(_INTERFACE_ID_ERC721), "Unsupported ERC721 Interface" ); bool isExists = false; for (uint i = 0; i < _collectionIndex.length; i++) { if (_collectionIndex[i] == _nftContractAddress) { isExists = true; break; } } require(!isExists, "Existance collection"); } /** * @dev Check is active collection * @param _nftContractAddress NFT contract address */ function _isActiveCollection(address _nftContractAddress) internal view { Collection storage collection = collections[_nftContractAddress]; require(collection.active, "Inactive Collection"); } /** * @dev Execute payment * @param _itemId Item id * @param _sender Sender address */ function _executePayment( bytes32 _itemId, address _sender ) internal virtual { Item storage item = _items[_itemId]; /// validate sale item require(item.price > 0, "Item is unavailable"); uint256 toTransfer = item.price; uint256 price = item.price; if (item.saleType == SaleType.Auction) { require(_holdTokens[_itemId][_sender] >= item.price, "Not enough funds"); for (uint256 i = 0; i < _feeCollectors.length; i++) { if (_feeCollectors[i].wallet != address(0) && _feeCollectors[i].percentage > 0) { uint256 fees = price.mul(_feeCollectors[i].percentage).div(1000); _releaseHoldAmount(_itemId, _sender, _feeCollectors[i].wallet, fees); toTransfer -= fees; } } (address royaltiesReceiver, uint256 royalty) = _getRoyaltyInfo(item.nftAddress, item.tokenId, price); if (royaltiesReceiver != address(0) && royalty > 0) { _releaseHoldAmount(_itemId, _sender, royaltiesReceiver, royalty); toTransfer -= royalty; } require(_tokenContract.balanceOf(address(this)) >= toTransfer, "Transfer to seller failed"); _releaseHoldAmount(_itemId, _sender, item.seller, toTransfer); } else { require(_tokenContract.balanceOf(_sender) >= item.price, "Not enough funds"); require(_tokenContract.allowance(_sender, address(this)) >= price, "Not enough tokens"); _tokenContract.transferFrom(_sender, address(this), price); for (uint256 i = 0; i < _feeCollectors.length; i++) { if (_feeCollectors[i].wallet != address(0) && _feeCollectors[i].percentage > 0) { uint256 fees = price.mul(_feeCollectors[i].percentage).div(1000); _tokenContract.transfer(_feeCollectors[i].wallet, fees); toTransfer -= fees; } } (address royaltiesReceiver, uint256 royalty) = _getRoyaltyInfo(item.nftAddress, item.tokenId, price); if (royaltiesReceiver != address(0) && royalty > 0) { _tokenContract.transfer(royaltiesReceiver, royalty); toTransfer -= royalty; } require(_tokenContract.balanceOf(address(this)) >= toTransfer, "Transfer to seller failed"); _tokenContract.transfer(item.seller, toTransfer); } } }
Remove collection _nftContractAddress NFT contract address for the collection/
function removeCollection(address _nftContractAddress) public onlyOwner { delete collections[_nftContractAddress]; for (uint i = 0; i < _collectionIndex.length; i++) { if (_collectionIndex[i] == _nftContractAddress) { _collectionIndex[i] = _collectionIndex[_collectionIndex.length - 1]; } } _collectionIndex.pop(); emit CollectionRemoved(_nftContractAddress); }
7,212,259
./partial_match/1313161554/0xC9A848AC73e378516B16E4EeBBa5ef6aFbC0BBc2/sources/AuriFairLaunch.sol
Add a new lp to the pool. Can only be called by the owner. _stakeToken: token to be staked to the pool _startTime: timestamp where the reward starts _endTime: timestamp where the reward ends _rewardPerSeconds: amount of reward token per second for the pool for each reward token/
function addPool( address _stakeToken, uint32 _startTime, uint32 _endTime, uint256[] calldata _rewardPerSeconds ) external nonReentrant onlyOwner { require(!poolExists[_stakeToken], "add: duplicated pool"); require(_stakeToken != address(0), "add: invalid stake token"); require(rewardTokens.length == _rewardPerSeconds.length, "add: invalid length"); require(_startTime > block.timestamp && _endTime > _startTime, "add: invalid times"); poolInfo[poolLength].stakeToken = _stakeToken; poolInfo[poolLength].startTime = _startTime; poolInfo[poolLength].endTime = _endTime; poolInfo[poolLength].lastRewardTimestamp = _startTime; for (uint256 i = 0; i < _rewardPerSeconds.length; i++) { poolInfo[poolLength].poolRewardData[i] = PoolRewardData({ rewardPerSecond: _rewardPerSeconds[i], accRewardPerShare: 0 }); } poolLength++; poolExists[_stakeToken] = true; emit AddNewPool(_stakeToken, _startTime, _endTime, _rewardPerSeconds); }
16,937,396
./full_match/1/0x23F8B0B57723bcD99D5Be4Cf4863E49D8092dC14/sources/contracts/LbdToken.sol
Increase the amount of tokens that an owner has allowed to a spender. This method should be used instead of approve() to avoid the double approval vulnerability described above. spender The address which will spend the funds. addedValue The amount of tokens to increase the allowance by./
function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); _allowedLBD[msg.sender][spender] = _allowedLBD[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedLBD[msg.sender][spender]); return true; }
8,354,433
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 interface ERC20Interface { //Get the totalSupply of the token. function totalSupply() external constant returns (uint256); // Get the account balance of another account with address _owner function balanceOf(address _owner) external constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) external returns (bool success); // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. // this function is required for some DEX functionality function approve(address _spender, uint256 _value) external returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) external constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract STTInterface is ERC20Interface { function BuyTokens () external payable returns (uint256 AtokenBought); event Mint(address indexed _to, uint256 amount); function SellTokens (uint256 SellAmount) external payable returns (uint256 EtherPaid); function split() external returns (bool success); event Split(uint256 factor); function getReserve() external constant returns (uint256); function burn(uint256 _value) external returns (bool success); event Burn(address indexed _burner, uint256 value); } contract AToken is STTInterface { using SafeMath for uint256; //ERC20 stuff // ************************************************************************ // // Constructor and initializer // // ************************************************************************ uint256 public _totalSupply = 10000000000000000000000; string public name = "A-Token"; string public symbol = "A"; uint8 public constant decimals = 18; mapping(address => uint256) public balances; mapping(address => mapping (address => uint256)) public allowed; //Arry and map for the split. address[] private tokenHolders; mapping(address => bool) private tokenHoldersMap; //Constructor constructor() public { balances[msg.sender] = _totalSupply; tokenHolders.push(msg.sender); tokenHoldersMap[msg.sender] = true; } //************************************************************************* // // Methods for all states // // ************************************************************************ // ERC20 stuff event Transfer(address indexed _from, address indexed _to, uint256 _amount); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); function balanceOf(address _addr) external constant returns(uint256 balance) { return balances[_addr]; } function transfer(address _to, uint256 _amount) external returns(bool success) { require(_amount > 0); require(_amount <= balances[msg.sender]); require (_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); if(tokenHoldersMap[_to] != true) { tokenHolders.push(_to); tokenHoldersMap[_to] = true; } emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) external returns(bool success) { require(_from != address(0)); require(_to != address (0)); require(_amount > 0); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); if(tokenHoldersMap[_to] != true) { tokenHolders.push(_to); tokenHoldersMap[_to] = true; } emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _amount) external returns(bool success) { require(_spender != address(0)); require(_amount > 0); require(_amount <= balances[msg.sender]); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) external constant returns(uint256 remaining) { require(_owner != address(0)); require(_spender != address(0)); return allowed[_owner][_spender]; } function totalSupply() external constant returns (uint) { return _totalSupply - balances[address(0)]; } // Self tradable functions event Mint(address indexed _to, uint256 amount); event Split(uint256 factor); event Burn(address indexed _burner, uint256 value); function BuyTokens () external payable returns ( uint256 AtokenBought) { address thisAddress = this; //checking minimum buy - twice the price uint256 Aprice = (thisAddress.balance - msg.value) * 4*2* 1000000000000000000/_totalSupply; require (msg.value>=Aprice); //calculating the formula AtokenBought = (thisAddress.balance -206000)* 1000000000000000000/ (thisAddress.balance-msg.value); uint256 x = (1000000000000000000 + AtokenBought)/2; x = (x + (AtokenBought * 1000000000000000000/x))/2; x = (x + (AtokenBought * 1000000000000000000/x))/2; x = (x + (AtokenBought * 1000000000000000000/x))/2; x = (x + (AtokenBought * 1000000000000000000/x))/2; x = (x + (AtokenBought * 1000000000000000000/x))/2; AtokenBought=x; x = (1000000000000000000 + AtokenBought)/2; x = (x + (AtokenBought * 1000000000000000000/x))/2; x = (x + (AtokenBought * 1000000000000000000/x))/2; x = (x + (AtokenBought * 1000000000000000000/x))/2; x = (x + (AtokenBought * 1000000000000000000/x))/2; x = (x + (AtokenBought * 1000000000000000000/x))/2; AtokenBought=x; AtokenBought -=1000000000000000000; AtokenBought = AtokenBought * _totalSupply/1000000000000000000; //checking the outcome uint256 check1=(msg.value-206000)*_totalSupply/(thisAddress.balance-msg.value)/4; require(check1>=AtokenBought); //doing the buy _totalSupply +=AtokenBought; balances[msg.sender] += AtokenBought; if(tokenHoldersMap[msg.sender] != true) { tokenHolders.push(msg.sender); tokenHoldersMap[msg.sender] = true; } emit Mint(msg.sender, AtokenBought); emit Transfer(address(0), msg.sender, AtokenBought); return AtokenBought; } function SellTokens (uint256 SellAmount) external payable returns (uint256 EtherPaid) { //re-entry defense bool locked; require(!locked); locked = true; //first check amount is equal or higher than 1 token require(SellAmount>=1000000000000000000); //calculating the formula require(msg.value>=206000); //Never going down from 300 tokens. require((_totalSupply-SellAmount)>=300000000000000000000); require(balances[(msg.sender)]>=SellAmount); address thisAddress = this; EtherPaid = (_totalSupply -SellAmount)*1000000000000000000/_totalSupply; EtherPaid=1000000000000000000-(((EtherPaid**2/1000000000000000000)*(EtherPaid**2/1000000000000000000))/1000000000000000000); EtherPaid=(EtherPaid*(thisAddress.balance-msg.value))*9/10000000000000000000; //checking the calculation uint256 check1=SellAmount*(thisAddress.balance-msg.value)*36/_totalSupply/10; require(check1>EtherPaid); require(EtherPaid<(thisAddress.balance-msg.value)); //paying the ether balances[msg.sender] -= SellAmount; _totalSupply-=SellAmount; emit Burn(msg.sender, SellAmount); emit Transfer(msg.sender, address(0), SellAmount); msg.sender.transfer(EtherPaid); locked=false; return EtherPaid; } //split function to lower the price. function split() external returns (bool success){ address thisContracrt = this; //calculating the factor uint256 factor = thisContracrt.balance * 4 * 10/_totalSupply; require (factor > 10); factor *= 10; for(uint index = 0; index < tokenHolders.length; index++) { balances[tokenHolders[(index)]] *=factor ; } _totalSupply *=factor; emit Split(factor); return true; } //get reserve information function getReserve() external constant returns (uint256){ address thissmart=this; return thissmart.balance; } // Burn function function burn(uint256 _value) external returns (bool success){ require(_value > 0); require(_value <= balances[msg.sender]); require(_totalSupply-_value>=300000000000000000000); balances[msg.sender] = balances[msg.sender].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true; } //FallBack function function () public payable {} }
calculating the factor
function split() external returns (bool success){ address thisContracrt = this; uint256 factor = thisContracrt.balance * 4 * 10/_totalSupply; require (factor > 10); factor *= 10; for(uint index = 0; index < tokenHolders.length; index++) { balances[tokenHolders[(index)]] *=factor ; } _totalSupply *=factor; emit Split(factor); return true; }
1,164,775
./full_match/1/0xcb6Ea7fddFdf2AFc2Bc6Bf715185A33F8E27B96b/sources/@pendle/core-v2/contracts/core/YieldContracts/PendleYieldToken.sol
Redeems interests and rewards for `user` redeemInterest will only transfer out interest for user if true redeemRewards will only transfer out rewards for user if true With YT yielding interest in the form of SY, which is redeemable by users, the reward distribution should be based on the amount of SYs that their YT currently represent, plus their dueInterest. It has been proven and tested that _rewardSharesUser will not change over time, unless users redeem their dueInterest or redeemPY. Due to this, it is required to update users' accruedReward STRICTLY BEFORE transferring out their interest./ if redeemRewards == true, this line must be here for obvious reason if redeemInterest == true, this line must be here because of the reason above
function redeemDueInterestAndRewards( address user, bool redeemInterest, bool redeemRewards ) external nonReentrant updateData returns (uint256 interestOut, uint256[] memory rewardsOut) { if (!redeemInterest && !redeemRewards) revert Errors.YCNothingToRedeem(); _updateAndDistributeRewards(user); if (redeemRewards) { rewardsOut = _doTransferOutRewards(user, user); emit RedeemRewards(user, rewardsOut); address[] memory tokens = getRewardTokens(); rewardsOut = new uint256[](tokens.length); } if (redeemInterest) { _distributeInterest(user); interestOut = _doTransferOutInterest(user, SY, factory); emit RedeemInterest(user, interestOut); interestOut = 0; } }
3,061,755
pragma solidity ^0.5.12; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; contract minterests is Ownable, ReentrancyGuard { using SafeMath for uint256; /** * @dev Represents the balance of a given user. The 'previous' field is used to store the * balance of the previous month in order to ponderate the bond's held time when updating * interests. */ struct Balance { // Total number of tokens held last month. uint256 previousBalance; // Total number of tokens held atm. uint256 currentBalance; // Total number of months these tokens have been held as of last month. uint256 previousHolding; // Total number of months these tokens have been held atm. uint256 currentHolding; // How much tokens has been bought through referral. uint256 refereeBalance; } /** * @dev Represents the claiming informations of an investor : * Whether he is claiming and in which currency he whishes to get paid. */ struct Claiming { // Tells wether investor is claiming its interests or not. bool claiming; // The currency type to be delivered, Euro or Ether. bytes32 currency; // The name of the bond partition to be redeemed. bytes32 partitionNameInHex; } /** * @dev Represents all about an investor. */ struct Info { // Calculated according to the balance, the held time, and the token type. // It needs to be multiplied by 10 to get the € value. uint256 balanceInterests; // User status about his willing to claim its interests. Claiming claimingInterests; // User status about his willing to redeem its midterm or longterm bonds. Claiming claimingBonds; // Total of midterm bond tokens. Balance mid; // Total of longterm bond tokens. Balance lng; // Total of perpetual bond tokens. Balance per; } // The state of each investor. mapping (address => Info) investors; // A list of "superuser" that have control over a few methods of this contract, // not a controller as in ERC1400. Used to allow third-parties to update an investor's // infos. mapping (address => bool) _isInterestsController; // To what extent an interest unit can be divided (10^18). uint256 DECIMALS = 1000000000000000000; /**************************** MWT_interests events ********************************/ // Emitted when an investor invested through a referal link. event Refered ( address indexed referer, address indexed referee, uint256 midAmount, uint256 lngAmount, uint256 perAmount ); // Emitted when the balance of an investor which invested through // a referal link is updated. event ModifiedReferee ( address indexed investor, uint256 midAmount, uint256 lngAmount, uint256 perAmount ); // Emitted when an investor's interests balance is modified. event UpdatedInterests ( address indexed investor, uint256 interests ); // Special case when a controller directly modified an investor's // interests balance. event ModifiedInterests ( address indexed investor, uint256 value ); // Emitted when an "interest controller" is addded or removed. event ModifiedInterestsController ( address indexed controller, bool value ); // Emitted when the claiming state of the investor is modified. event ModifiedClaimingInterests ( address indexed investor, bool claiming, bytes32 currency ); // Emitted when an user's interests are to be paid in euros by // the third party. event WillBePaidInterests ( address indexed investor, uint256 balanceInterests ); // Emitted when the bonds claiming status of an investor changed. event ModifiedClaimingBonds ( address indexed investor, bool claiming, bytes32 currency, bytes32 partitionNameInHex ); // Emitted when an user's bonds are to be paid in euros by // the third party. event WillBePaidBonds ( address indexed investor, bytes32 partitionNameInHex, uint256 claimedAmount ); // Emitted when the number of months an investor has been holding // each bond is modified. It's modified when a month has passed, // when the bonds are redeemed, or when set ad hoc by the contract // owner. event ModifiedHoldings ( address indexed investor, uint256 midHolding, uint256 lngHolding, uint256 perHolding ); // Emitted when an user redeems more bonds that we know he got. This // seems sneaky, and actually it is : the bonds balance is on another // contract (ERC1400) and we know about the actual balance of the // investor when we call `updateInterests`, once each month... event ModifiedHoldingsAndBalanceError ( address indexed investor, bytes32 partitionNameInHex, uint256 holding, uint256 balance ); // Emitted when an investor's interests balance is modified. It's // modified when one month has passed, when bonds are redeemed, or // when the balance is set ad hoc by the contract owner. event ModifiedBalances ( address indexed investor, uint256 midBalance, uint256 lngBalance, uint256 perBalance ); /**************************** MWT_interests getters ********************************/ /** * @dev Get the interests balance of an investor. */ function interestsOf (address investor) external view returns (uint256) { return (investors[investor].balanceInterests); } /** * @dev Check whether an address is an "interest controller" (a third-party superuser). */ function isInterestsController (address _address) external view returns (bool) { return (_isInterestsController[_address]); } /** * @dev Check whether an investor is currently claiming its interests, and in which currency. */ function isClaimingInterests (address investor) external view returns (bool, bytes32) { return (investors[investor].claimingInterests.claiming, investors[investor].claimingInterests.currency); } /** * @dev Check whether an investor is currently claiming its bonds, which one(s), and in which currency. */ function isClaimingBonds (address investor) external view returns (bool, bytes32, bytes32) { return ( investors[investor].claimingBonds.claiming, investors[investor].claimingBonds.currency, investors[investor].claimingBonds.partitionNameInHex ); } /** * @dev Get the midterm bond infos of an investor. */ function midtermBondInfosOf (address investor) external view returns ( uint256, uint256, uint256 ) { return ( investors[investor].mid.currentBalance, investors[investor].mid.currentHolding, investors[investor].mid.refereeBalance ); } /** * @dev Get the longterm bond infos of an investor. */ function longtermBondInfosOf (address investor) external view returns ( uint256, uint256, uint256 ) { return ( investors[investor].lng.currentBalance, investors[investor].lng.currentHolding, investors[investor].lng.refereeBalance ); } /** * @dev Get the perpetual bond infos of an investor. */ function perpetualBondInfosOf (address investor) external view returns ( uint256, uint256, uint256 ) { return ( investors[investor].per.currentBalance, investors[investor].per.currentHolding, investors[investor].per.refereeBalance ); } /**************************** MWT_interests external functions ********************************/ /** * @dev Allows an investor to express his desire to redeem his interests. */ function claimInterests (bool claiming, bytes32 _currency) external { bytes32 currency = _currency; require (currency == "eur" || currency == "eth", "A8"); // Transfer Blocked - Token restriction uint256 minimum = currency == "eth" ? 10 : 100; // ie: 100 euros require (investors[msg.sender].balanceInterests >= minimum.mul(DECIMALS), "A6"); // Transfer Blocked - Receiver not eligible if (!claiming) { currency = ""; } investors[msg.sender].claimingInterests.claiming = claiming; investors[msg.sender].claimingInterests.currency = currency; emit ModifiedClaimingInterests (msg.sender, claiming, currency); } /** * @dev This function updates interests balance for several investors, so that they can be paid by the third party. */ function payInterests (address[] calldata investorsAddresses) external nonReentrant { require (_isInterestsController[msg.sender], "A5"); // Your are not allowed to perform this action for (uint i = 0; i < investorsAddresses.length; i++) { require (investors[investorsAddresses[i]].claimingInterests.claiming, "A6"); // This investor is not currently claiming investors[investorsAddresses[i]].claimingInterests.claiming = false; investors[investorsAddresses[i]].claimingInterests.currency = ""; emit ModifiedClaimingInterests(investorsAddresses[i], false, ""); emit WillBePaidInterests(investorsAddresses[i], investors[investorsAddresses[i]].balanceInterests); investors[investorsAddresses[i]].balanceInterests = 0; emit UpdatedInterests(investorsAddresses[i], investors[investorsAddresses[i]].balanceInterests); } } /** * @dev Allows an investor to claim one of its bonds. */ function claimBond (bool claiming, bytes32 _currency, bytes32 partition) external { uint256 bondYear = 0; uint256 bondMonth = 0; bytes32 currency = _currency; require (currency == "eur" || currency == "eth", "A8"); // Transfer Blocked - Token restriction // This function is only for midterm and longterm bonds, which have a restricted period // before they can be withdrawn. // We use 3 utf8 characters in each partition to identify it ("mid" for the midterm ones and "lng" for the longterm // ones). require ((partition[0] == "m" && partition[1] == "i" && partition[2] == "d") || (partition[0] == "l" && partition[1] == "n" && partition[2] == "g"), "A6"); // Retrieving the bond issuance date (YYYYMM) from an UTF8 encoded string. for (uint i = 4; i < 10; i++) { // Is it a valid UTF8 digit ? https://www.utf8-chartable.de/unicode-utf8-table.pl require ((uint8(partition[i]) >= 48) && (uint8(partition[i]) <= 57), "A6"); // Transfer Blocked - Receiver not eligible } // The first digit is the millenium. bondYear = bondYear.add(uint256(uint8(partition[4])).sub(48).mul(1000)); // The second one is the century. bondYear = bondYear.add(uint256(uint8(partition[5])).sub(48).mul(100)); // The third one is the <is there a name for a ten year period ?>. bondYear = bondYear.add(uint256(uint8(partition[6])).sub(48).mul(10)); // The fourth one is the year unit. bondYear = bondYear.add(uint256(uint8(partition[7])).sub(48)); // Same for month, but it has only two digits. bondMonth = bondMonth.add(uint256(uint8(partition[8])).sub(48).mul(10)); bondMonth = bondMonth.add(uint256(uint8(partition[9])).sub(48)); // Did the boutique decoding fucked up ? :-) require (bondYear >= 2000); require (bondMonth >= 0 && bondMonth <= 12); // Calculating the elapsed time since bond issuance uint256 elapsedMonths = (bondYear * 12 + bondMonth) - 23640; uint256 currentTime; assembly { currentTime := timestamp() } // conversion of the current time (in sec) since epoch to months uint256 currentMonth = currentTime / 2630016; uint256 deltaMonths = currentMonth - elapsedMonths; if (partition[0] == "m" && partition[1] == "i" && partition[2] == "d") { // This is a midterm bond, 5 years (60 months) should have passed. require (deltaMonths >= 60, "A6"); // Transfer Blocked - Receiver not eligible } else if (partition[0] == "l" && partition[1] == "n" && partition[2] == "g") { // This is a longterm bond, 10 years (120 months) should have passed. require (deltaMonths >= 120, "A6"); // Transfer Blocked - Receiver not eligible } else { // This is __not__ possible ! assert (false); } investors[msg.sender].claimingBonds.claiming = claiming; investors[msg.sender].claimingBonds.currency = claiming ? currency : bytes32(""); investors[msg.sender].claimingBonds.partitionNameInHex = claiming ? partition : bytes32(""); emit ModifiedClaimingBonds( msg.sender, claiming, investors[msg.sender].claimingBonds.currency, investors[msg.sender].claimingBonds.partitionNameInHex ); } /** * @dev This functions is called after the investor expressed its desire to redeem its bonds using the above * function (claimBonds). It needs to be called __before__ the third party pays the investor its bonds * in fiat. * * @param claimedAmount The balance of the investor on the redeemed partition. */ function payBonds (address investor, uint256 claimedAmount) external nonReentrant { require (_isInterestsController[msg.sender], "A5"); // You are not allowed to perform this action require (investors[investor].claimingBonds.claiming, "A6"); // This investor is not currently claiming investors[investor].claimingBonds.claiming = false; // This function is only for midterm and longterm bonds, which have a restricted period // before they can be withdrawn. // We use 3 utf8 characters in each partition to identify it ("mid" for the midterm ones and "lng" for the longterm // ones). bytes32 partition = investors[investor].claimingBonds.partitionNameInHex; require ((partition[0] == "m" && partition[1] == "i" && partition[2] == "d") || (partition[0] == "l" && partition[1] == "n" && partition[2] == "g"), "A6"); // If all balances of a partition type are empty, we need to reset the "holding" variable. uint256 midLeft = 0; uint256 lngLeft = 0; bool emitHoldingEvent = false; if (partition[0] == "m" && partition[1] == "i" && partition[2] == "d") { // For the midterm bonds. if (claimedAmount < investors[investor].mid.currentBalance) { // All partitions of this type are not empty, no need to update holding. midLeft = investors[investor].mid.currentBalance.sub(claimedAmount); } else if (claimedAmount == investors[investor].mid.currentBalance) { // The investor just withdrew all bonds from all partitions of this type. // There is a possibility that an investor could refill the __exact same__ amount of the // __same partition type__ before we update the interests, i.e. before the end of the month. // Example: let's be an investor with the foolowing balances. // mid_201001 = 200, mid_201801 = 200, currentBalance = mid_201001 + mid_201801 = 400 // If this investor refills mid_201801 with 200, then mid_201801 = 400 = currentBalance. // In that case, holding would be reseted whereas the investor still has 200 mid_201001 // Since this case should be extremly rare, we do not emit an error event. investors[investor].mid.previousHolding = 0; investors[investor].mid.currentHolding = 0; emitHoldingEvent = true; } else { // This case should normally not occur. // If the current holding is not up to date regarding token balances, it means that the // investor refilled its balance after claiming bonds but before we update the interests. // This period lasts at most one month. // We reset holding and balance too (which could mess up adjustmentRate), but we emit an event. emit ModifiedHoldingsAndBalanceError( investor, investors[investor].claimingBonds.partitionNameInHex, investors[investor].mid.currentHolding, investors[investor].mid.currentBalance ); investors[investor].mid.previousHolding = 0; investors[investor].mid.currentHolding = 0; emitHoldingEvent = true; } // There are some units left only if the investor had other partitions of the same type. investors[investor].mid.previousBalance = midLeft; investors[investor].mid.currentBalance = midLeft; } else if (partition[0] == "l" && partition[1] == "n" && partition[2] == "g") { if (claimedAmount < investors[investor].lng.currentBalance) { // All partitions of this type are not empty, no need to update holding. lngLeft = investors[investor].lng.currentBalance.sub(claimedAmount); } else if (claimedAmount == investors[investor].lng.currentBalance) { // Same as in the precedent branch, but with longterm bonds. investors[investor].lng.previousHolding = 0; investors[investor].lng.currentHolding = 0; emitHoldingEvent = true; } else { // See above for the details of this sneaky case.. emit ModifiedHoldingsAndBalanceError( investor, investors[investor].claimingBonds.partitionNameInHex, investors[investor].lng.currentHolding, investors[investor].lng.currentBalance ); investors[investor].lng.previousHolding = 0; investors[investor].lng.currentHolding = 0; emitHoldingEvent = true; } // There are some units left only if the investor had other partitions of the same type. investors[investor].lng.previousBalance = lngLeft; investors[investor].lng.currentBalance = lngLeft; } else { // We should __not__ get here ! assert (false); } emit WillBePaidBonds( investor, partition, claimedAmount ); investors[investor].claimingBonds.currency = ""; investors[investor].claimingBonds.partitionNameInHex = ""; emit ModifiedClaimingBonds( investor, false, investors[investor].claimingBonds.currency, investors[investor].claimingBonds.partitionNameInHex ); if (emitHoldingEvent) { emit ModifiedHoldings( investor, investors[investor].mid.currentHolding, investors[investor].lng.currentHolding, investors[investor].per.currentHolding ); } emit ModifiedBalances( investor, investors[investor].mid.currentBalance, investors[investor].lng.currentBalance, investors[investor].per.currentBalance ); } /** * @dev Set how much time an investor has been holding each bond. */ function setHoldings (address investor, uint256 midHolding, uint256 lngHolding, uint256 perHolding) external onlyOwner { investors[investor].mid.previousHolding = midHolding; investors[investor].mid.currentHolding = midHolding; investors[investor].lng.previousHolding = lngHolding; investors[investor].lng.currentHolding = lngHolding; investors[investor].per.previousHolding = perHolding; investors[investor].per.currentHolding = perHolding; emit ModifiedHoldings(investor, midHolding, lngHolding, perHolding); } /** * @dev Set custom balances for an investor. */ function setBalances (address investor, uint256 midBalance, uint256 lngBalance, uint256 perBalance) external onlyOwner { investors[investor].mid.previousBalance = midBalance; investors[investor].mid.currentBalance = midBalance; investors[investor].lng.previousBalance = lngBalance; investors[investor].lng.currentBalance = lngBalance; investors[investor].per.previousBalance = perBalance; investors[investor].per.currentBalance = perBalance; emit ModifiedBalances(investor, midBalance, lngBalance, perBalance); } /** * @dev Set the interests balance of an investor. */ function setInterests (address investor, uint256 value) external onlyOwner { investors[investor].balanceInterests = value; emit ModifiedInterests(investor, value); emit UpdatedInterests(investor, investors[investor].balanceInterests); } /** * @dev Add or remove an address from the InterestsController mapping. */ function setInterestsController (address controller, bool value) external onlyOwner { _isInterestsController[controller] = value; emit ModifiedInterestsController(controller, value); } /** * @dev Increases the referer interests balance of a given amount. * * @param referer The address of the referal initiator * @param referee The address of the referal consumer * @param percent The percentage of interests earned by the referer * @param midAmount How many mid term bonds the referee bought through this referal * @param lngAmount How many long term bonds the referee bought through this referal * @param perAmount How many perpetual tokens the referee bought through this referal */ function updateReferralInfos ( address referer, address referee, uint256 percent, uint256 midAmount, uint256 lngAmount, uint256 perAmount ) external onlyOwner { // Referee and/or referer address(es) is(/are) not valid. require (referer != referee && referer != address(0) && referee != address(0), "A7"); // The given percent parameter is not a valid percentage. require (percent >= 1 && percent <= 100, "A8"); // Updates referer interests balance accounting for the referee investment investors[referer].balanceInterests = investors[referer].balanceInterests.add(midAmount.mul(percent).div(100)); investors[referer].balanceInterests = investors[referer].balanceInterests.add(lngAmount.mul(percent).div(100)); investors[referer].balanceInterests = investors[referer].balanceInterests.add(perAmount.mul(percent).div(100)); emit UpdatedInterests(referer, investors[referer].balanceInterests); investors[referee].mid.refereeBalance = investors[referee].mid.refereeBalance.add(midAmount); investors[referee].lng.refereeBalance = investors[referee].lng.refereeBalance.add(lngAmount); investors[referee].per.refereeBalance = investors[referee].per.refereeBalance.add(perAmount); emit ModifiedReferee( referee, investors[referee].mid.refereeBalance, investors[referee].lng.refereeBalance, investors[referee].per.refereeBalance ); emit Refered(referer, referee, midAmount, lngAmount, perAmount); } /** * @dev Set the referee balance of an investor. * * @param investor The address of the investor whose balance has to be modified * @param midAmount How many mid term bonds the referee bought through referal * @param lngAmount How many long term bonds the referee bought through referal * @param perAmount How many perpetual tokens the referee bought through referal */ function setRefereeAmount ( address investor, uint256 midAmount, uint256 lngAmount, uint256 perAmount ) external onlyOwner { investors[investor].mid.refereeBalance = midAmount; investors[investor].lng.refereeBalance = lngAmount; investors[investor].per.refereeBalance = perAmount; emit ModifiedReferee(investor, midAmount, lngAmount, perAmount); } /** * @dev Updates an investor's investment state. Will be called each month. * * @param investor The address of the investor for which to update interests * @param midBalance Balance of mid term bond * @param lngBalance Balance of long term bond * @param perBalance Balance of perpetual token */ function updateInterests (address investor, uint256 midBalance, uint256 lngBalance, uint256 perBalance) external onlyOwner { // Investor's balance in each bond may have changed since last month investors[investor].mid.currentBalance = midBalance; investors[investor].lng.currentBalance = lngBalance; investors[investor].per.currentBalance = perBalance; // Adjusts investor's referee balance bool adjustedReferee = false; if (investors[investor].mid.refereeBalance > investors[investor].mid.currentBalance) { investors[investor].mid.refereeBalance = investors[investor].mid.currentBalance; adjustedReferee = true; } if (investors[investor].lng.refereeBalance > investors[investor].lng.currentBalance) { investors[investor].lng.refereeBalance = investors[investor].lng.currentBalance; adjustedReferee = true; } if (investors[investor].per.refereeBalance > investors[investor].per.currentBalance) { investors[investor].per.refereeBalance = investors[investor].per.currentBalance; adjustedReferee = true; } if (adjustedReferee) { emit ModifiedReferee( investor, investors[investor].mid.refereeBalance, investors[investor].lng.refereeBalance, investors[investor].per.refereeBalance ); } // Increment the hodling counter : we pass to the next month. The hodling (in months) has to be adjusted // if the longterm or perpetual bonds balance has increased, for the midterm the interests are fixed so we // can, for one, keep it simple :-). if (investors[investor].mid.currentBalance > 0) { investors[investor].mid.currentHolding = investors[investor].mid.currentHolding.add(DECIMALS); } if (investors[investor].lng.currentBalance > 0) { if (investors[investor].lng.currentBalance > investors[investor].lng.previousBalance && investors[investor].lng.previousBalance > 0) { uint256 adjustmentRate = (((investors[investor].lng.currentBalance .sub(investors[investor].lng.previousBalance)) .mul(DECIMALS)) .div(investors[investor].lng.currentBalance)); investors[investor].lng.currentHolding = (((DECIMALS .sub(adjustmentRate)) .mul(investors[investor].lng.previousHolding .add(DECIMALS))) .div(DECIMALS)); } else { investors[investor].lng.currentHolding = investors[investor].lng.currentHolding.add(DECIMALS); } } if (investors[investor].per.currentBalance > 0) { if (investors[investor].per.currentBalance > investors[investor].per.previousBalance && investors[investor].per.previousBalance > 0) { uint256 adjustmentRate = (((investors[investor].per.currentBalance .sub(investors[investor].per.previousBalance)) .mul(DECIMALS)) .div(investors[investor].per.currentBalance)); investors[investor].per.currentHolding = (((DECIMALS.sub(adjustmentRate)) .mul(investors[investor].per.previousHolding .add(DECIMALS))) .div(DECIMALS)); } else { investors[investor].per.currentHolding = investors[investor].per.currentHolding.add(DECIMALS); } } // We emit ModifiedHoldings later _minterest(investor); // We pass to the next month, hence the previous month is now the current one :D investors[investor].mid.previousHolding = investors[investor].mid.currentHolding; investors[investor].lng.previousHolding = investors[investor].lng.currentHolding; investors[investor].per.previousHolding = investors[investor].per.currentHolding; // Same thing for balances investors[investor].mid.previousBalance = investors[investor].mid.currentBalance; investors[investor].lng.previousBalance = investors[investor].lng.currentBalance; investors[investor].per.previousBalance = investors[investor].per.currentBalance; emit ModifiedBalances( investor, investors[investor].mid.currentBalance, investors[investor].lng.currentBalance, investors[investor].per.currentBalance ); // If the balance of a partition is empty, we need to reset the corresponding "holding" variable if (investors[investor].per.currentBalance == 0) { investors[investor].per.previousHolding = 0; investors[investor].per.currentHolding = 0; } if (investors[investor].mid.currentBalance == 0) { investors[investor].mid.previousHolding = 0; investors[investor].mid.currentHolding = 0; } if (investors[investor].lng.currentBalance == 0) { investors[investor].lng.previousHolding = 0; investors[investor].lng.currentHolding = 0; } emit ModifiedHoldings( investor, investors[investor].mid.currentHolding, investors[investor].lng.currentHolding, investors[investor].per.currentHolding ); emit UpdatedInterests(investor, investors[investor].balanceInterests); } /******************** MWT_interests internal functions ************************/ /** * @dev Calculates the investor's total interests given how many tokens he holds, their type, and * for how long he's been holding them. * For midterm bonds tokens, the interest rate is constant. For longterm and perpetual bonds tokens * rates are given by a table designed by the token issuer (Montessori Worldwide) which is * translated in Solidity as a set of conditions. */ function _minterest (address investor) internal { // The interests rates are multiplied by 10^4 to both use integers and have a 10^-4 percent precision uint256 rateFactor = 10000; // 10^4 // Bonus to referee interest rates are multiplied by 100 to keep 10^-2 precision uint256 bonusFactor = 100; // midRate represents the interest rate of the user's midterm bonds uint256 midRate = 575; // lngRate represents the interest rate of the user's midterm bonds uint256 lngRate = 0; if (investors[investor].lng.currentBalance > 0) { if (investors[investor].lng.currentHolding < DECIMALS.mul(12)) { if (investors[investor].lng.currentBalance < DECIMALS.mul(800)) { lngRate = 700; } else if (investors[investor].lng.currentBalance < DECIMALS.mul(2400)) { lngRate = 730; } else if (investors[investor].lng.currentBalance < DECIMALS.mul(7200)) { lngRate = 749; } else { lngRate = 760; } } else if (investors[investor].lng.currentHolding < DECIMALS.mul(36)) { if (investors[investor].lng.currentBalance < DECIMALS.mul(800)) { lngRate = 730; } else if (investors[investor].lng.currentBalance < DECIMALS.mul(2400)) { lngRate = 745; } else if (investors[investor].lng.currentBalance < DECIMALS.mul(7200)) { lngRate = 756; } else { lngRate = 764; } } else if (investors[investor].lng.currentHolding < DECIMALS.mul(72)) { if (investors[investor].lng.currentBalance < DECIMALS.mul(800)) { lngRate = 749; } else if (investors[investor].lng.currentBalance < DECIMALS.mul(2400)) { lngRate = 757; } else if (investors[investor].lng.currentBalance < DECIMALS.mul(7200)) { lngRate = 763; } else { lngRate = 767; } } else if (investors[investor].lng.currentHolding >= DECIMALS.mul(72)) { if (investors[investor].lng.currentBalance < DECIMALS.mul(800)) { lngRate = 760; } else if (investors[investor].lng.currentBalance < DECIMALS.mul(2400)) { lngRate = 764; } else if (investors[investor].lng.currentBalance < DECIMALS.mul(7200)) { lngRate = 767; } else if (investors[investor].lng.currentBalance >= DECIMALS.mul(7200)) { lngRate = 770; } } assert (lngRate != 0); } // perRate represents the interest rate of the user's midterm bonds uint256 perRate = 0; if (investors[investor].per.currentBalance > 0) { if (investors[investor].per.currentHolding < DECIMALS.mul(12)) { if (investors[investor].per.currentBalance < DECIMALS.mul(800)) { perRate = 850; } else if (investors[investor].per.currentBalance < DECIMALS.mul(2400)) { perRate = 888; } else if (investors[investor].per.currentBalance < DECIMALS.mul(7200)) { perRate = 911; } else if (investors[investor].per.currentBalance >= DECIMALS.mul(7200)) { perRate = 925; } } else if (investors[investor].per.currentHolding < DECIMALS.mul(36)) { if (investors[investor].per.currentBalance < DECIMALS.mul(800)) { perRate = 888; } else if (investors[investor].per.currentBalance < DECIMALS.mul(2400)) { perRate = 906; } else if (investors[investor].per.currentBalance < DECIMALS.mul(7200)) { perRate = 919; } else if (investors[investor].per.currentBalance >= DECIMALS.mul(7200)) { perRate = 930; } } else if (investors[investor].per.currentHolding < DECIMALS.mul(72)) { if (investors[investor].per.currentBalance < DECIMALS.mul(800)) { perRate = 911; } else if (investors[investor].per.currentBalance < DECIMALS.mul(2400)) { perRate = 919; } else if (investors[investor].per.currentBalance < DECIMALS.mul(7200)) { perRate = 927; } else if (investors[investor].per.currentBalance >= DECIMALS.mul(7200)) { perRate = 934; } } else if (investors[investor].per.currentHolding >= DECIMALS.mul(72)) { if (investors[investor].per.currentBalance < DECIMALS.mul(800)) { perRate = 925; } else if (investors[investor].per.currentBalance < DECIMALS.mul(2400)) { perRate = 930; } else if (investors[investor].per.currentBalance < DECIMALS.mul(7200)) { perRate = 934; } else if (investors[investor].per.currentBalance >= DECIMALS.mul(7200)) { perRate = 937; } } assert (perRate != 0); } // The total user interests are incremented by this month's interests in each bond. // We divide by 12 because the interest rate is calculated on a yearly basis. // If an investor has a "referee balance" we need to apply a 5% bonus to its interests rate. In this case, // we multiply the interests rate by 105 then divide it by 100 so it is increased by 5% without precision loss. // In any case, we add the rate of each bond (time the investor's balance in this bond) on the interests balance. // Midterm bond interests if (investors[investor].mid.refereeBalance > 0) { investors[investor].balanceInterests = investors[investor].balanceInterests.add( ((midRate.mul(105) // Rate with 5% bonus .mul(investors[investor].mid.refereeBalance)) .div(12)) .div(rateFactor) .div(bonusFactor) ); investors[investor].balanceInterests = investors[investor].balanceInterests.add( ((midRate .mul(investors[investor].mid.currentBalance.sub(investors[investor].mid.refereeBalance))) .div(12)) .div(rateFactor) ); } else { investors[investor].balanceInterests = investors[investor].balanceInterests.add( ((midRate .mul(investors[investor].mid.currentBalance)) .div(12)) .div(rateFactor) ); } // Longterm bond interests if (investors[investor].lng.refereeBalance > 0) { investors[investor].balanceInterests = investors[investor].balanceInterests.add( ((lngRate.mul(105) // Rate with 5% bonus .mul(investors[investor].lng.refereeBalance)) .div(12)) .div(rateFactor) .div(bonusFactor) ); investors[investor].balanceInterests = investors[investor].balanceInterests.add( ((lngRate.mul(investors[investor].lng.currentBalance.sub(investors[investor].lng.refereeBalance))) .div(12)) .div(rateFactor) ); } else { investors[investor].balanceInterests = investors[investor].balanceInterests.add( ((lngRate.mul(investors[investor].lng.currentBalance)) .div(12)) .div(rateFactor) ); } // Perpetual bond interests if (investors[investor].per.refereeBalance > 0) { investors[investor].balanceInterests = investors[investor].balanceInterests.add( ((perRate.mul(105) // Rate with 5% bonus .mul(investors[investor].per.refereeBalance)) .div(12)) .div(rateFactor) .div(bonusFactor) ); investors[investor].balanceInterests = investors[investor].balanceInterests.add( ((perRate.mul(investors[investor].per.currentBalance.sub(investors[investor].per.refereeBalance))) .div(12)) .div(rateFactor) ); } else { investors[investor].balanceInterests = investors[investor].balanceInterests.add( ((perRate.mul(investors[investor].per.currentBalance)) .div(12)) .div(rateFactor) ); } } }
Check whether an investor is currently claiming its interests, and in which currency./
function isClaimingInterests (address investor) external view returns (bool, bytes32) { return (investors[investor].claimingInterests.claiming, investors[investor].claimingInterests.currency); }
5,449,892
pragma solidity ^0.4.18; /** * @title VestingLib * @author Modular.network * * version 1.0.1 * Copyright (c) 2017 Modular, LLC * The MIT License (MIT) * https://github.com/Modular-Network/ethereum-libraries/blob/master/LICENSE * * Library for vesting tokens to a group of addresses. The library only handles * one token at a time, with a linear vesting schedule for a set period of time * * Modular works on open source projects in the Ethereum community with the * purpose of testing, documenting, and deploying reusable code onto the * blockchain to improve security and usability of smart contracts. Modular * also strives to educate non-profits, schools, and other community members * about the application of blockchain technology. * For further information: modular.network * * 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. */ import "./BasicMathLib.sol"; import "./TokenLib.sol"; import "./CrowdsaleToken.sol"; library VestingLib { using BasicMathLib for uint256; struct VestingStorage { address owner; uint256 totalSupply; // total supply of ETH or tokens uint256 contractBalance; // current balance of the contract bool isToken; // false for ETH, true for token uint256 startTime; // timestamp when vesting starts uint256 endTime; // timestamp when vesting is complete uint256 numRegistered; // number of addresses registered for the vesting uint256 timeInterval; // interval between vesting uint256 percentPerInterval; // percentage of the total released every interval // for each address, 0-index is the amount being held, 1-index is the bonus. // if the bonus amount is > 0, any withdrawal before endTime will result // in the total amount being withdrawn without the bonus mapping (address => uint256[2]) holdingAmount; // shows how much an address has already withdrawn from the vesting contract mapping (address => uint256) hasWithdrawn; } // Generic Error message, error code and string event LogErrorMsg(uint256 amount, string Msg); // Logs when a user is registered in the system for vesting event LogUserRegistered(address registrant, uint256 vestAmount, uint256 bonus); // Logs when a user is unregistered from the system event LogUserUnRegistered(address registrant); // Logs when a user replaces themselves with a different beneficiary event LogRegistrationReplaced(address currentRegistrant, address newRegistrant, uint256 amountWithdrawn); // Logs when a user withdraws their ETH from vesting event LogETHWithdrawn(address beneficiary, uint256 amount); // Logs when a user withdraws their tokens from the contract event LogTokensWithdrawn(address beneficiary, uint256 amount); /// @dev Called by the token vesting contract upon creation. /// @param self Stored token from token contract /// @param _owner the owner of the vesting contract /// @param _isToken indicates if the vesting is for tokens or ETH /// @param _startTime the start time of the vesting (UNIX timestamp) /// @param _endTime the end time of the vesting (UNIX timestamp) /// @param _numReleases number of times during vesting that the contract releases coins function init(VestingStorage storage self, address _owner, bool _isToken, uint256 _startTime, uint256 _endTime, uint256 _numReleases) public { require(self.owner == 0); require(self.totalSupply == 0); require(_owner != 0); require(_startTime > now); require(_endTime > _startTime); require(_numReleases > 0); require(_numReleases <= 100); self.owner = _owner; self.isToken = _isToken; self.startTime = _startTime; self.endTime = _endTime; self.timeInterval = (_endTime - _startTime)/_numReleases; require(self.timeInterval > 0); self.percentPerInterval = 100/_numReleases; } /// @dev function owner has to call before the vesting starts to initialize the ETH balance of the contract. /// @param self Stored vesting from vesting contract /// @param _balance the balance that is being vested. msg.value from the contract call. function initializeETHBalance(VestingStorage storage self, uint256 _balance) public returns (bool) { require(msg.sender == self.owner); require(now < self.startTime); require(_balance != 0); require(!self.isToken); require(self.totalSupply == 0); self.totalSupply = _balance; self.contractBalance = _balance; return true; } /// @dev function owner has to call before the vesting starts to initialize the token balance of the contract. /// @param self Stored vesting from vesting contract /// @param _balance the balance that is being vested. owner has to have sent tokens to the contract before calling this function function initializeTokenBalance(VestingStorage storage self, CrowdsaleToken token, uint256 _balance) public returns (bool) { require(msg.sender == self.owner); require(now < self.startTime); require(_balance != 0); require(self.isToken); require(token.balanceOf(this) == _balance); require(self.totalSupply == 0); self.totalSupply = _balance; self.contractBalance = _balance; return true; } /// @dev register user function, can only be called by the owner. registers amount /// of vesting into the address and reduces contractBalance /// @param self Stored vesting from vesting contract /// @param _registrant address to be registered for the vesting /// @param _vestAmount amount of ETH or tokens to vest for address /// @param _bonus amount of bonus tokens or eth if no withdrawal prior to endTime function registerUser(VestingStorage storage self, address _registrant, uint256 _vestAmount, uint256 _bonus) public returns (bool) { require((msg.sender == self.owner) || (msg.sender == address(this))); if (now >= self.startTime) { LogErrorMsg(self.startTime,"Can only register users before the vesting starts!"); return false; } if(self.holdingAmount[_registrant][0] > 0) { LogErrorMsg(0,"Registrant address is already registered for the vesting!"); return false; } if(_bonus > _vestAmount){ LogErrorMsg(_bonus,"Bonus is larger than vest amount, please reduce bonus!"); return false; } uint256 _totalAmount; uint256 result; bool err; (err, _totalAmount) = _vestAmount.plus(_bonus); require(!err); (err, result) = self.contractBalance.minus(_totalAmount); require(!err); self.contractBalance = result; self.holdingAmount[_registrant][0] = _vestAmount; self.holdingAmount[_registrant][1] = _bonus; (err,result) = self.numRegistered.plus(1); require(!err); self.numRegistered = result; LogUserRegistered(_registrant, _vestAmount, _bonus); return true; } /// @dev registers multiple users at the same time. each registrant must be /// receiving the same amount of tokens or ETH /// @param self Stored vesting from vesting contract /// @param _registrants addresses to register for the vesting /// @param _vestAmount amount of ETH or tokens to vest /// @param _bonus amount of ETH or token bonus function registerUsers(VestingStorage storage self, address[] _registrants, uint256 _vestAmount, uint256 _bonus) public returns (bool) { require(msg.sender == self.owner); bool ok; for (uint256 i = 0; i < _registrants.length; i++) { ok = registerUser(self,_registrants[i], _vestAmount, _bonus); } return ok; } /// @dev Cancels a user's registration status can only be called by the owner /// when a user cancels their registration. sets their address field in the /// holding amount mapping to 0, decrements the numRegistered, and adds amount /// back into contractBalance /// @param self Stored vesting from vesting contract function unregisterUser(VestingStorage storage self, address _registrant) public returns (bool) { require((msg.sender == self.owner) || (msg.sender == address(this))); if (now >= self.startTime) { LogErrorMsg(self.startTime, "Can only register and unregister users before the vesting starts!"); return false; } uint256 _totalHolding; uint256 result; bool err; _totalHolding = self.holdingAmount[_registrant][0] + self.holdingAmount[_registrant][1]; if(_totalHolding == 0) { LogErrorMsg(0, "Registrant address not registered for the vesting!"); return false; } self.holdingAmount[_registrant][0] = 0; self.holdingAmount[_registrant][1] = 0; self.contractBalance += _totalHolding; (err,result) = self.numRegistered.minus(1); require(!err); self.numRegistered = result; LogUserUnRegistered(_registrant); return true; } /// @dev unregisters multiple users at the same time /// @param self Stored vesting from vesting contract /// @param _registrants addresses to unregister for the vesting function unregisterUsers(VestingStorage storage self, address[] _registrants) public returns (bool) { require(msg.sender == self.owner); bool ok; for (uint256 i = 0; i < _registrants.length; i++) { ok = unregisterUser(self,_registrants[i]); } return ok; } /// @dev allows a participant to replace themselves in the vesting schedule with a new address /// @param self Stored vesting from vesting contract /// @param _replacementRegistrant new address to replace the caller with function swapRegistration(VestingStorage storage self, address _replacementRegistrant) public returns (bool) { require(_replacementRegistrant != 0); require(self.holdingAmount[_replacementRegistrant][0] == 0); uint256 _vestAmount = self.holdingAmount[msg.sender][0]; uint256 _bonus = self.holdingAmount[msg.sender][1]; uint256 _withdrawnAmount = self.hasWithdrawn[msg.sender]; require(_vestAmount > 0); self.holdingAmount[msg.sender][0] = 0; self.holdingAmount[msg.sender][1] = 0; self.hasWithdrawn[msg.sender] = 0; self.holdingAmount[_replacementRegistrant][0] = _vestAmount; self.holdingAmount[_replacementRegistrant][1] = _bonus; self.hasWithdrawn[_replacementRegistrant] = _withdrawnAmount; LogRegistrationReplaced(msg.sender, _replacementRegistrant, self.hasWithdrawn[_replacementRegistrant]); return true; } /// @dev calculates the number of tokens or ETH available for the beneficiary to withdraw /// @param self Stored vesting from vesting contract /// @param _beneficiary the sender, who will be withdrawing their balance function calculateWithdrawal(VestingStorage storage self, address _beneficiary) internal view returns (uint256) { require(_beneficiary != 0); require(self.holdingAmount[_beneficiary][0] > 0); require(self.numRegistered > 0); bool err; // figure out how many intervals have passed since the start uint256 _numIntervals = (now-self.startTime)/self.timeInterval; // multiply that by the percentage released every interval // calculate the amount released by this time uint256 _amountReleased = ((_numIntervals*self.percentPerInterval)*self.holdingAmount[_beneficiary][0])/100; // subtract the amount that has already been withdrawn (err, _amountReleased) = _amountReleased.minus(self.hasWithdrawn[_beneficiary]); return _amountReleased; } /// @dev allows participants to withdraw their vested ETH /// @param self Stored vesting from vesting contract function withdrawETH(VestingStorage storage self) public returns (bool) { require(now > self.startTime); require(!self.isToken); bool ok; bool err; uint256 _withdrawAmount; if((now < self.endTime) && (self.holdingAmount[msg.sender][1] > 0)){ // if there is a bonus and it's before the endTime, cancel the bonus _withdrawAmount = calculateWithdrawal(self, msg.sender); uint256 _bonusAmount = self.holdingAmount[msg.sender][1]; //self.holdingAmount[msg.sender][0] = 0; self.holdingAmount[msg.sender][1] = 0; // add bonus eth back into the contract balance self.contractBalance += _bonusAmount; } else { if(now > self.endTime){ // if it's past the endTime then send everything left _withdrawAmount = self.holdingAmount[msg.sender][0] + self.holdingAmount[msg.sender][1]; (ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[msg.sender]); require(!err); self.holdingAmount[msg.sender][0] = 0; self.holdingAmount[msg.sender][1] = 0; } else { // if we're here then it's before the endTime and no bonus, need to calculate _withdrawAmount = calculateWithdrawal(self, msg.sender); } } self.hasWithdrawn[msg.sender] += _withdrawAmount; // transfer ETH to the sender msg.sender.transfer(_withdrawAmount); LogETHWithdrawn(msg.sender,_withdrawAmount); return true; } /// @dev allows participants to withdraw their vested tokens /// @param self Stored vesting from vesting contract /// @param token the token contract that is being withdrawn function withdrawTokens(VestingStorage storage self,CrowdsaleToken token) public returns (bool) { require(now > self.startTime); require(self.isToken); bool ok; bool err; uint256 _withdrawAmount; if((now < self.endTime) && (self.holdingAmount[msg.sender][1] > 0)){ // if there is a bonus and it's before the endTime, cancel the bonus and send tokens _withdrawAmount = calculateWithdrawal(self, msg.sender); uint256 _bonusAmount = self.holdingAmount[msg.sender][1]; self.holdingAmount[msg.sender][1] = 0; ok = token.burnToken(_bonusAmount); require(ok); } else { if(now > self.endTime){ // if it's past the endTime then send everything left _withdrawAmount = self.holdingAmount[msg.sender][0] + self.holdingAmount[msg.sender][1]; (ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[msg.sender]); require(!err); self.holdingAmount[msg.sender][0] = 0; self.holdingAmount[msg.sender][1] = 0; } else { // if we're here then it's before the endTime and no bonus, need to calculate _withdrawAmount = calculateWithdrawal(self, msg.sender); } } self.hasWithdrawn[msg.sender] += _withdrawAmount; // transfer tokens to the sender ok = token.transfer(msg.sender, _withdrawAmount); require(ok); LogTokensWithdrawn(msg.sender,_withdrawAmount); return true; } /// @dev allows the owner to send vested ETH to participants /// @param self Stored vesting from vesting contract /// @param _beneficiary registered address to send the ETH to function sendETH(VestingStorage storage self, address _beneficiary) public returns (bool) { require(now > self.startTime); require(msg.sender == self.owner); require(!self.isToken); bool ok; bool err; uint256 _withdrawAmount; if((now < self.endTime) && (self.holdingAmount[_beneficiary][1] > 0)){ // if there is a bonus and it's before the endTime, cancel the bonus _withdrawAmount = calculateWithdrawal(self, _beneficiary); uint256 _bonusAmount = self.holdingAmount[_beneficiary][1]; self.holdingAmount[_beneficiary][1] = 0; // add bonus eth back into the contract balance self.contractBalance += _bonusAmount; } else { if(now > self.endTime){ // if it's past the endTime then send everything left _withdrawAmount = self.holdingAmount[_beneficiary][0] + self.holdingAmount[_beneficiary][1]; (ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[_beneficiary]); require(!err); self.holdingAmount[_beneficiary][0] = 0; self.holdingAmount[_beneficiary][1] = 0; } else { // if we're here then it's before the endTime and no bonus, need to calculate _withdrawAmount = calculateWithdrawal(self, _beneficiary); } } self.hasWithdrawn[_beneficiary] += _withdrawAmount; // transfer ETH to the _beneficiary _beneficiary.transfer(_withdrawAmount); LogETHWithdrawn(_beneficiary,_withdrawAmount); return true; } /// @dev allows the owner to send vested tokens to participants /// @param self Stored vesting from vesting contract /// @param token the token contract that is being withdrawn /// @param _beneficiary registered address to send the tokens to function sendTokens(VestingStorage storage self,CrowdsaleToken token, address _beneficiary) public returns (bool) { require(now > self.startTime); require(msg.sender == self.owner); require(self.isToken); bool ok; bool err; uint256 _withdrawAmount; if((now < self.endTime) && (self.holdingAmount[_beneficiary][1] > 0)){ // if there is a bonus and it's before the endTime, cancel the bonus _withdrawAmount = calculateWithdrawal(self, _beneficiary); uint256 _bonusAmount = self.holdingAmount[_beneficiary][1]; self.holdingAmount[msg.sender][1] = 0; ok = token.burnToken(_bonusAmount); } else { if(now > self.endTime){ // if it's past the endTime then send everything left _withdrawAmount = self.holdingAmount[_beneficiary][0] + self.holdingAmount[_beneficiary][1]; (ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[_beneficiary]); require(!err); self.holdingAmount[_beneficiary][0] = 0; self.holdingAmount[_beneficiary][1] = 0; } else { // if we're here then it's before the endTime and no bonus, need to calculate _withdrawAmount = calculateWithdrawal(self, _beneficiary); } } self.hasWithdrawn[_beneficiary] += _withdrawAmount; // transfer tokens to the beneficiary ok = token.transfer(_beneficiary, _withdrawAmount); require(ok); LogTokensWithdrawn(_beneficiary,_withdrawAmount); return true; } /// @dev Allows the owner to withdraw any ETH left in the contractBalance /// @param self Stored vesting from vesting contract function ownerWithdrawExtraETH(VestingStorage storage self) public returns (bool) { require(msg.sender == self.owner); require(now > self.endTime); require(!self.isToken); uint256 _contractBalance = this.balance; self.contractBalance = 0; self.owner.transfer(_contractBalance); LogETHWithdrawn(self.owner,_contractBalance); return true; } /// @dev Allows the owner to withdraw any tokens left in the contractBalance /// @param self Stored vesting from vesting contract function ownerWithdrawExtraTokens(VestingStorage storage self, CrowdsaleToken token) public returns (bool) { require(msg.sender == self.owner); require(now > self.endTime); require(self.isToken); uint256 _contractBalance = token.balanceOf(this); self.contractBalance = 0; token.transfer(self.owner,_contractBalance); LogTokensWithdrawn(self.owner,_contractBalance); return true; } /// @dev Returns the percentage of the vesting that has been released at the current moment function getPercentReleased(VestingStorage storage self) public view returns (uint256) { require(now > self.startTime); return self.percentPerInterval * ((now-self.startTime)/self.timeInterval); } }
Returns the percentage of the vesting that has been released at the current moment
function getPercentReleased(VestingStorage storage self) public view returns (uint256) { require(now > self.startTime); return self.percentPerInterval * ((now-self.startTime)/self.timeInterval); }
12,964,842
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; interface IRadRouter is IERC721Receiver { /** * @dev Emitted when a retail revenue split is updated for asset ledger `ledger` */ event RetailRevenueSplitChange(address indexed ledger, address indexed stakeholder, uint256 share, uint256 totalStakeholders, uint256 totalSplit); /** * @dev Emitted when a resale revenue split is updated for asset ledger `ledger` */ event ResaleRevenueSplitChange(address indexed ledger, address indexed stakeholder, uint256 share, uint256 totalStakeholders, uint256 totalSplit); /** * @dev Emitted when the minimum price of asset `assetId` is updated */ event AssetMinPriceChange(address indexed ledger, uint256 indexed assetId, uint256 minPrice); /** * @dev Emitted when seller `seller` changes ownership for asset `assetId` in ledger `ledger` to or from this escrow. `escrowed` is true for deposits and false for withdrawals */ event SellerEscrowChange(address indexed ledger, uint256 indexed assetId, address indexed seller, bool escrowed); /** * @dev Emitted when buyer `buyer` deposits or withdraws ETH from this escrow for asset `assetId` in ledger `ledger`. `escrowed` is true for deposits and false for withdrawals */ event BuyerEscrowChange(address indexed ledger, uint256 indexed assetId, address indexed buyer, bool escrowed); /** * @dev Emitted when stakeholder `stakeholder` is paid out from a retail sale or resale */ event StakeholderPayout(address indexed ledger, uint256 indexed assetId, address indexed stakeholder, uint256 payout, uint256 share, bool retail); /** * @dev Emitted when buyer `buyer` deposits or withdraws ETH from this escrow for asset `assetId` in ledger `ledger`. `escrowed` is true for deposits and false for withdrawals */ event EscrowFulfill(address indexed ledger, uint256 indexed assetId, address seller, address buyer, uint256 value); /** * @dev Sets a stakeholder's revenue share for an asset ledger. If `retail` is true, sets retail revenue splits; otherwise sets resale revenue splits * * Requirements: * * - `_ledger` cannot be the zero address. * - `_stakeholder` cannot be the zero address. * - `_share` must be >= 0 and <= 100 * - Revenue cannot be split more than 5 ways * * Emits a {RetailRevenueSplitChange|ResaleRevenueSplitChange} event. */ function setRevenueSplit(address _ledger, address payable _stakeholder, uint256 _share, bool _retail) external returns (bool success); /** * @dev Returns the revenue share of `_stakeholder` for ledger `_ledger` * * See {setRevenueSplit} */ function getRevenueSplit(address _ledger, address payable _stakeholder, bool _retail) external view returns (uint256 share); /** * @dev Sets multiple stakeholders' revenue shares for an asset ledger. Overwrites any existing revenue share. If `retail` is true, sets retail revenue splits; otherwise sets resale revenue splits * See {setRevenueSplit} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_stakeholders` cannot contain zero addresses. * - `_shares` must be >= 0 and <= 100 * - Revenue cannot be split more than 5 ways * * Emits a {RetailRevenueSplitChange|ResaleRevenueSplitChange} event. */ function setRevenueSplits(address _ledger, address payable[] calldata _stakeholders, uint256[] calldata _shares, bool _retail) external returns (bool success); /** * @dev For ledger `_ledger`, returns retail revenue stakeholders if `_retail` is true, otherwise returns resale revenue stakeholders. */ function getRevenueStakeholders(address _ledger, bool _retail) external view returns (address[] memory stakeholders); /** * @dev Sets the minimum price for asset `_assetId` * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * - `_minPrice` is in wei * * Emits a {AssetMinPriceChange} event. */ function setAssetMinPrice(address _ledger, uint256 _assetId, uint256 _minPrice) external returns (bool success); /** * @dev Sets a stakeholder's revenue share for an asset ledger. If `retail` is true, sets retail revenue splits; otherwise sets resale revenue splits. * Also sets the minimum price for asset `_assetId` * See {setAssetMinPrice | setRevenueSplits} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_stakeholder` cannot be the zero address. * - `_share` must be > 0 and <= 100 * - Revenue cannot be split more than 5 ways * - `_owner` must first approve this contract as an operator for ledger `_ledger` * - `_minPrice` is in wei * * Emits a {RetailRevenueSplitChange|ResaleRevenueSplitChange} event. */ function setAssetMinPriceAndRevenueSplits(address _ledger, address payable[] calldata _stakeholders, uint256[] calldata _shares, bool _retail, uint256 _assetId, uint256 _minPrice) external returns (bool success); /** * @dev Returns the minium price of asset `_assetId` in ledger `_ledger` * * See {setAssetMinPrice} */ function getAssetMinPrice(address _ledger, uint256 _assetId) external view returns (uint256 minPrice); /** * @dev Transfers ownership of asset `_assetId` to this contract for escrow. * If buyer has already escrowed, triggers escrow fulfillment. * See {fulfill} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * * Emits a {SellerEscrowChange} event. */ function sellerEscrowDeposit(address _ledger, uint256 _assetId) external returns (bool success); /** * @dev Transfers ownership of asset `_assetId` to this contract for escrow. * If buyer has already escrowed, triggers escrow fulfillment. * See {fulfill} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * * Emits a {SellerEscrowChange} event. */ function sellerEscrowDepositWithCreatorShare(address _ledger, uint256 _assetId, uint256 _creatorResaleShare) external returns (bool success); function sellerEscrowDepositWithCreatorShareBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare) external returns (bool success); /** * @dev Transfers ownership of asset `_assetId` to this contract for escrow. * If buyer has already escrowed, triggers escrow fulfillment. * See {fulfill} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * * Emits a {SellerEscrowChange} event. */ function sellerEscrowDepositWithCreatorShareWithMinPrice(address _ledger, uint256 _assetId, uint256 _creatorResaleShare, uint256 _minPrice) external returns (bool success); function sellerEscrowDepositWithCreatorShareWithMinPriceBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare, uint256 _minPrice) external returns (bool success); /** * @dev Transfers ownership of asset `_assetId` to this contract for escrow. * Sets asset min price to `_minPrice` if `_setMinPrice` is true. Reverts if `_setMinPrice` is true and buyer has already escrowed. Otherwise, if buyer has already escrowed, triggers escrow fulfillment. * See {fulfill | setAssetMinPrice} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * - `_minPrice` is in wei * * Emits a {SellerEscrowChange} event. */ function sellerEscrowDeposit(address _ledger, uint256 _assetId, bool _setMinPrice, uint256 _minPrice) external returns (bool success); /** * @dev Transfers ownership of all assets `_assetIds` to this contract for escrow. * If any buyers have already escrowed, triggers escrow fulfillment for the respective asset. * See {fulfill} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * * Emits a {SellerEscrowChange} event. */ function sellerEscrowDepositBatch(address _ledger, uint256[] calldata _assetIds) external returns (bool success); /** * @dev Transfers ownership of all assets `_assetIds` to this contract for escrow. * Sets each asset min price to `_minPrice` if `_setMinPrice` is true. Reverts if `_setMinPrice` is true and buyer has already escrowed. Otherwise, if any buyers have already escrowed, triggers escrow fulfillment for the respective asset. * See {fulfill | setAssetMinPrice} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * - `_minPrice` is in wei * * Emits a {SellerEscrowChange} event. */ function sellerEscrowDepositBatch(address _ledger, uint256[] calldata _assetIds, bool _setMinPrice, uint256 _minPrice) external returns (bool success); /** * @dev Transfers ownership of asset `_assetId` from this contract for escrow back to seller. * * Requirements: * * - `_ledger` cannot be the zero address. * * Emits a {SellerEscrowChange} event. */ function sellerEscrowWithdraw(address _ledger, uint256 _assetId) external returns (bool success); /** * @dev Accepts buyer's `msg.sender` funds into escrow for asset `_assetId` in ledger `_ledger`. * If seller has already escrowed, triggers escrow fulfillment. * See {fulfill} * * Requirements: * * - `_ledger` cannot be the zero address. * - `msg.value` must be at least the seller's listed price * - `_assetId` in `ledger` cannot already have an escrowed buyer * * Emits a {BuyerEscrowChange} event. */ function buyerEscrowDeposit(address _ledger, uint256 _assetId) external payable returns (bool success); /** * @dev Returns buyer's `msg.sender` funds back from escrow for asset `_assetId` in ledger `_ledger`. * * Requirements: * * - `_ledger` cannot be the zero address. * - `msg.sender` must be the escrowed buyer for asset `_assetId` in ledger `_ledger`, asset owner, or Rad operator * * Emits a {BuyerEscrowChange} event. */ function buyerEscrowWithdraw(address _ledger, uint256 _assetId) external returns (bool success); /** * @dev Returns the wallet address of the seller of asset `_assetId` * * See {sellerEscrowDeposit} */ function getSellerWallet(address _ledger, uint256 _assetId) external view returns (address wallet); /** * @dev Returns the wallet address of the buyer of asset `_assetId` * * See {buyerEscrowDeposit} */ function getBuyerWallet(address _ledger, uint256 _assetId) external view returns (address wallet); /** * @dev Returns the escrowed amount by the buyer of asset `_assetId` * * See {buyerEscrowDeposit} */ function getBuyerDeposit(address _ledger, uint256 _assetId) external view returns (uint256 amount); /** * @dev Returns the wallet address of the creator of asset `_assetId` * * See {sellerEscrowDeposit} */ function getCreatorWallet(address _ledger, uint256 _assetId) external view returns (address wallet); /** * @dev Returns the amount of the creator's share of asset `_assetId` * * See {sellerEscrowDeposit} */ function getCreatorShare(address _ledger, uint256 _assetId) external view returns (uint256 amount); /** * @dev Returns true if an asset has been sold for retail and will be considered resale moving forward */ function getAssetIsResale(address _ledger, uint256 _assetId) external view returns (bool resale); /** * @dev Returns an array of all retailed asset IDs for ledger `_ledger` */ function getRetailedAssets(address _ledger) external view returns (uint256[] memory assets); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import './IRadRouter.sol'; import './RevenueSplitMapping.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol'; contract RadRouter is IRadRouter, ERC721Holder { using RevenueSplitMapping for RevMap; struct Ledger { RevMap RetailSplits; RevMap ResaleSplits; mapping (uint256 => Asset) Assets; uint256[] retailedAssets; } struct Asset { address owner; // does not change on escrow, only through sale uint256 minPrice; bool resale; Creator creator; Buyer buyer; } struct Creator { address wallet; uint256 share; } struct Buyer { address wallet; uint256 amountEscrowed; } modifier onlyBy(address _account) { require( msg.sender == _account, 'Sender not authorized' ); _; } address public administrator_; // Rad administrator account mapping(address => Ledger) private Ledgers; /** * @dev Initializes the contract and sets the router administrator `administrator_` */ constructor() { administrator_ = msg.sender; } /** * @dev See {IRadRouter-setRevenueSplit}. */ function setRevenueSplit(address _ledger, address payable _stakeholder, uint256 _share, bool _retail) public onlyBy(administrator_) virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); require(_stakeholder != address(0), 'Stakeholder cannot be the zero address'); require(_share >= 0 && _share <= 100, 'Stakeholder share must be at least 0% and at most 100%'); uint256 total; if (_retail) { if (_share == 0) { Ledgers[_ledger].RetailSplits.remove(_stakeholder); emit RetailRevenueSplitChange(_ledger, _stakeholder, _share, Ledgers[_ledger].RetailSplits.size(), Ledgers[_ledger].RetailSplits.total); return true; } if (Ledgers[_ledger].RetailSplits.contains(_stakeholder)) { require(Ledgers[_ledger].RetailSplits.size() <= 5, 'Cannot split revenue more than 5 ways.'); total = Ledgers[_ledger].RetailSplits.total - Ledgers[_ledger].RetailSplits.get(_stakeholder); } else { require(Ledgers[_ledger].RetailSplits.size() < 5, 'Cannot split revenue more than 5 ways.'); total = Ledgers[_ledger].RetailSplits.total; } } else { if (_share == 0) { Ledgers[_ledger].ResaleSplits.remove(_stakeholder); emit ResaleRevenueSplitChange(_ledger, _stakeholder, _share, Ledgers[_ledger].ResaleSplits.size(), Ledgers[_ledger].ResaleSplits.total); return true; } if (Ledgers[_ledger].ResaleSplits.contains(_stakeholder)) { require(Ledgers[_ledger].ResaleSplits.size() <= 5, 'Cannot split revenue more than 5 ways.'); total = Ledgers[_ledger].ResaleSplits.total - Ledgers[_ledger].RetailSplits.get(_stakeholder); } else { require(Ledgers[_ledger].ResaleSplits.size() < 5, 'Cannot split revenue more than 5 ways.'); total = Ledgers[_ledger].ResaleSplits.total; } } require(_share + total <= 100, 'Total revenue split cannot exceed 100%'); if (_retail) { Ledgers[_ledger].RetailSplits.set(_stakeholder, _share); emit RetailRevenueSplitChange(_ledger, _stakeholder, _share, Ledgers[_ledger].RetailSplits.size(), Ledgers[_ledger].RetailSplits.total); } else { Ledgers[_ledger].ResaleSplits.set(_stakeholder, _share); emit ResaleRevenueSplitChange(_ledger, _stakeholder, _share, Ledgers[_ledger].ResaleSplits.size(), Ledgers[_ledger].ResaleSplits.total); } success = true; } /** * @dev See {IRadRouter-getRevenueSplit}. */ function getRevenueSplit(address _ledger, address payable _stakeholder, bool _retail) external view virtual override returns (uint256 share) { if (_retail) { share = Ledgers[_ledger].RetailSplits.get(_stakeholder); } else { share = Ledgers[_ledger].ResaleSplits.get(_stakeholder); } } /** * @dev See {IRadRouter-setRevenueSplits}. */ function setRevenueSplits(address _ledger, address payable[] calldata _stakeholders, uint256[] calldata _shares, bool _retail) public virtual override returns (bool success) { require(_stakeholders.length == _shares.length, 'Stakeholders and shares must have equal length'); require(_stakeholders.length <= 5, 'Cannot split revenue more than 5 ways.'); if (_retail) { Ledgers[_ledger].RetailSplits.clear(); } else { Ledgers[_ledger].ResaleSplits.clear(); } for (uint256 i = 0; i < _stakeholders.length; i++) { setRevenueSplit(_ledger, _stakeholders[i], _shares[i], _retail); } success = true; } function getRevenueStakeholders(address _ledger, bool _retail) external view virtual override returns (address[] memory stakeholders) { if (_retail) { stakeholders = Ledgers[_ledger].RetailSplits.keys; } else { stakeholders = Ledgers[_ledger].ResaleSplits.keys; } } /** * @dev See {IRadRouter-setAssetMinPrice}. */ function setAssetMinPrice(address _ledger, uint256 _assetId, uint256 _minPrice) public virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); IERC721 ledger = IERC721(_ledger); address owner = ledger.ownerOf(_assetId); require(msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can set the asset minimum price'); require(owner == address(this) || ledger.isApprovedForAll(owner, address(this)) || ledger.getApproved(_assetId) == address(this), 'Must approve Rad Router as an operator before setting minimum price.'); Ledgers[_ledger].Assets[_assetId].owner = owner; Ledgers[_ledger].Assets[_assetId].minPrice = _minPrice; emit AssetMinPriceChange(_ledger, _assetId, _minPrice); success = true; } /** * @dev See {IRadRouter-getAssetMinPrice}. */ function getAssetMinPrice(address _ledger, uint256 _assetId) external view virtual override returns (uint256 minPrice) { minPrice = Ledgers[_ledger].Assets[_assetId].minPrice; } /** * @dev See {IRadRouter-setAssetMinPriceAndRevenueSplits}. */ function setAssetMinPriceAndRevenueSplits(address _ledger, address payable[] calldata _stakeholders, uint256[] calldata _shares, bool _retail, uint256 _assetId, uint256 _minPrice) public virtual override returns (bool success) { success = setRevenueSplits(_ledger, _stakeholders, _shares, _retail) && setAssetMinPrice(_ledger, _assetId, _minPrice); } /** * @dev See {IRadRouter-sellerEscrowDeposit}. */ function sellerEscrowDeposit(address _ledger, uint256 _assetId) public virtual override returns (bool success) { success = sellerEscrowDeposit(_ledger, _assetId, false, 0); } /** * @dev See {IRadRouter-sellerEscrowDepositWithCreatorShare}. */ function sellerEscrowDepositWithCreatorShare(address _ledger, uint256 _assetId, uint256 _creatorResaleShare) public virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); require(_creatorResaleShare >= 0 && _creatorResaleShare <= 100, 'Creator share must be at least 0% and at most 100%'); IERC721 ledger = IERC721(_ledger); address owner = ledger.ownerOf(_assetId); require( msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can change asset ownership' ); require( ledger.isApprovedForAll(owner, address(this)) || ledger.getApproved(_assetId) == address(this), 'Must set Rad Router as an operator for all assets before depositing to escrow.' ); if ( Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0) || Ledgers[_ledger].Assets[_assetId].creator.wallet == owner || Ledgers[_ledger].Assets[_assetId].owner == owner ) { if (Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0)) { Ledgers[_ledger].Assets[_assetId].creator.wallet = owner; } require( Ledgers[_ledger].Assets[_assetId].creator.wallet == owner || Ledgers[_ledger].Assets[_assetId].creator.share == 0 || Ledgers[_ledger].Assets[_assetId].owner == owner, 'Cannot set creator share.' ); uint256 total = Ledgers[_ledger].Assets[_assetId].creator.share; address[] storage stakeholders = Ledgers[_ledger].ResaleSplits.keys; for (uint256 i = 0; i < stakeholders.length; i++) { total += Ledgers[_ledger].ResaleSplits.get(stakeholders[i]); } require(total <= 100, 'Creator share cannot exceed total ledger stakeholder when it is 100.'); Ledgers[_ledger].Assets[_assetId].creator.share = _creatorResaleShare; } success = sellerEscrowDeposit(_ledger, _assetId, false, 0); } /** * @dev See {IRadRouter-sellerEscrowDepositWithCreatorShareBatch}. */ function sellerEscrowDepositWithCreatorShareBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare) public virtual override returns (bool success) { success = false; for (uint256 i = 0; i < _assetIds.length; i++) { if (!sellerEscrowDepositWithCreatorShare(_ledger, _assetIds[i], _creatorResaleShare)) { success = false; break; } else { success = true; } } } /** * @dev See {IRadRouter-sellerEscrowDepositWithCreatorShareWithMinPrice}. */ function sellerEscrowDepositWithCreatorShareWithMinPrice(address _ledger, uint256 _assetId, uint256 _creatorResaleShare, uint256 _minPrice) public virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); require(_creatorResaleShare >= 0 && _creatorResaleShare <= 100, 'Creator share must be at least 0% and at most 100%'); IERC721 ledger = IERC721(_ledger); address owner = ledger.ownerOf(_assetId); require( msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can change asset ownership' ); require( ledger.isApprovedForAll(owner, address(this)) || ledger.getApproved(_assetId) == address(this), 'Must set Rad Router as an operator for all assets before depositing to escrow.' ); if ( Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0) || Ledgers[_ledger].Assets[_assetId].creator.wallet == owner || Ledgers[_ledger].Assets[_assetId].owner == owner ) { if (Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0)) { Ledgers[_ledger].Assets[_assetId].creator.wallet = owner; } require( Ledgers[_ledger].Assets[_assetId].creator.wallet == owner || Ledgers[_ledger].Assets[_assetId].creator.share == 0 || Ledgers[_ledger].Assets[_assetId].owner == owner, 'Cannot set creator share.' ); uint256 total = Ledgers[_ledger].Assets[_assetId].creator.share; address[] storage stakeholders = Ledgers[_ledger].ResaleSplits.keys; for (uint256 i = 0; i < stakeholders.length; i++) { total += Ledgers[_ledger].ResaleSplits.get(stakeholders[i]); } require(total <= 100, 'Creator share cannot exceed total ledger stakeholder when it is 100.'); Ledgers[_ledger].Assets[_assetId].creator.share = _creatorResaleShare; } success = sellerEscrowDeposit(_ledger, _assetId, true, _minPrice); } /** * @dev See {IRadRouter-sellerEscrowDepositWithCreatorShareWithMinPriceBatch}. */ function sellerEscrowDepositWithCreatorShareWithMinPriceBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare, uint256 _minPrice) public virtual override returns (bool success) { success = false; for (uint256 i = 0; i < _assetIds.length; i++) { if (!sellerEscrowDepositWithCreatorShareWithMinPrice(_ledger, _assetIds[i], _creatorResaleShare, _minPrice)) { success = false; break; } else { success = true; } } } /** * @dev See {IRadRouter-sellerEscrowDeposit}. */ function sellerEscrowDeposit(address _ledger, uint256 _assetId, bool _setMinPrice, uint256 _minPrice) public virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); IERC721 ledger = IERC721(_ledger); address owner = ledger.ownerOf(_assetId); require(msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can change asset ownership'); require(ledger.isApprovedForAll(owner, address(this)) || ledger.getApproved(_assetId) == address(this), 'Must set Rad Router as an operator for all assets before depositing to escrow'); if (_setMinPrice) { require(Ledgers[_ledger].Assets[_assetId].buyer.wallet == address(0), 'Buyer cannot escrow first when seller batch escrow deposits with set asset min price.'); setAssetMinPrice(_ledger, _assetId, _minPrice); } Ledgers[_ledger].Assets[_assetId].owner = owner; ledger.safeTransferFrom(owner, address(this), _assetId); if (Ledgers[_ledger].Assets[_assetId].buyer.wallet != address(0)) { _fulfill(_ledger, _assetId); } emit SellerEscrowChange(_ledger, _assetId, owner, true); success = true; } /** * @dev See {IRadRouter-sellerEscrowDepositBatch}. */ function sellerEscrowDepositBatch(address _ledger, uint256[] calldata _assetIds) external virtual override returns (bool success) { success = sellerEscrowDepositBatch(_ledger, _assetIds, false, 0); } /** * @dev See {IRadRouter-sellerEscrowDepositBatch}. */ function sellerEscrowDepositBatch(address _ledger, uint256[] calldata _assetIds, bool _setMinPrice, uint256 _minPrice) public virtual override returns (bool success) { for (uint256 i = 0; i < _assetIds.length; i++) { sellerEscrowDeposit(_ledger, _assetIds[i], _setMinPrice, _minPrice); } success = true; } /** * @dev See {IRadRouter-sellerEscrowWithdraw}. */ function sellerEscrowWithdraw(address _ledger, uint256 _assetId) external virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); IERC721 ledger = IERC721(_ledger); address owner = Ledgers[_ledger].Assets[_assetId].owner; require(msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can change asset ownership'); require(ledger.isApprovedForAll(owner, address(this)), 'Must set Rad Router as an operator for all assets before depositing to escrow'); Ledgers[_ledger].Assets[_assetId].creator.wallet = address(0); Ledgers[_ledger].Assets[_assetId].creator.share = 0; ledger.safeTransferFrom(address(this), owner, _assetId); emit SellerEscrowChange(_ledger, _assetId, owner, false); success = true; } /** * @dev See {IRadRouter-buyerEscrowDeposit}. */ function buyerEscrowDeposit(address _ledger, uint256 _assetId) external payable virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); require(Ledgers[_ledger].Assets[_assetId].owner != address(0), 'Asset is not being tracked'); require(msg.value >= Ledgers[_ledger].Assets[_assetId].minPrice, 'Buyer did not send enough ETH'); require (Ledgers[_ledger].Assets[_assetId].buyer.wallet == address(0), 'Another buyer has already escrowed'); Ledgers[_ledger].Assets[_assetId].buyer.wallet = msg.sender; Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed = msg.value; IERC721 ledger = IERC721(_ledger); if (ledger.ownerOf(_assetId) == address(this)) { _fulfill(_ledger, _assetId); } emit BuyerEscrowChange(_ledger, _assetId, msg.sender, true); success = true; } /** * @dev See {IRadRouter-buyerEscrowWithdraw}. */ function buyerEscrowWithdraw(address _ledger, uint256 _assetId) external virtual override returns (bool success) { require(msg.sender == Ledgers[_ledger].Assets[_assetId].buyer.wallet || msg.sender == Ledgers[_ledger].Assets[_assetId].owner || msg.sender == administrator_, 'msg.sender must be the buyer, seller, or Rad operator'); require(_ledger != address(0), 'Asset ledger cannot be the zero address'); Ledgers[_ledger].Assets[_assetId].buyer.wallet = address(0); Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed = 0; payable(Ledgers[_ledger].Assets[_assetId].buyer.wallet).transfer(Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed); emit BuyerEscrowChange(_ledger, _assetId, msg.sender, false); success = true; } /** * @dev See {IRadRouter-getSellerWallet}. */ function getSellerWallet(address _ledger, uint256 _assetId) public view override returns (address wallet) { if (Ledgers[_ledger].Assets[_assetId].owner == address(0)) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); IERC721 ledger = IERC721(_ledger); wallet = ledger.ownerOf(_assetId); } else { wallet = Ledgers[_ledger].Assets[_assetId].owner; } } /** * @dev See {IRadRouter-getBuyerWallet}. */ function getBuyerWallet(address _ledger, uint256 _assetId) public view override returns (address wallet) { wallet = Ledgers[_ledger].Assets[_assetId].buyer.wallet; } /** * @dev See {IRadRouter-getBuyerEscrow}. */ function getBuyerDeposit(address _ledger, uint256 _assetId) public view override returns (uint256 amount) { amount = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed; } /** * @dev See {IRadRouter-getAssetIsResale}. */ function getAssetIsResale(address _ledger, uint256 _assetId) public view override returns (bool resale) { resale = Ledgers[_ledger].Assets[_assetId].resale; } /** * @dev See {IRadRouter-getRetailedAssets}. */ function getRetailedAssets(address _ledger) public view override returns (uint256[] memory assets) { assets = Ledgers[_ledger].retailedAssets; } /** * @dev See {IRadRouter-getCreatorWallet}. */ function getCreatorWallet(address _ledger, uint256 _assetId) public view override returns (address wallet) { wallet = Ledgers[_ledger].Assets[_assetId].creator.wallet; } /** * @dev See {IRadRouter-getCreatorShare}. */ function getCreatorShare(address _ledger, uint256 _assetId) public view override returns (uint256 amount) { amount = Ledgers[_ledger].Assets[_assetId].creator.share; } /** * @dev Fulfills asset sale transaction and pays out all revenue split stakeholders * * Requirements: * * - `_ledger` cannot be the zero address. * - `_assetId` owner must be this contract * - `_assetId` buyer must not be the zero address * * Emits a {EscrowFulfill} event. */ function _fulfill(address _ledger, uint256 _assetId) internal virtual returns (bool success) { IERC721 ledger = IERC721(_ledger); require( ledger.ownerOf(_assetId) == address(this), 'Seller has not escrowed' ); require( Ledgers[_ledger].Assets[_assetId].buyer.wallet != address(0), 'Buyer has not escrowed' ); ledger.safeTransferFrom( address(this), Ledgers[_ledger].Assets[_assetId].buyer.wallet, _assetId ); if (!Ledgers[_ledger].Assets[_assetId].resale) { if (Ledgers[_ledger].RetailSplits.size() > 0) { uint256 totalShareSplit = 0; for (uint256 i = 0; i < Ledgers[_ledger].RetailSplits.size(); i++) { address stakeholder = Ledgers[_ledger].RetailSplits.getKeyAtIndex(i); uint256 share = Ledgers[_ledger].RetailSplits.get(stakeholder); if (totalShareSplit + share > 100) { share = totalShareSplit + share - 100; } uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * share / 100; payable(stakeholder).transfer(payout); emit StakeholderPayout(_ledger, _assetId, stakeholder, payout, share, true); totalShareSplit += share; // ignore other share stake holders if total max split has been reached if (totalShareSplit >= 100) { break; } } if (totalShareSplit < 100) { uint256 remainingShare = 100 - totalShareSplit; uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * remainingShare / 100; payable(Ledgers[_ledger].Assets[_assetId].owner).transfer(payout); emit StakeholderPayout(_ledger, _assetId, Ledgers[_ledger].Assets[_assetId].owner, payout, remainingShare, true); } } else { // if no revenue split is defined, send all to asset owner uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed; payable(ledger.ownerOf(_assetId)).transfer(payout); emit StakeholderPayout(_ledger, _assetId, ledger.ownerOf(_assetId), payout, 100, true); } Ledgers[_ledger].Assets[_assetId].resale = true; Ledgers[_ledger].retailedAssets.push(_assetId); } else { uint256 creatorResaleShare = Ledgers[_ledger].Assets[_assetId].creator.share; uint256 totalShareSplit = 0; uint256 creatorPayout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * creatorResaleShare / 100; address creator = Ledgers[_ledger].Assets[_assetId].creator.wallet; if (creatorResaleShare > 0) { totalShareSplit = creatorResaleShare; payable(creator).transfer(creatorPayout); emit StakeholderPayout(_ledger, _assetId, creator, creatorPayout, creatorResaleShare, false); } if (Ledgers[_ledger].ResaleSplits.size() > 0) { for (uint256 i = 0; i < Ledgers[_ledger].ResaleSplits.size(); i++) { address stakeholder = Ledgers[_ledger].ResaleSplits.getKeyAtIndex(i); uint256 share = Ledgers[_ledger].ResaleSplits.get(stakeholder) - (creatorResaleShare / 100); if (totalShareSplit + share > 100) { share = totalShareSplit + share - 100; } uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * share / 100; payable(stakeholder).transfer(payout); emit StakeholderPayout(_ledger, _assetId, stakeholder, payout, share, false); totalShareSplit += share; // ignore other share stake holders if total max split has been reached if (totalShareSplit >= 100) { break; } } if (totalShareSplit < 100) { uint256 remainingShare = 100 - totalShareSplit; uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * remainingShare / 100; payable(Ledgers[_ledger].Assets[_assetId].owner).transfer(payout); emit StakeholderPayout(_ledger, _assetId, Ledgers[_ledger].Assets[_assetId].owner, payout, remainingShare, false); } } else { // if no revenue split is defined, send all to asset owner uint256 remainingShare = 100 - totalShareSplit; uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * remainingShare / 100; payable(ledger.ownerOf(_assetId)).transfer(payout); emit StakeholderPayout(_ledger, _assetId, ledger.ownerOf(_assetId), payout, remainingShare, false); } } emit EscrowFulfill( _ledger, _assetId, Ledgers[_ledger].Assets[_assetId].owner, Ledgers[_ledger].Assets[_assetId].buyer.wallet, Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed ); Ledgers[_ledger].Assets[_assetId].owner = Ledgers[_ledger].Assets[_assetId].buyer.wallet; Ledgers[_ledger].Assets[_assetId].minPrice = 0; Ledgers[_ledger].Assets[_assetId].buyer.wallet = address(0); Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed = 0; success = true; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.8 <0.9.0; struct RevMap { address[] keys; uint256 total; mapping(address => IndexValue) values; } struct IndexValue { uint256 value; uint256 indexOf; bool inserted; } // https://solidity-by-example.org/app/iterable-mapping/ library RevenueSplitMapping { function get(RevMap storage map, address key) external view returns (uint256) { return map.values[key].value; } function getKeyAtIndex(RevMap storage map, uint256 index) external view returns (address) { return map.keys[index]; } function size(RevMap storage map) external view returns (uint256) { return map.keys.length; } function set(RevMap storage map, address key, uint256 val) external { if (map.values[key].inserted) { map.total-=map.values[key].value; map.values[key].value = val; map.total+=val; } else { map.values[key].inserted = true; map.values[key].value = val; map.total+=val; map.values[key].indexOf = map.keys.length; map.keys.push(key); } } function remove(RevMap storage map, address key) external { if (!map.values[key].inserted) { return; } map.total-=map.values[key].value; uint256 index = map.values[key].indexOf; uint256 lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.values[lastKey].indexOf = index; delete map.values[key]; map.keys[index] = lastKey; map.keys.pop(); } function contains(RevMap storage map, address key) external view returns(bool) { return map.values[key].inserted; } function clear(RevMap storage map) external { for (uint256 i = 0; i < map.keys.length; i++) { delete map.values[map.keys[i]]; } delete map.keys; map.total = 0; } } // 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 "../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 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); }
See {IRadRouter-sellerEscrowDeposit}./
function sellerEscrowDeposit(address _ledger, uint256 _assetId, bool _setMinPrice, uint256 _minPrice) public virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); IERC721 ledger = IERC721(_ledger); address owner = ledger.ownerOf(_assetId); require(msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can change asset ownership'); require(ledger.isApprovedForAll(owner, address(this)) || ledger.getApproved(_assetId) == address(this), 'Must set Rad Router as an operator for all assets before depositing to escrow'); if (_setMinPrice) { require(Ledgers[_ledger].Assets[_assetId].buyer.wallet == address(0), 'Buyer cannot escrow first when seller batch escrow deposits with set asset min price.'); setAssetMinPrice(_ledger, _assetId, _minPrice); } Ledgers[_ledger].Assets[_assetId].owner = owner; ledger.safeTransferFrom(owner, address(this), _assetId); if (Ledgers[_ledger].Assets[_assetId].buyer.wallet != address(0)) { _fulfill(_ledger, _assetId); } emit SellerEscrowChange(_ledger, _assetId, owner, true); success = true; }
14,949,577
./full_match/77/0x55baF24f11B4b6FC75aBc3eA15B3Dec74eC91d17/sources/project_/contracts/TigerToken.sol
totalSupply will return the tokens total supply of tokens/
function totalSupply() external override view returns (uint256){ return _totalSupply; }
5,047,046
pragma solidity ^0.4.21; /** * @title Maths * A library to make working with numbers in Solidity hurt your brain less. */ library Maths { /** * @dev Adds two addends together, returns the sum * @param addendA the first addend * @param addendB the second addend * @return sum the sum of the equation (e.g. addendA + addendB) */ function plus( uint256 addendA, uint256 addendB ) public pure returns (uint256 sum) { sum = addendA + addendB; assert(sum - addendB == addendA); return sum; } /** * @dev Subtracts the minuend from the subtrahend, returns the difference * @param minuend the minuend * @param subtrahend the subtrahend * @return difference the difference (e.g. minuend - subtrahend) */ function minus( uint256 minuend, uint256 subtrahend ) public pure returns (uint256 difference) { assert(minuend >= subtrahend); difference = minuend - subtrahend; return difference; } /** * @dev Multiplies two factors, returns the product * @param factorA the first factor * @param factorB the second factor * @return product the product of the equation (e.g. factorA * factorB) */ function mul( uint256 factorA, uint256 factorB ) public pure returns (uint256 product) { if (factorA == 0 || factorB == 0) return 0; product = factorA * factorB; assert(product / factorA == factorB); return product; } /** * @dev Multiplies two factors, returns the product * @param factorA the first factor * @param factorB the second factor * @return product the product of the equation (e.g. factorA * factorB) */ function times( uint256 factorA, uint256 factorB ) public pure returns (uint256 product) { return mul(factorA, factorB); } /** * @dev Divides the dividend by divisor, returns the truncated quotient * @param dividend the dividend * @param divisor the divisor * @return quotient the quotient of the equation (e.g. dividend / divisor) */ function div( uint256 dividend, uint256 divisor ) public pure returns (uint256 quotient) { quotient = dividend / divisor; assert(quotient * divisor == dividend); return quotient; } /** * @dev Divides the dividend by divisor, returns the truncated quotient * @param dividend the dividend * @param divisor the divisor * @return quotient the quotient of the equation (e.g. dividend / divisor) */ function dividedBy( uint256 dividend, uint256 divisor ) public pure returns (uint256 quotient) { return div(dividend, divisor); } /** * @dev Divides the dividend by divisor, returns the quotient and remainder * @param dividend the dividend * @param divisor the divisor * @return quotient the quotient of the equation (e.g. dividend / divisor) * @return remainder the remainder of the equation (e.g. dividend % divisor) */ function divideSafely( uint256 dividend, uint256 divisor ) public pure returns (uint256 quotient, uint256 remainder) { quotient = div(dividend, divisor); remainder = dividend % divisor; } /** * @dev Returns the lesser of two values. * @param a the first value * @param b the second value * @return result the lesser of the two values */ function min( uint256 a, uint256 b ) public pure returns (uint256 result) { result = a <= b ? a : b; return result; } /** * @dev Returns the greater of two values. * @param a the first value * @param b the second value * @return result the greater of the two values */ function max( uint256 a, uint256 b ) public pure returns (uint256 result) { result = a >= b ? a : b; return result; } /** * @dev Determines whether a value is less than another. * @param a the first value * @param b the second value * @return isTrue whether a is less than b */ function isLessThan(uint256 a, uint256 b) public pure returns (bool isTrue) { isTrue = a < b; return isTrue; } /** * @dev Determines whether a value is equal to or less than another. * @param a the first value * @param b the second value * @return isTrue whether a is less than or equal to b */ function isAtMost(uint256 a, uint256 b) public pure returns (bool isTrue) { isTrue = a <= b; return isTrue; } /** * @dev Determines whether a value is greater than another. * @param a the first value * @param b the second value * @return isTrue whether a is greater than b */ function isGreaterThan(uint256 a, uint256 b) public pure returns (bool isTrue) { isTrue = a > b; return isTrue; } /** * @dev Determines whether a value is equal to or greater than another. * @param a the first value * @param b the second value * @return isTrue whether a is less than b */ function isAtLeast(uint256 a, uint256 b) public pure returns (bool isTrue) { isTrue = a >= b; return isTrue; } } /** * @title Manageable */ contract Manageable { address public owner; address public manager; event OwnershipChanged(address indexed previousOwner, address indexed newOwner); event ManagementChanged(address indexed previousManager, address indexed newManager); /** * @dev The Manageable constructor sets the original `owner` of the contract to the sender * account. */ function Manageable() public { owner = msg.sender; manager = msg.sender; } /** * @dev Throws if called by any account other than the owner or manager. */ modifier onlyManagement() { require(msg.sender == owner || msg.sender == manager); _; } /** * @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)); OwnershipChanged(owner, newOwner); owner = newOwner; } /** * @dev Allows the owner or manager to replace the current manager * @param newManager The address to give contract management rights. */ function replaceManager(address newManager) public onlyManagement { require(newManager != address(0)); ManagementChanged(manager, newManager); manager = newManager; } } contract ERC20 { function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); } contract AbnormalERC20 { function transfer(address to, uint256 value) public; } contract MythereumERC20Token is ERC20 { function burn(address burner, uint256 amount) public returns (bool); function mint(address to, uint256 amount) public returns (bool); } contract MythereumCardToken { function mintRandomCards( address _owner, uint8 _editionNumber, uint8 _numCards ) public returns (bool); function improveCard( uint256 _tokenId, uint256 _addedDamage, uint256 _addedShield ) public returns (bool); } contract Mythereum is Manageable { using Maths for uint256; struct Edition { string name; uint256 sales; uint256 maxSales; uint8 packSize; uint256 packPrice; uint256 packPriceIncrease; } mapping (uint8 => Edition) public editions; mapping (address => bool) public isVIP; mapping (address => bool) public isTokenAccepted; mapping (address => uint256) public tokenCostPerPack; mapping (uint256 => uint256) public mythexCostPerUpgradeLevel; mapping (uint256 => uint256) public cardDamageUpgradeLevel; mapping (uint256 => uint256) public cardShieldUpgradeLevel; uint256 public maxCardUpgradeLevel = 30; address public cardTokenAddress; address public xpTokenAddress; address public mythexTokenAddress; address public gameHostAddress; /* data related to shared ownership */ uint256 public totalShares = 0; uint256 public totalReleased = 0; mapping(address => uint256) public shares; mapping(address => uint256) public released; event CardsPurchased(uint256 editionNumber, uint256 packSize, address buyer); event CardUpgraded(uint256 cardId, uint256 addedDamage, uint256 addedShield); modifier onlyHosts() { require( msg.sender == owner || msg.sender == manager || msg.sender == gameHostAddress ); _; } function Mythereum() public { editions[0] = Edition({ name: "Genesis", sales: 4139, maxSales: 5000, packSize: 7, packPrice: 177000000000000000, packPriceIncrease: 1 finney }); editions[1] = Edition({ name: "Survivor", sales: 20, maxSales: 1000000, packSize: 10, packPrice: 0, packPriceIncrease: 0 }); isVIP[msg.sender] = true; } /** * @dev Disallow funds being sent directly to the contract since we can't know * which edition they'd intended to purchase. */ function () public payable { revert(); } function buyPack( uint8 _editionNumber ) public payable { uint256 packPrice = isVIP[msg.sender] ? 0 : editions[_editionNumber].packPrice; require(msg.value.isAtLeast(packPrice)); if (msg.value.isGreaterThan(packPrice)) { msg.sender.transfer(msg.value.minus(packPrice)); } _deliverPack(msg.sender, _editionNumber); } function buyPackWithERC20Tokens( uint8 _editionNumber, address _tokenAddress ) public { require(isTokenAccepted[_tokenAddress]); _processERC20TokenPackPurchase(_editionNumber, _tokenAddress, msg.sender); } function upgradeCardDamage(uint256 _cardId) public { require(cardDamageUpgradeLevel[_cardId].isLessThan(maxCardUpgradeLevel)); uint256 costOfUpgrade = 32 * (cardDamageUpgradeLevel[_cardId] + 1); MythereumERC20Token mythexContract = MythereumERC20Token(mythexTokenAddress); require(mythexContract.burn(msg.sender, costOfUpgrade)); cardDamageUpgradeLevel[_cardId]++; _improveCard(_cardId, 1, 0); } function upgradeCardShield(uint256 _cardId) public { require(cardShieldUpgradeLevel[_cardId].isLessThan(maxCardUpgradeLevel)); uint256 costOfUpgrade = 32 * (cardShieldUpgradeLevel[_cardId] + 1); MythereumERC20Token mythexContract = MythereumERC20Token(mythexTokenAddress); require(mythexContract.burn(msg.sender, costOfUpgrade)); cardShieldUpgradeLevel[_cardId]++; _improveCard(_cardId, 0, 1); } function improveCard( uint256 _cardId, uint256 _addedDamage, uint256 _addedShield ) public onlyManagement { require(cardShieldUpgradeLevel[_cardId].isLessThan(maxCardUpgradeLevel)); _improveCard(_cardId, _addedDamage, _addedShield); } function _improveCard( uint256 _cardId, uint256 _addedDamage, uint256 _addedShield ) internal { MythereumCardToken cardToken = MythereumCardToken(cardTokenAddress); require(cardToken.improveCard(_cardId, _addedDamage, _addedShield)); CardUpgraded(_cardId, _addedDamage, _addedShield); } function receiveApproval( address _sender, uint256 _value, address _tokenContract, bytes _extraData ) public { require(isTokenAccepted[_tokenContract]); uint8 editionNumber = 0; if (_extraData.length != 0) editionNumber = uint8(_extraData[0]); _processERC20TokenPackPurchase(editionNumber, _tokenContract, _sender); } function _processERC20TokenPackPurchase( uint8 _editionNumber, address _tokenAddress, address _buyer ) internal { require(isTokenAccepted[_tokenAddress]); ERC20 tokenContract = ERC20(_tokenAddress); uint256 costPerPack = tokenCostPerPack[_tokenAddress]; uint256 ourBalanceBefore = tokenContract.balanceOf(address(this)); tokenContract.transferFrom(_buyer, address(this), costPerPack); uint256 ourBalanceAfter = tokenContract.balanceOf(address(this)); require(ourBalanceAfter.isAtLeast(ourBalanceBefore.plus(costPerPack))); _deliverPack(_buyer, _editionNumber); } function burnMythexTokens(address _burner, uint256 _amount) public onlyHosts { require(_burner != address(0)); MythereumERC20Token(mythexTokenAddress).burn(_burner, _amount); } function burnXPTokens(address _burner, uint256 _amount) public onlyHosts { require(_burner != address(0)); MythereumERC20Token(xpTokenAddress).burn(_burner, _amount); } function grantMythexTokens(address _recipient, uint256 _amount) public onlyHosts { require(_recipient != address(0)); MythereumERC20Token(mythexTokenAddress).mint(_recipient, _amount); } function grantXPTokens(address _recipient, uint256 _amount) public onlyHosts { require(_recipient != address(0)); MythereumERC20Token(xpTokenAddress).mint(_recipient, _amount); } function grantPromoPack( address _recipient, uint8 _editionNumber ) public onlyManagement { _deliverPack(_recipient, _editionNumber); } function setTokenAcceptanceRate( address _token, uint256 _costPerPack ) public onlyManagement { if (_costPerPack > 0) { isTokenAccepted[_token] = true; tokenCostPerPack[_token] = _costPerPack; } else { isTokenAccepted[_token] = false; tokenCostPerPack[_token] = 0; } } function transferERC20Tokens( address _token, address _recipient, uint256 _amount ) public onlyManagement { require(ERC20(_token).transfer(_recipient, _amount)); } function transferAbnormalERC20Tokens( address _token, address _recipient, uint256 _amount ) public onlyManagement { // certain ERC20s don't return bool success flags :( AbnormalERC20(_token).transfer(_recipient, _amount); } function addVIP(address _vip) public onlyManagement { isVIP[_vip] = true; } function removeVIP(address _vip) public onlyManagement { isVIP[_vip] = false; } function setEditionName( uint8 _editionNumber, string _name ) public onlyManagement { editions[_editionNumber].name = _name; } function setEditionSales( uint8 _editionNumber, uint256 _numSales ) public onlyManagement { editions[_editionNumber].sales = _numSales; } function setEditionMaxSales( uint8 _editionNumber, uint256 _maxSales ) public onlyManagement { editions[_editionNumber].maxSales = _maxSales; } function setEditionPackPrice( uint8 _editionNumber, uint256 _newPrice ) public onlyManagement { editions[_editionNumber].packPrice = _newPrice; } function setEditionPackPriceIncrease( uint8 _editionNumber, uint256 _increase ) public onlyManagement { editions[_editionNumber].packPriceIncrease = _increase; } function setEditionPackSize( uint8 _editionNumber, uint8 _newSize ) public onlyManagement { editions[_editionNumber].packSize = _newSize; } function setCardUpgradeLevels( uint256 _cardId, uint256 _damageUpgradeLevel, uint256 _shieldUpgradeLevel ) public onlyManagement { cardDamageUpgradeLevel[_cardId] = _damageUpgradeLevel; cardShieldUpgradeLevel[_cardId] = _shieldUpgradeLevel; } function setCardTokenAddress(address _addr) public onlyManagement { require(_addr != address(0)); cardTokenAddress = _addr; } function setXPTokenAddress(address _addr) public onlyManagement { require(_addr != address(0)); xpTokenAddress = _addr; } function setMythexTokenAddress(address _addr) public onlyManagement { require(_addr != address(0)); mythexTokenAddress = _addr; } function setGameHostAddress(address _addr) public onlyManagement { require(_addr != address(0)); gameHostAddress = _addr; } function claim() public { _claim(msg.sender); } function deposit() public payable { // this is for crediting funds to the contract - only meant for internal use } function addShareholder(address _payee, uint256 _shares) public onlyOwner { require(_payee != address(0)); require(_shares.isAtLeast(1)); require(shares[_payee] == 0); shares[_payee] = _shares; totalShares = totalShares.plus(_shares); } function removeShareholder(address _payee) public onlyOwner { require(shares[_payee] != 0); _claim(_payee); _forfeitShares(_payee, shares[_payee]); } function grantAdditionalShares( address _payee, uint256 _shares ) public onlyOwner { require(shares[_payee] != 0); require(_shares.isAtLeast(1)); shares[_payee] = shares[_payee].plus(_shares); totalShares = totalShares.plus(_shares); } function forfeitShares(uint256 _numShares) public { _forfeitShares(msg.sender, _numShares); } function transferShares(address _to, uint256 _numShares) public { require(_numShares.isAtLeast(1)); require(shares[msg.sender].isAtLeast(_numShares)); shares[msg.sender] = shares[msg.sender].minus(_numShares); shares[_to] = shares[_to].plus(_numShares); } function _claim(address payee) internal { require(shares[payee].isAtLeast(1)); uint256 totalReceived = address(this).balance.plus(totalReleased); uint256 payment = totalReceived.times(shares[payee]).dividedBy(totalShares).minus(released[payee]); require(payment != 0); require(address(this).balance.isAtLeast(payment)); released[payee] = released[payee].plus(payment); totalReleased = totalReleased.plus(payment); payee.transfer(payment); } function _forfeitShares(address payee, uint256 numShares) internal { require(shares[payee].isAtLeast(numShares)); shares[payee] = shares[payee].minus(numShares); totalShares = totalShares.minus(numShares); } function _deliverPack(address recipient, uint8 editionNumber) internal { Edition storage edition = editions[editionNumber]; require(edition.sales.isLessThan(edition.maxSales.plus(edition.packSize))); edition.sales = edition.sales.plus(edition.packSize); edition.packPrice = edition.packPrice.plus(edition.packPriceIncrease); MythereumCardToken cardToken = MythereumCardToken(cardTokenAddress); cardToken.mintRandomCards(recipient, editionNumber, edition.packSize); CardsPurchased(editionNumber, edition.packSize, recipient); } }
this is for crediting funds to the contract - only meant for internal use
function deposit() public payable { }
564,985
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint256 _amount, bytes calldata _params ) external virtual; function deposit( address _reserve, uint256 _amount, uint16 _referralCode ) external payable virtual; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow( address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode ) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf ) external payable virtual; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external view virtual returns (address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external view virtual returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external view virtual returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external view virtual returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external view virtual returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public view virtual returns (address); function getReserveConfiguration(address _reserve) external view virtual returns ( uint256, uint256, uint256, bool ); function getUserUnderlyingAssetBalance(address _reserve, address _user) public view virtual returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public view virtual returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public view virtual returns (uint256); function getReserveTotalLiquidity(address _reserve) public view virtual returns (uint256); function getReserveAvailableLiquidity(address _reserve) public view virtual returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public view virtual returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public view virtual returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } abstract contract DSGuard { function canCall( address src_, address dst_, bytes4 sig ) public view virtual returns (bool); function permit( bytes32 src, bytes32 dst, bytes32 sig ) public virtual; function forbid( bytes32 src, bytes32 dst, bytes32 sig ) public virtual; function permit( address src, address dst, bytes32 sig ) public virtual; function forbid( address src, address dst, bytes32 sig ) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } abstract contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view virtual returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "Not authorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } /// @title ProxyPermission Proxy contract which works with DSProxy to give execute permission contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } function proxyOwner() internal view returns (address) { return DSAuth(address(this)).owner(); } } abstract contract IDFSRegistry { function getAddr(bytes32 _id) public view virtual returns (address); function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public virtual; function startContractChange(bytes32 _id, address _newContractAddr) public virtual; function approveContractChange(bytes32 _id) public virtual; function cancelContractChange(bytes32 _id) public virtual; function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual; } interface IERC20 { function totalSupply() external view returns (uint256 supply); 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); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library Address { 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); } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } 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"); } 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); } } } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library 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 Edited so it always first approves 0 and then the value, because of non standard tokens function safeApprove( IERC20 token, address spender, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _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) ); } function _callOptionalReturn(IERC20 token, bytes memory data) private { 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"); } } } /// @title A stateful contract that holds and can change owner/admin contract AdminVault { address public owner; address public admin; constructor() { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function changeOwner(address _owner) public { require(admin == msg.sender, "msg.sender not admin"); owner = _owner; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function changeAdmin(address _admin) public { require(admin == msg.sender, "msg.sender not admin"); admin = _admin; } } /// @title AdminAuth Handles owner/admin privileges over smart contracts contract AdminAuth { using SafeERC20 for IERC20; AdminVault public constant adminVault = AdminVault(0xCCf3d848e08b94478Ed8f46fFead3008faF581fD); modifier onlyOwner() { require(adminVault.owner() == msg.sender, "msg.sender not owner"); _; } modifier onlyAdmin() { require(adminVault.admin() == msg.sender, "msg.sender not admin"); _; } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(_receiver).transfer(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } /// @notice Destroy the contract function kill() public onlyAdmin { selfdestruct(payable(msg.sender)); } } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log( address _contract, address _caller, string memory _logName, bytes memory _data ) public { emit LogEvent(_contract, _caller, _logName, _data); } } /// @title Stores all the important DFS addresses and can be changed (timelock) contract DFSRegistry is AdminAuth { DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists"; string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists"; string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process"; string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger"; string public constant ERR_CHANGE_NOT_READY = "Change not ready yet"; string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0"; string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change"; string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change"; struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes32 => Entry) public entries; mapping(bytes32 => address) public previousAddresses; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registered address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes32 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registered /// @param _id Id of contract function isRegistered(bytes32 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS); entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); // Remember tha address so we can revert back to old addr if needed previousAddresses[_id] = _contractAddr; logger.Log( address(this), msg.sender, "AddNewContract", abi.encode(_id, _contractAddr, _waitPeriod) ); } /// @notice Reverts to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR); address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; logger.Log( address(this), msg.sender, "RevertToPreviousAddress", abi.encode(_id, currentAddr, previousAddresses[_id]) ); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE); entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; logger.Log( address(this), msg.sender, "StartContractChange", abi.encode(_id, entries[_id].contractAddr, _newContractAddr) ); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; logger.Log( address(this), msg.sender, "ApproveContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE); pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; logger.Log( address(this), msg.sender, "StartWaitPeriodChange", abi.encode(_id, _newWaitPeriod) ); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; logger.Log( address(this), msg.sender, "ApproveWaitPeriodChange", abi.encode(_id, oldWaitTime, entries[_id].waitPeriod) ); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelWaitPeriodChange", abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod) ); } } /// @title Implements Action interface and common helpers for passing inputs abstract contract ActionBase is AdminAuth { address public constant REGISTRY_ADDR = 0xD6049E1F5F3EfF1F921f5532aF1A1632bA23929C; DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value"; string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value"; /// @dev Subscription params index range [128, 255] uint8 public constant SUB_MIN_INDEX_VALUE = 128; uint8 public constant SUB_MAX_INDEX_VALUE = 255; /// @dev Return params index range [1, 127] uint8 public constant RETURN_MIN_INDEX_VALUE = 1; uint8 public constant RETURN_MAX_INDEX_VALUE = 127; /// @dev If the input value should not be replaced uint8 public constant NO_PARAM_MAPPING = 0; /// @dev We need to parse Flash loan actions in a different way enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the TaskExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes[] memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (uint)); } } return _param; } /// @notice Given an addr input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamAddr( address _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (address) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = address(bytes20((_returnValues[getReturnIndex(_mapType)]))); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (address)); } } return _param; } /// @notice Given an bytes32 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamABytes32( bytes32 _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (bytes32) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = (_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32)); } } return _param; } /// @notice Checks if the paramMapping value indicated that we need to inject values /// @param _type Indicated the type of the input function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; } /// @notice Checks if the paramMapping value is in the return value range /// @param _type Indicated the type of the input function isReturnInjection(uint8 _type) internal pure returns (bool) { return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in return array value /// @param _type Indicated the type of the input function getReturnIndex(uint8 _type) internal pure returns (uint8) { require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE); return (_type - RETURN_MIN_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in sub array value /// @param _type Indicated the type of the input function getSubIndex(uint8 _type) internal pure returns (uint8) { require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE); return (_type - SUB_MIN_INDEX_VALUE); } } abstract contract IDSProxy { // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address, bytes32); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32); function setCache(address _cacheAddr) public payable virtual returns (bool); function owner() public view virtual returns (address); } /// @title Struct data in a separate contract so it can be used in multiple places contract StrategyData { struct Template { string name; bytes32[] triggerIds; bytes32[] actionIds; uint8[][] paramMapping; } struct Task { string name; bytes[][] callData; bytes[][] subData; bytes32[] actionIds; uint8[][] paramMapping; } struct Strategy { uint templateId; address proxy; bytes[][] subData; bytes[][] triggerData; bool active; uint posInUserArr; } } /// @title Storage of strategies and templates contract Subscriptions is StrategyData, AdminAuth { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); string public constant ERR_EMPTY_STRATEGY = "Strategy does not exist"; string public constant ERR_SENDER_NOT_OWNER = "Sender is not strategy owner"; string public constant ERR_USER_POS_EMPTY = "No user positions"; /// @dev The order of strategies might change as they are deleted Strategy[] public strategies; /// @dev Templates are fixed and are non removable Template[] public templates; /// @dev Keeps track of all the users strategies (their indexes in the array) mapping (address => uint[]) public usersPos; /// @dev Increments on state change, used for easier off chain tracking of changes uint public updateCounter; /// @notice Creates a new strategy with an existing template /// @param _templateId Id of the template used for strategy /// @param _active If the strategy is turned on at the start /// @param _subData Subscription data for actions /// @param _triggerData Subscription data for triggers function createStrategy( uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public returns (uint) { strategies.push( Strategy({ templateId: _templateId, proxy: msg.sender, active: _active, subData: _subData, triggerData: _triggerData, posInUserArr: (usersPos[msg.sender].length - 1) }) ); usersPos[msg.sender].push(strategies.length - 1); updateCounter++; logger.Log(address(this), msg.sender, "CreateStrategy", abi.encode(strategies.length - 1)); return strategies.length - 1; } /// @notice Creates a new template to use in strategies /// @dev Templates once created can't be changed /// @param _name Name of template, used mainly for logging /// @param _triggerIds Array of trigger ids which translate to trigger addresses /// @param _actionIds Array of actions ids which translate to action addresses /// @param _paramMapping Array that holds metadata of how inputs are mapped to sub/return data function createTemplate( string memory _name, bytes32[] memory _triggerIds, bytes32[] memory _actionIds, uint8[][] memory _paramMapping ) public returns (uint) { templates.push( Template({ name: _name, triggerIds: _triggerIds, actionIds: _actionIds, paramMapping: _paramMapping }) ); updateCounter++; logger.Log(address(this), msg.sender, "CreateTemplate", abi.encode(templates.length - 1)); return templates.length - 1; } /// @notice Updates the users strategy /// @dev Only callable by proxy who created the strategy /// @param _strategyId Id of the strategy to update /// @param _templateId Id of the template used for strategy /// @param _active If the strategy is turned on at the start /// @param _subData Subscription data for actions /// @param _triggerData Subscription data for triggers function updateStrategy( uint _strategyId, uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public { Strategy storage s = strategies[_strategyId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); s.templateId = _templateId; s.active = _active; s.subData = _subData; s.triggerData = _triggerData; updateCounter++; logger.Log(address(this), msg.sender, "UpdateStrategy", abi.encode(_strategyId)); } /// @notice Unsubscribe an existing strategy /// @dev Only callable by proxy who created the strategy /// @param _subId Subscription id function removeStrategy(uint256 _subId) public { Strategy memory s = strategies[_subId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); uint lastSub = strategies.length - 1; _removeUserPos(msg.sender, s.posInUserArr); strategies[_subId] = strategies[lastSub]; // last strategy put in place of the deleted one strategies.pop(); // delete last strategy, because it moved logger.Log(address(this), msg.sender, "Unsubscribe", abi.encode(_subId)); } function _removeUserPos(address _user, uint _index) internal { require(usersPos[_user].length > 0, ERR_USER_POS_EMPTY); uint lastPos = usersPos[_user].length - 1; usersPos[_user][_index] = usersPos[_user][lastPos]; usersPos[_user].pop(); } ///////////////////// VIEW ONLY FUNCTIONS //////////////////////////// function getTemplateFromStrategy(uint _strategyId) public view returns (Template memory) { uint templateId = strategies[_strategyId].templateId; return templates[templateId]; } function getStrategy(uint _strategyId) public view returns (Strategy memory) { return strategies[_strategyId]; } function getTemplate(uint _templateId) public view returns (Template memory) { return templates[_templateId]; } function getStrategyCount() public view returns (uint256) { return strategies.length; } function getTemplateCount() public view returns (uint256) { return templates.length; } function getStrategies() public view returns (Strategy[] memory) { return strategies; } function getTemplates() public view returns (Template[] memory) { return templates; } function userHasStrategies(address _user) public view returns (bool) { return usersPos[_user].length > 0; } function getUserStrategies(address _user) public view returns (Strategy[] memory) { Strategy[] memory userStrategies = new Strategy[](usersPos[_user].length); for (uint i = 0; i < usersPos[_user].length; ++i) { userStrategies[i] = strategies[usersPos[_user][i]]; } return userStrategies; } function getPaginatedStrategies(uint _page, uint _perPage) public view returns (Strategy[] memory) { Strategy[] memory strategiesPerPage = new Strategy[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > strategiesPerPage.length) ? strategiesPerPage.length : end; uint count = 0; for (uint i = start; i < end; i++) { strategiesPerPage[count] = strategies[i]; count++; } return strategiesPerPage; } function getPaginatedTemplates(uint _page, uint _perPage) public view returns (Template[] memory) { Template[] memory templatesPerPage = new Template[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > templatesPerPage.length) ? templatesPerPage.length : end; uint count = 0; for (uint i = start; i < end; i++) { templatesPerPage[count] = templates[i]; count++; } return templatesPerPage; } } /// @title Handles FL taking and executes actions contract TaskExecutor is StrategyData, ProxyPermission, AdminAuth { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant REGISTRY_ADDR = 0xD6049E1F5F3EfF1F921f5532aF1A1632bA23929C; DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); bytes32 constant SUBSCRIPTION_ID = keccak256("Subscriptions"); /// @notice Called directly through DsProxy to execute a task /// @dev This is the main entry point for Recipes/Tasks executed manually /// @param _currTask Task to be executed function executeTask(Task memory _currTask) public payable { _executeActions(_currTask); } /// @notice Called through the Strategy contract to execute a task /// @param _strategyId Id of the strategy we want to execute /// @param _actionCallData All the data related to the strategies Task function executeStrategyTask(uint256 _strategyId, bytes[][] memory _actionCallData) public payable { address subAddr = registry.getAddr(SUBSCRIPTION_ID); Strategy memory strategy = Subscriptions(subAddr).getStrategy(_strategyId); Template memory template = Subscriptions(subAddr).getTemplate(strategy.templateId); Task memory currTask = Task({ name: template.name, callData: _actionCallData, subData: strategy.subData, actionIds: template.actionIds, paramMapping: template.paramMapping }); _executeActions(currTask); } /// @notice This is the callback function that FL actions call /// @dev FL function must be the first action and repayment is done last /// @param _currTask Task to be executed /// @param _flAmount Result value from FL action function _executeActionsFromFL(Task memory _currTask, bytes32 _flAmount) public payable { bytes32[] memory returnValues = new bytes32[](_currTask.actionIds.length); returnValues[0] = _flAmount; // set the flash loan action as first return value // skips the first actions as it was the fl action for (uint256 i = 1; i < _currTask.actionIds.length; ++i) { returnValues[i] = _executeAction(_currTask, i, returnValues); } } /// @notice Runs all actions from the task /// @dev FL action must be first and is parsed separately, execution will go to _executeActionsFromFL /// @param _currTask to be executed function _executeActions(Task memory _currTask) internal { address firstActionAddr = registry.getAddr(_currTask.actionIds[0]); bytes32[] memory returnValues = new bytes32[](_currTask.actionIds.length); if (isFL(firstActionAddr)) { _parseFLAndExecute(_currTask, firstActionAddr, returnValues); } else { for (uint256 i = 0; i < _currTask.actionIds.length; ++i) { returnValues[i] = _executeAction(_currTask, i, returnValues); } } /// log the task name DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, _currTask.name, ""); } /// @notice Gets the action address and executes it /// @param _currTask Task to be executed /// @param _index Index of the action in the task array /// @param _returnValues Return values from previous actions function _executeAction( Task memory _currTask, uint256 _index, bytes32[] memory _returnValues ) internal returns (bytes32 response) { response = IDSProxy(address(this)).execute( registry.getAddr(_currTask.actionIds[_index]), abi.encodeWithSignature( "executeAction(bytes[],bytes[],uint8[],bytes32[])", _currTask.callData[_index], _currTask.subData[_index], _currTask.paramMapping[_index], _returnValues ) ); } /// @notice Prepares and executes a flash loan action /// @dev It adds to the last input value of the FL, the task data so it can be passed on /// @param _currTask Task to be executed /// @param _flActionAddr Address of the flash loan action /// @param _returnValues An empty array of return values, because it's the first action function _parseFLAndExecute( Task memory _currTask, address _flActionAddr, bytes32[] memory _returnValues ) internal { givePermission(_flActionAddr); bytes memory taskData = abi.encode(_currTask, address(this)); // last input value is empty for FL action, attach task data there _currTask.callData[0][_currTask.callData[0].length - 1] = taskData; /// @dev FL action is called directly so that we can check who the msg.sender of FL is ActionBase(_flActionAddr).executeAction( _currTask.callData[0], _currTask.subData[0], _currTask.paramMapping[0], _returnValues ); removePermission(_flActionAddr); } /// @notice Checks if the specified address is of FL type action /// @param _actionAddr Address of the action function isFL(address _actionAddr) internal pure returns (bool) { return ActionBase(_actionAddr).actionType() == uint8(ActionBase.ActionType.FL_ACTION); } }
Called through the Strategy contract to execute a task _strategyId Id of the strategy we want to execute _actionCallData All the data related to the strategies Task
function executeStrategyTask(uint256 _strategyId, bytes[][] memory _actionCallData) public payable { address subAddr = registry.getAddr(SUBSCRIPTION_ID); Strategy memory strategy = Subscriptions(subAddr).getStrategy(_strategyId); Template memory template = Subscriptions(subAddr).getTemplate(strategy.templateId); Task memory currTask = Task({ name: template.name, callData: _actionCallData, subData: strategy.subData, actionIds: template.actionIds, paramMapping: template.paramMapping }); _executeActions(currTask); }
403,510
pragma solidity ^0.4.23; library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; assert(c >= a); return c; } } contract Token { function transferFrom(address from, address to, uint256 tokens) public returns (bool success); function transfer(address to, uint256 tokens) public returns (bool success); } contract TokenLiquidityContract { using SafeMath for uint256; address public admin; address public traded_token; uint256 public eth_seed_amount; uint256 public traded_token_seed_amount; uint256 public commission_ratio; uint256 public eth_balance; uint256 public traded_token_balance; bool public eth_is_seeded; bool public traded_token_is_seeded; bool public trading_deactivated; bool public admin_commission_activated; modifier only_admin() { require(msg.sender == admin); _; } modifier trading_activated() { require(trading_deactivated == false); _; } constructor(address _traded_token,uint256 _eth_seed_amount, uint256 _traded_token_seed_amount, uint256 _commission_ratio) public { admin = msg.sender; traded_token = _traded_token; eth_seed_amount = _eth_seed_amount; traded_token_seed_amount = _traded_token_seed_amount; commission_ratio = _commission_ratio; } function transferTokensThroughProxyToContract(address _from, address _to, uint256 _amount) private { traded_token_balance = traded_token_balance.add(_amount); require(Token(traded_token).transferFrom(_from,_to,_amount)); } function transferTokensFromContract(address _to, uint256 _amount) private { traded_token_balance = traded_token_balance.sub(_amount); require(Token(traded_token).transfer(_to,_amount)); } function transferETHToContract() private { eth_balance = eth_balance.add(msg.value); } function transferETHFromContract(address _to, uint256 _amount) private { eth_balance = eth_balance.sub(_amount); _to.transfer(_amount); } function deposit_token(uint256 _amount) private { transferTokensThroughProxyToContract(msg.sender, this, _amount); } function deposit_eth() private { transferETHToContract(); } function withdraw_token(uint256 _amount) public only_admin { transferTokensFromContract(admin, _amount); } function withdraw_eth(uint256 _amount) public only_admin { transferETHFromContract(admin, _amount); } function set_traded_token_as_seeded() private { traded_token_is_seeded = true; } function set_eth_as_seeded() private { eth_is_seeded = true; } function seed_traded_token() public only_admin { require(!traded_token_is_seeded); set_traded_token_as_seeded(); deposit_token(traded_token_seed_amount); } function seed_eth() public payable only_admin { require(!eth_is_seeded); require(msg.value == eth_seed_amount); set_eth_as_seeded(); deposit_eth(); } function seed_additional_token(uint256 _amount) public only_admin { require(market_is_open()); deposit_token(_amount); } function seed_additional_eth() public payable only_admin { require(market_is_open()); deposit_eth(); } function market_is_open() private view returns(bool) { return (eth_is_seeded && traded_token_is_seeded); } function deactivate_trading() public only_admin { require(!trading_deactivated); trading_deactivated = true; } function reactivate_trading() public only_admin { require(trading_deactivated); trading_deactivated = false; } /// buyAmount*amountTokenA/(amountTokenB + buyAmount) /// buy: (tokenAmountInContract*_ethAmountFromBuyer)/(contract_eth_balamce + _ethAmountFromBuyer) /// sell: sellAmount*(contract_eth_balance)/(tokenAmount + sellAmount) function get_amount_sell(uint256 _amount) public view returns(uint256) { return eth_balance.mul(_amount) / traded_token_balance.add(_amount); } function get_amount_buy(uint256 _amount) public view returns(uint256) { return traded_token_balance.mul(_amount) / eth_balance.add(_amount); } function get_amount_minus_commission(uint256 _amount) private view returns(uint256) { return (_amount*(1 ether - commission_ratio))/(1 ether); } function activate_admin_commission() public only_admin { require(!admin_commission_activated); admin_commission_activated = true; } function deactivate_admin_comission() public only_admin { require(admin_commission_activated); admin_commission_activated = false; } function change_admin_commission(uint256 _new_commission_ratio) public only_admin { require(_new_commission_ratio != commission_ratio); commission_ratio = _new_commission_ratio; } function complete_sell_exchange(uint256 _amount_give) private { uint256 amount_get_ = get_amount_sell(_amount_give); // this is the amount that is transferred to the seller -minus the commision ANYWAY (even if admin_commission_activated is False) uint256 amount_get_minus_commission_ = get_amount_minus_commission(amount_get_); transferTokensThroughProxyToContract(msg.sender,this,_amount_give); // the commission is transferred to admin only if admin_commission_activated, but the commission is subtracted anyway if(admin_commission_activated) { transferETHFromContract(msg.sender,amount_get_minus_commission_); uint256 admin_commission_ = amount_get_ - amount_get_minus_commission_; transferETHFromContract(admin, admin_commission_); } else { transferETHFromContract(msg.sender,amount_get_); } } function complete_buy_exchange() private { // SAME problem that is in complete_sell_exchange uint256 amount_give_ = msg.value; uint256 amount_get_ = get_amount_buy(amount_give_); uint256 amount_get_minus_commission_ = get_amount_minus_commission(amount_get_); transferETHToContract(); if(admin_commission_activated) { transferTokensFromContract(msg.sender, amount_get_minus_commission_); // minus commision anyway? uint256 admin_commission_ = amount_get_ - amount_get_minus_commission_; // not safe if commision is calculated in a weird way? transferTokensFromContract(admin, admin_commission_); } else { transferTokensFromContract(msg.sender, amount_get_); } } function sell_tokens(uint256 _amount_give) public trading_activated { require(market_is_open()); complete_sell_exchange(_amount_give); } function buy_tokens() private trading_activated { require(market_is_open()); complete_buy_exchange(); } function() public payable { buy_tokens(); } }
SAME problem that is in complete_sell_exchange
function complete_buy_exchange() private { uint256 amount_give_ = msg.value; uint256 amount_get_ = get_amount_buy(amount_give_); uint256 amount_get_minus_commission_ = get_amount_minus_commission(amount_get_); transferETHToContract(); if(admin_commission_activated) { transferTokensFromContract(admin, admin_commission_); } else { transferTokensFromContract(msg.sender, amount_get_); } }
6,752,908
./full_match/3/0xcfF195483b171C222CF634aD9D97c68002e4B084/sources/contracts/pool/FlipperVault.sol
Add a new token pool. Can only be called by the owner. Note contract owner is meant to be a governance contract allowing FLIPPER governance consensus
function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accFlipperPerShare: 0, withdrawable : _withdrawable }) ); }
14,176,316
./full_match/4/0x25fDC017Ed1F88ba671E6A487e837f09c76AD139/sources/_EBTtoken1.sol
Returns true if the contract is paused, and false otherwise./
function paused() public view virtual returns (bool) { return _paused; }
13,303,971
/** *Submitted for verification at Etherscan.io on 2021-03-18 */ // File: interfaces/DelegatorInterface.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract DelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } abstract contract DelegatorInterface is DelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation( address oldImplementation, address newImplementation ); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public virtual; } abstract contract DelegateInterface is DelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public virtual; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public virtual; } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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/utils/Address.sol 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 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: @openzeppelin/contracts/utils/Context.sol 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 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: @uniswap/lib/contracts/libraries/FullMath.sol pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } // File: @uniswap/lib/contracts/libraries/Babylonian.sol pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // File: @uniswap/lib/contracts/libraries/BitMath.sol pragma solidity >=0.5.0; library BitMath { // returns the 0 indexed position of the most significant bit of the input x // s.t. x >= 2**msb and x < 2**(msb+1) function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } // returns the 0 indexed position of the least significant bit of the input x // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0) // i.e. the bit at the index is set and the mask of all lower bits is 0 function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } // File: @uniswap/lib/contracts/libraries/FixedPoint.sol pragma solidity >=0.4.0; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 public constant RESOLUTION = 112; uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112 uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224 uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z = 0; require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow'); return uq144x112(z); } // multiply a UQ112x112 by an int and decode, returning an int // reverts on overflow function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); } // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 // lossy function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 // partial products uint224 upper = uint224(upper_self) * upper_other; // * 2^0 uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 // so the bit shift does not overflow require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow'); // this cannot exceed 256 bits, all values are 224 bits uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); // so the cast does not overflow require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow'); return uq112x112(uint224(sum)); } // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // can be lossy function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // take the reciprocal of a UQ112x112 // reverts on overflow // lossy function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero'); require(self._x != 1, 'FixedPoint::reciprocal: overflow'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: @uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol pragma solidity >=0.5.0; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // File: interfaces/IInvitation.sol pragma solidity 0.6.12; interface IInvitation{ function acceptInvitation(address _invitor) external; function getInvitation(address _sender) external view returns(address _invitor, address[] memory _invitees, bool _isWithdrawn); } // File: contracts/ActivityBase.sol pragma solidity 0.6.12; contract ActivityBase is Ownable{ using SafeMath for uint256; address public admin; address public marketingFund; // token as the unit of measurement address public WETHToken; // invitee's supply 5% deposit weight to its invitor uint256 public constant INVITEE_WEIGHT = 20; // invitee's supply 10% deposit weight to its invitor uint256 public constant INVITOR_WEIGHT = 10; // The block number when SHARD mining starts. uint256 public startBlock; // dev fund uint256 public userDividendWeight; uint256 public devDividendWeight; address public developerDAOFund; // deposit limit uint256 public amountFeeRateNumerator; uint256 public amountfeeRateDenominator; // contract sender fee rate uint256 public contractFeeRateNumerator; uint256 public contractFeeRateDenominator; // Info of each user is Contract sender mapping (uint256 => mapping (address => bool)) public isUserContractSender; mapping (uint256 => uint256) public poolTokenAmountLimit; function setDividendWeight(uint256 _userDividendWeight, uint256 _devDividendWeight) public virtual{ checkAdmin(); require( _userDividendWeight != 0 && _devDividendWeight != 0, "invalid input" ); userDividendWeight = _userDividendWeight; devDividendWeight = _devDividendWeight; } function setDeveloperDAOFund(address _developerDAOFund) public virtual onlyOwner { developerDAOFund = _developerDAOFund; } function setTokenAmountLimit(uint256 _pid, uint256 _tokenAmountLimit) public virtual { checkAdmin(); poolTokenAmountLimit[_pid] = _tokenAmountLimit; } function setTokenAmountLimitFeeRate(uint256 _feeRateNumerator, uint256 _feeRateDenominator) public virtual { checkAdmin(); require( _feeRateDenominator >= _feeRateNumerator, "invalid input" ); amountFeeRateNumerator = _feeRateNumerator; amountfeeRateDenominator = _feeRateDenominator; } function setContracSenderFeeRate(uint256 _feeRateNumerator, uint256 _feeRateDenominator) public virtual { checkAdmin(); require( _feeRateDenominator >= _feeRateNumerator, "invalid input" ); contractFeeRateNumerator = _feeRateNumerator; contractFeeRateDenominator = _feeRateDenominator; } function setStartBlock(uint256 _startBlock) public virtual onlyOwner { require(startBlock > block.number, "invalid start block"); startBlock = _startBlock; updateAfterModifyStartBlock(_startBlock); } function transferAdmin(address _admin) public virtual { checkAdmin(); admin = _admin; } function setMarketingFund(address _marketingFund) public virtual onlyOwner { marketingFund = _marketingFund; } function updateAfterModifyStartBlock(uint256 _newStartBlock) internal virtual{ } function calculateDividend(uint256 _pending, uint256 _pid, uint256 _userAmount, bool _isContractSender) internal view returns (uint256 _marketingFundDividend, uint256 _devDividend, uint256 _userDividend){ uint256 fee = 0; if(_isContractSender && contractFeeRateDenominator > 0){ fee = _pending.mul(contractFeeRateNumerator).div(contractFeeRateDenominator); _marketingFundDividend = _marketingFundDividend.add(fee); _pending = _pending.sub(fee); } if(poolTokenAmountLimit[_pid] > 0 && amountfeeRateDenominator > 0 && _userAmount >= poolTokenAmountLimit[_pid]){ fee = _pending.mul(amountFeeRateNumerator).div(amountfeeRateDenominator); _marketingFundDividend =_marketingFundDividend.add(fee); _pending = _pending.sub(fee); } if(devDividendWeight > 0){ fee = _pending.mul(devDividendWeight).div(devDividendWeight.add(userDividendWeight)); _devDividend = _devDividend.add(fee); _pending = _pending.sub(fee); } _userDividend = _pending; } function judgeContractSender(uint256 _pid) internal { if(msg.sender != tx.origin){ isUserContractSender[_pid][msg.sender] = true; } } function checkAdmin() internal view { require(admin == msg.sender, "invalid authorized"); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity >=0.6.0 <0.8.0; // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/SHDToken.sol pragma solidity 0.6.12; // SHDToken with Governance. contract SHDToken is ERC20("ShardingDAO", "SHD"), Ownable { // cross chain mapping(address => bool) public minters; struct Checkpoint { uint256 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; event VotesBalanceChanged( address indexed user, uint256 previousBalance, uint256 newBalance ); /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public { require(minters[msg.sender] == true, "SHD : You are not the miner"); _mint(_to, _amount); } function burn(uint256 _amount) public { _burn(msg.sender, _amount); } function addMiner(address _miner) external onlyOwner { minters[_miner] = true; } function removeMiner(address _miner) external onlyOwner { minters[_miner] = false; } function getPriorVotes(address account, uint256 blockNumber) public view returns (uint256) { require( blockNumber < block.number, "getPriorVotes: not yet determined" ); uint256 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; } uint256 lower = 0; uint256 upper = nCheckpoints - 1; while (upper > lower) { uint256 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 _voteTransfer( address from, address to, uint256 amount ) internal { if (from != to && amount > 0) { if (from != address(0)) { uint256 fromNum = numCheckpoints[from]; uint256 fromOld = fromNum > 0 ? checkpoints[from][fromNum - 1].votes : 0; uint256 fromNew = fromOld.sub(amount); _writeCheckpoint(from, fromNum, fromOld, fromNew); } if (to != address(0)) { uint256 toNum = numCheckpoints[to]; uint256 toOld = toNum > 0 ? checkpoints[to][toNum - 1].votes : 0; uint256 toNew = toOld.add(amount); _writeCheckpoint(to, toNum, toOld, toNew); } } } function _writeCheckpoint( address user, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint256 blockNumber = block.number; if ( nCheckpoints > 0 && checkpoints[user][nCheckpoints - 1].fromBlock == blockNumber ) { checkpoints[user][nCheckpoints - 1].votes = newVotes; } else { checkpoints[user][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[user] = nCheckpoints + 1; } emit VotesBalanceChanged(user, oldVotes, newVotes); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { _voteTransfer(from, to, amount); } } // File: contracts/ShardingDAOMining.sol pragma solidity 0.6.12; contract ShardingDAOMining is IInvitation, ActivityBase { using SafeMath for uint256; using SafeERC20 for IERC20; using FixedPoint for *; // Info of each user. struct UserInfo { uint256 amount; // How much LP token the user has provided. uint256 originWeight; //initial weight uint256 inviteeWeight; // invitees' weight uint256 endBlock; bool isCalculateInvitation; } // Info of each pool. struct PoolInfo { uint256 nftPoolId; address lpTokenSwap; // uniswapPair contract address uint256 accumulativeDividend; uint256 usersTotalWeight; // user's sum weight uint256 lpTokenAmount; // lock amount uint256 oracleWeight; // eth value uint256 lastDividendHeight; // last dividend block height TokenPairInfo tokenToEthPairInfo; bool isFirstTokenShard; } struct TokenPairInfo{ IUniswapV2Pair tokenToEthSwap; FixedPoint.uq112x112 price; bool isFirstTokenEth; uint256 priceCumulativeLast; uint32 blockTimestampLast; uint256 lastPriceUpdateHeight; } struct InvitationInfo { address invitor; address[] invitees; bool isUsed; bool isWithdrawn; mapping(address => uint256) inviteeIndexMap; } // black list struct EvilPoolInfo { uint256 pid; string description; } // The SHD TOKEN! SHDToken public SHD; // Info of each pool. uint256[] public rankPoolIndex; // indicates whether the pool is in the rank mapping(uint256 => uint256) public rankPoolIndexMap; // relationship info about invitation mapping(address => InvitationInfo) public usersRelationshipInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Info of each pool. PoolInfo[] private poolInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public maxRankNumber = 10; // Last block number that SHARDs distribution occurs. uint256 public lastRewardBlock; // produced blocks per day uint256 public constant produceBlocksPerDay = 6496; // produced blocks per month uint256 public constant produceBlocksPerMonth = produceBlocksPerDay * 30; // SHD tokens created per block. uint256 public SHDPerBlock = 104994 * (1e13); // after each term, mine half SHD token uint256 public constant MINT_DECREASE_TERM = 9500000; // used to caculate user deposit weight uint256[] private depositTimeWeight; // max lock time in stage two uint256 private constant MAX_MONTH = 36; // add pool automatically in nft shard address public nftShard; // oracle token price update term uint256 public updateTokenPriceTerm = 120; // to mint token cross chain uint256 public shardMintWeight = 1; uint256 public reserveMintWeight = 0; uint256 public reserveToMint; // black list EvilPoolInfo[] public blackList; mapping(uint256 => uint256) public blackListMap; // undividend shard uint256 public unDividendShard; // 20% shard => SHD - ETH pool uint256 public shardPoolDividendWeight = 2; // 80% shard => SHD - ETH pool uint256 public otherPoolDividendWeight = 8; event Deposit( address indexed user, uint256 indexed pid, uint256 amount, uint256 weight ); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event Replace( address indexed user, uint256 indexed rankIndex, uint256 newPid ); event AddToBlacklist( uint256 indexed pid ); event RemoveFromBlacklist( uint256 indexed pid ); event AddPool(uint256 indexed pid, uint256 nftId, address tokenAddress); function initialize( SHDToken _SHD, address _wethToken, address _developerDAOFund, address _marketingFund, uint256 _maxRankNumber, uint256 _startBlock ) public virtual onlyOwner{ require(WETHToken == address(0), "already initialized"); SHD = _SHD; maxRankNumber = _maxRankNumber; if (_startBlock < block.number) { startBlock = block.number; } else { startBlock = _startBlock; } lastRewardBlock = startBlock.sub(1); WETHToken = _wethToken; initializeTimeWeight(); developerDAOFund = _developerDAOFund; marketingFund = _marketingFund; InvitationInfo storage initialInvitor = usersRelationshipInfo[address(this)]; userDividendWeight = 8; devDividendWeight = 2; amountFeeRateNumerator = 0; amountfeeRateDenominator = 0; contractFeeRateNumerator = 1; contractFeeRateDenominator = 5; initialInvitor.isUsed = true; } function initializeTimeWeight() private { depositTimeWeight = [ 1238, 1383, 1495, 1587, 1665, 1732, 1790, 1842, 1888, 1929, 1966, 2000, 2031, 2059, 2085, 2108, 2131, 2152, 2171, 2189, 2206, 2221, 2236, 2250, 2263, 2276, 2287, 2298, 2309, 2319, 2328, 2337, 2346, 2355, 2363, 2370 ]; } function setNftShard(address _nftShard) public virtual { checkAdmin(); nftShard = _nftShard; } // Add a new lp to the pool. Can only be called by the nft shard contract. // if _lpTokenSwap contains tokenA instead of eth, then _tokenToEthSwap should consist of token A and eth function add( uint256 _nftPoolId, IUniswapV2Pair _lpTokenSwap, IUniswapV2Pair _tokenToEthSwap ) public virtual { require(msg.sender == nftShard || msg.sender == admin, "invalid sender"); TokenPairInfo memory tokenToEthInfo; uint256 lastDividendHeight = 0; if(poolInfo.length == 0){ _nftPoolId = 0; lastDividendHeight = lastRewardBlock; } bool isFirstTokenShard; if (address(_tokenToEthSwap) != address(0)) { (address token0, address token1, uint256 targetTokenPosition) = getTargetTokenInSwap(_tokenToEthSwap, WETHToken); address wantToken; bool isFirstTokenEthToken; if (targetTokenPosition == 0) { isFirstTokenEthToken = true; wantToken = token1; } else { isFirstTokenEthToken = false; wantToken = token0; } (, , targetTokenPosition) = getTargetTokenInSwap( _lpTokenSwap, wantToken ); if (targetTokenPosition == 0) { isFirstTokenShard = false; } else { isFirstTokenShard = true; } tokenToEthInfo = generateOrcaleInfo( _tokenToEthSwap, isFirstTokenEthToken ); } else { (, , uint256 targetTokenPosition) = getTargetTokenInSwap(_lpTokenSwap, WETHToken); if (targetTokenPosition == 0) { isFirstTokenShard = false; } else { isFirstTokenShard = true; } tokenToEthInfo = generateOrcaleInfo( _lpTokenSwap, !isFirstTokenShard ); } poolInfo.push( PoolInfo({ nftPoolId: _nftPoolId, lpTokenSwap: address(_lpTokenSwap), lpTokenAmount: 0, usersTotalWeight: 0, accumulativeDividend: 0, oracleWeight: 0, lastDividendHeight: lastDividendHeight, tokenToEthPairInfo: tokenToEthInfo, isFirstTokenShard: isFirstTokenShard }) ); emit AddPool(poolInfo.length.sub(1), _nftPoolId, address(_lpTokenSwap)); } function setPriceUpdateTerm(uint256 _term) public virtual onlyOwner{ updateTokenPriceTerm = _term; } function kickEvilPoolByPid(uint256 _pid, string calldata description) public virtual onlyOwner { bool isDescriptionLeagal = verifyDescription(description); require(isDescriptionLeagal, "invalid description, just ASCII code is allowed"); require(_pid > 0, "invalid pid"); uint256 poolRankIndex = rankPoolIndexMap[_pid]; if (poolRankIndex > 0) { massUpdatePools(); uint256 _rankIndex = poolRankIndex.sub(1); uint256 currentRankLastIndex = rankPoolIndex.length.sub(1); uint256 lastPidInRank = rankPoolIndex[currentRankLastIndex]; rankPoolIndex[_rankIndex] = lastPidInRank; rankPoolIndexMap[lastPidInRank] = poolRankIndex; delete rankPoolIndexMap[_pid]; rankPoolIndex.pop(); } addInBlackList(_pid, description); dealEvilPoolDiviend(_pid); emit AddToBlacklist(_pid); } function addInBlackList(uint256 _pid, string calldata description) private { if (blackListMap[_pid] > 0) { return; } blackList.push(EvilPoolInfo({pid: _pid, description: description})); blackListMap[_pid] = blackList.length; } function resetEvilPool(uint256 _pid) public virtual onlyOwner { uint256 poolPosition = blackListMap[_pid]; if (poolPosition == 0) { return; } uint256 poolIndex = poolPosition.sub(1); uint256 lastIndex = blackList.length.sub(1); EvilPoolInfo storage lastEvilInBlackList = blackList[lastIndex]; uint256 lastPidInBlackList = lastEvilInBlackList.pid; blackListMap[lastPidInBlackList] = poolPosition; blackList[poolIndex] = blackList[lastIndex]; delete blackListMap[_pid]; blackList.pop(); emit RemoveFromBlacklist(_pid); } function dealEvilPoolDiviend(uint256 _pid) private { PoolInfo storage pool = poolInfo[_pid]; uint256 undistributeDividend = pool.accumulativeDividend; if (undistributeDividend == 0) { return; } uint256 currentRankCount = rankPoolIndex.length; if (currentRankCount > 0) { uint256 averageDividend = undistributeDividend.div(currentRankCount); for (uint256 i = 0; i < currentRankCount; i++) { PoolInfo storage poolInRank = poolInfo[rankPoolIndex[i]]; if (i < currentRankCount - 1) { poolInRank.accumulativeDividend = poolInRank .accumulativeDividend .add(averageDividend); undistributeDividend = undistributeDividend.sub( averageDividend ); } else { poolInRank.accumulativeDividend = poolInRank .accumulativeDividend .add(undistributeDividend); } } } else { unDividendShard = unDividendShard.add(undistributeDividend); } pool.accumulativeDividend = 0; } function setMintCoefficient( uint256 _shardMintWeight, uint256 _reserveMintWeight ) public virtual { checkAdmin(); require( _shardMintWeight != 0 && _reserveMintWeight != 0, "invalid input" ); massUpdatePools(); shardMintWeight = _shardMintWeight; reserveMintWeight = _reserveMintWeight; } function setShardPoolDividendWeight( uint256 _shardPoolWeight, uint256 _otherPoolWeight ) public virtual { checkAdmin(); require( _shardPoolWeight != 0 && _otherPoolWeight != 0, "invalid input" ); massUpdatePools(); shardPoolDividendWeight = _shardPoolWeight; otherPoolDividendWeight = _otherPoolWeight; } function setSHDPerBlock(uint256 _SHDPerBlock, bool _withUpdate) public virtual { checkAdmin(); if (_withUpdate) { massUpdatePools(); } SHDPerBlock = _SHDPerBlock; } function massUpdatePools() public virtual { uint256 poolCountInRank = rankPoolIndex.length; uint256 farmMintShard = mintSHARD(address(this), block.number); updateSHARDPoolAccumulativeDividend(block.number); if(poolCountInRank == 0){ farmMintShard = farmMintShard.mul(otherPoolDividendWeight) .div(shardPoolDividendWeight.add(otherPoolDividendWeight)); if(farmMintShard > 0){ unDividendShard = unDividendShard.add(farmMintShard); } } for (uint256 i = 0; i < poolCountInRank; i++) { updatePoolAccumulativeDividend( rankPoolIndex[i], poolCountInRank, block.number ); } } // update reward vairables for a pool function updatePoolDividend(uint256 _pid) public virtual { if(_pid == 0){ updateSHARDPoolAccumulativeDividend(block.number); return; } if (rankPoolIndexMap[_pid] == 0) { return; } updatePoolAccumulativeDividend( _pid, rankPoolIndex.length, block.number ); } function mintSHARD(address _address, uint256 _toBlock) private returns (uint256){ uint256 recentlyRewardBlock = lastRewardBlock; if (recentlyRewardBlock >= _toBlock) { return 0; } uint256 totalReward = getRewardToken(recentlyRewardBlock.add(1), _toBlock); uint256 farmMint = totalReward.mul(shardMintWeight).div( reserveMintWeight.add(shardMintWeight) ); uint256 reserve = totalReward.sub(farmMint); if (totalReward > 0) { SHD.mint(_address, farmMint); if (reserve > 0) { reserveToMint = reserveToMint.add(reserve); } lastRewardBlock = _toBlock; } return farmMint; } function updatePoolAccumulativeDividend( uint256 _pid, uint256 _validRankPoolCount, uint256 _toBlock ) private { PoolInfo storage pool = poolInfo[_pid]; if (pool.lastDividendHeight >= _toBlock) return; uint256 poolReward = getModifiedRewardToken(pool.lastDividendHeight.add(1), _toBlock) .mul(otherPoolDividendWeight) .div(shardPoolDividendWeight.add(otherPoolDividendWeight)); uint256 otherPoolReward = poolReward.div(_validRankPoolCount); pool.lastDividendHeight = _toBlock; uint256 existedDividend = pool.accumulativeDividend; pool.accumulativeDividend = existedDividend.add(otherPoolReward); } function updateSHARDPoolAccumulativeDividend (uint256 _toBlock) private{ PoolInfo storage pool = poolInfo[0]; if (pool.lastDividendHeight >= _toBlock) return; uint256 poolReward = getModifiedRewardToken(pool.lastDividendHeight.add(1), _toBlock); uint256 shardPoolDividend = poolReward.mul(shardPoolDividendWeight) .div(shardPoolDividendWeight.add(otherPoolDividendWeight)); pool.lastDividendHeight = _toBlock; uint256 existedDividend = pool.accumulativeDividend; pool.accumulativeDividend = existedDividend.add(shardPoolDividend); } // deposit LP tokens to MasterChef for SHD allocation. // ignore lockTime in stage one function deposit( uint256 _pid, uint256 _amount, uint256 _lockTime ) public virtual { require(_amount > 0, "invalid deposit amount"); InvitationInfo storage senderInfo = usersRelationshipInfo[msg.sender]; require(senderInfo.isUsed, "must accept an invitation firstly"); require(_lockTime > 0 && _lockTime <= 36, "invalid lock time"); // less than 36 months PoolInfo storage pool = poolInfo[_pid]; uint256 lpTokenAmount = pool.lpTokenAmount.add(_amount); UserInfo storage user = userInfo[_pid][msg.sender]; uint256 newOriginWeight = user.originWeight; uint256 existedAmount = user.amount; uint256 endBlock = user.endBlock; uint256 newEndBlock = block.number.add(produceBlocksPerMonth.mul(_lockTime)); if (existedAmount > 0) { if (block.number >= endBlock) { newOriginWeight = getDepositWeight( _amount.add(existedAmount), _lockTime ); } else { newOriginWeight = newOriginWeight.add(getDepositWeight(_amount, _lockTime)); newOriginWeight = newOriginWeight.add( getDepositWeight( existedAmount, newEndBlock.sub(endBlock).div(produceBlocksPerMonth) ) ); } } else { judgeContractSender(_pid); newOriginWeight = getDepositWeight(_amount, _lockTime); } modifyWeightByInvitation( _pid, msg.sender, user.originWeight, newOriginWeight, user.inviteeWeight, existedAmount ); updateUserInfo( user, existedAmount.add(_amount), newOriginWeight, newEndBlock ); IERC20(pool.lpTokenSwap).safeTransferFrom( address(msg.sender), address(this), _amount ); pool.oracleWeight = getOracleWeight(pool, lpTokenAmount); pool.lpTokenAmount = lpTokenAmount; if ( rankPoolIndexMap[_pid] == 0 && rankPoolIndex.length < maxRankNumber && blackListMap[_pid] == 0 ) { addToRank(pool, _pid); } emit Deposit(msg.sender, _pid, _amount, newOriginWeight); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid) public virtual { UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; require(amount > 0, "user is not existed"); require(user.endBlock < block.number, "token is still locked"); mintSHARD(address(this), block.number); updatePoolDividend(_pid); uint256 originWeight = user.originWeight; PoolInfo storage pool = poolInfo[_pid]; uint256 usersTotalWeight = pool.usersTotalWeight; uint256 userWeight = user.inviteeWeight.add(originWeight); if(user.isCalculateInvitation){ userWeight = userWeight.add(originWeight.div(INVITOR_WEIGHT)); } if (pool.accumulativeDividend > 0) { uint256 pending = pool.accumulativeDividend.mul(userWeight).div(usersTotalWeight); pool.accumulativeDividend = pool.accumulativeDividend.sub(pending); uint256 treasruyDividend; uint256 devDividend; (treasruyDividend, devDividend, pending) = calculateDividend(pending, _pid, amount, isUserContractSender[_pid][msg.sender]); if(treasruyDividend > 0){ safeSHARDTransfer(marketingFund, treasruyDividend); } if(devDividend > 0){ safeSHARDTransfer(developerDAOFund, devDividend); } if(pending > 0){ safeSHARDTransfer(msg.sender, pending); } } pool.usersTotalWeight = usersTotalWeight.sub(userWeight); user.amount = 0; user.originWeight = 0; user.endBlock = 0; IERC20(pool.lpTokenSwap).safeTransfer(address(msg.sender), amount); pool.lpTokenAmount = pool.lpTokenAmount.sub(amount); if (pool.lpTokenAmount == 0) pool.oracleWeight = 0; else { pool.oracleWeight = getOracleWeight(pool, pool.lpTokenAmount); } resetInvitationRelationship(_pid, msg.sender, originWeight); emit Withdraw(msg.sender, _pid, amount); } function addToRank( PoolInfo storage _pool, uint256 _pid ) private { if(_pid == 0){ return; } massUpdatePools(); _pool.lastDividendHeight = block.number; rankPoolIndex.push(_pid); rankPoolIndexMap[_pid] = rankPoolIndex.length; if(unDividendShard > 0){ _pool.accumulativeDividend = _pool.accumulativeDividend.add(unDividendShard); unDividendShard = 0; } emit Replace(msg.sender, rankPoolIndex.length.sub(1), _pid); return; } //_poolIndexInRank is the index in rank //_pid is the index in poolInfo function tryToReplacePoolInRank(uint256 _poolIndexInRank, uint256 _pid) public virtual { if(_pid == 0){ return; } PoolInfo storage pool = poolInfo[_pid]; require(pool.lpTokenAmount > 0, "there is not any lp token depsoited"); require(blackListMap[_pid] == 0, "pool is in the black list"); if (rankPoolIndexMap[_pid] > 0) { return; } uint256 currentPoolCountInRank = rankPoolIndex.length; require(currentPoolCountInRank == maxRankNumber, "invalid operation"); uint256 targetPid = rankPoolIndex[_poolIndexInRank]; PoolInfo storage targetPool = poolInfo[targetPid]; uint256 targetPoolOracleWeight = getOracleWeight(targetPool, targetPool.lpTokenAmount); uint256 challengerOracleWeight = getOracleWeight(pool, pool.lpTokenAmount); if (challengerOracleWeight <= targetPoolOracleWeight) { return; } updatePoolDividend(targetPid); rankPoolIndex[_poolIndexInRank] = _pid; delete rankPoolIndexMap[targetPid]; rankPoolIndexMap[_pid] = _poolIndexInRank.add(1); pool.lastDividendHeight = block.number; emit Replace(msg.sender, _poolIndexInRank, _pid); } function acceptInvitation(address _invitor) public virtual override { require(_invitor != msg.sender, "invitee should not be invitor"); buildInvitation(_invitor, msg.sender); } function buildInvitation(address _invitor, address _invitee) private { InvitationInfo storage invitee = usersRelationshipInfo[_invitee]; require(!invitee.isUsed, "has accepted invitation"); invitee.isUsed = true; InvitationInfo storage invitor = usersRelationshipInfo[_invitor]; require(invitor.isUsed, "invitor has not acceptted invitation"); invitee.invitor = _invitor; invitor.invitees.push(_invitee); invitor.inviteeIndexMap[_invitee] = invitor.invitees.length.sub(1); } function setMaxRankNumber(uint256 _count) public virtual { checkAdmin(); require(_count > 0, "invalid count"); if (maxRankNumber == _count) return; massUpdatePools(); maxRankNumber = _count; uint256 currentPoolCountInRank = rankPoolIndex.length; if (_count >= currentPoolCountInRank) { return; } uint256 sparePoolCount = currentPoolCountInRank.sub(_count); uint256 lastPoolIndex = currentPoolCountInRank.sub(1); while (sparePoolCount > 0) { delete rankPoolIndexMap[rankPoolIndex[lastPoolIndex]]; rankPoolIndex.pop(); lastPoolIndex--; sparePoolCount--; } } function getModifiedRewardToken(uint256 _fromBlock, uint256 _toBlock) private view returns (uint256) { return getRewardToken(_fromBlock, _toBlock).mul(shardMintWeight).div( reserveMintWeight.add(shardMintWeight) ); } // View function to see pending SHARDs on frontend. function pendingSHARD(uint256 _pid, address _user) external view virtual returns (uint256 _pending, uint256 _potential, uint256 _blockNumber) { _blockNumber = block.number; (_pending, _potential) = calculatePendingSHARD(_pid, _user); } function pendingSHARDByPids(uint256[] memory _pids, address _user) external view virtual returns (uint256[] memory _pending, uint256[] memory _potential, uint256 _blockNumber) { uint256 poolCount = _pids.length; _pending = new uint256[](poolCount); _potential = new uint256[](poolCount); _blockNumber = block.number; for(uint i = 0; i < poolCount; i ++){ (_pending[i], _potential[i]) = calculatePendingSHARD(_pids[i], _user); } } function calculatePendingSHARD(uint256 _pid, address _user) private view returns (uint256 _pending, uint256 _potential){ PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; if (user.amount == 0) { return (0, 0); } uint256 userModifiedWeight = getUserModifiedWeight(_pid, _user); _pending = pool.accumulativeDividend.mul(userModifiedWeight); _pending = _pending.div(pool.usersTotalWeight); bool isContractSender = isUserContractSender[_pid][_user]; (,,_pending) = calculateDividend(_pending, _pid, user.amount, isContractSender); if (pool.lastDividendHeight >= block.number) { return (_pending, 0); } if (_pid != 0 && (rankPoolIndex.length == 0 || rankPoolIndexMap[_pid] == 0)) { return (_pending, 0); } uint256 poolReward = getModifiedRewardToken(pool.lastDividendHeight.add(1), block.number); uint256 numerator; uint256 denominator = otherPoolDividendWeight.add(shardPoolDividendWeight); if(_pid == 0){ numerator = shardPoolDividendWeight; } else{ numerator = otherPoolDividendWeight; } poolReward = poolReward .mul(numerator) .div(denominator); if(_pid != 0){ poolReward = poolReward.div(rankPoolIndex.length); } _potential = poolReward .mul(userModifiedWeight) .div(pool.usersTotalWeight); (,,_potential) = calculateDividend(_potential, _pid, user.amount, isContractSender); } //calculate the weight and end block when users deposit function getDepositWeight(uint256 _lockAmount, uint256 _lockTime) private view returns (uint256) { if (_lockTime == 0) return 0; if (_lockTime.div(MAX_MONTH) > 1) _lockTime = MAX_MONTH; return depositTimeWeight[_lockTime.sub(1)].sub(500).mul(_lockAmount); } function getPoolLength() public view virtual returns (uint256) { return poolInfo.length; } function getPagePoolInfo(uint256 _fromIndex, uint256 _toIndex) public view virtual returns ( uint256[] memory _nftPoolId, uint256[] memory _accumulativeDividend, uint256[] memory _usersTotalWeight, uint256[] memory _lpTokenAmount, uint256[] memory _oracleWeight, address[] memory _swapAddress ) { uint256 poolCount = _toIndex.sub(_fromIndex).add(1); _nftPoolId = new uint256[](poolCount); _accumulativeDividend = new uint256[](poolCount); _usersTotalWeight = new uint256[](poolCount); _lpTokenAmount = new uint256[](poolCount); _oracleWeight = new uint256[](poolCount); _swapAddress = new address[](poolCount); uint256 startIndex = 0; for (uint256 i = _fromIndex; i <= _toIndex; i++) { PoolInfo storage pool = poolInfo[i]; _nftPoolId[startIndex] = pool.nftPoolId; _accumulativeDividend[startIndex] = pool.accumulativeDividend; _usersTotalWeight[startIndex] = pool.usersTotalWeight; _lpTokenAmount[startIndex] = pool.lpTokenAmount; _oracleWeight[startIndex] = pool.oracleWeight; _swapAddress[startIndex] = pool.lpTokenSwap; startIndex++; } } function getInstantPagePoolInfo(uint256 _fromIndex, uint256 _toIndex) public virtual returns ( uint256[] memory _nftPoolId, uint256[] memory _accumulativeDividend, uint256[] memory _usersTotalWeight, uint256[] memory _lpTokenAmount, uint256[] memory _oracleWeight, address[] memory _swapAddress ) { uint256 poolCount = _toIndex.sub(_fromIndex).add(1); _nftPoolId = new uint256[](poolCount); _accumulativeDividend = new uint256[](poolCount); _usersTotalWeight = new uint256[](poolCount); _lpTokenAmount = new uint256[](poolCount); _oracleWeight = new uint256[](poolCount); _swapAddress = new address[](poolCount); uint256 startIndex = 0; for (uint256 i = _fromIndex; i <= _toIndex; i++) { PoolInfo storage pool = poolInfo[i]; _nftPoolId[startIndex] = pool.nftPoolId; _accumulativeDividend[startIndex] = pool.accumulativeDividend; _usersTotalWeight[startIndex] = pool.usersTotalWeight; _lpTokenAmount[startIndex] = pool.lpTokenAmount; _oracleWeight[startIndex] = getOracleWeight(pool, _lpTokenAmount[startIndex]); _swapAddress[startIndex] = pool.lpTokenSwap; startIndex++; } } function getRankList() public view virtual returns (uint256[] memory) { uint256[] memory rankIdList = rankPoolIndex; return rankIdList; } function getBlackList() public view virtual returns (EvilPoolInfo[] memory _blackList) { _blackList = blackList; } function getInvitation(address _sender) public view virtual override returns ( address _invitor, address[] memory _invitees, bool _isWithdrawn ) { InvitationInfo storage invitation = usersRelationshipInfo[_sender]; _invitees = invitation.invitees; _invitor = invitation.invitor; _isWithdrawn = invitation.isWithdrawn; } function getUserInfo(uint256 _pid, address _user) public view virtual returns ( uint256 _amount, uint256 _originWeight, uint256 _modifiedWeight, uint256 _endBlock ) { UserInfo storage user = userInfo[_pid][_user]; _amount = user.amount; _originWeight = user.originWeight; _modifiedWeight = getUserModifiedWeight(_pid, _user); _endBlock = user.endBlock; } function getUserInfoByPids(uint256[] memory _pids, address _user) public view virtual returns ( uint256[] memory _amount, uint256[] memory _originWeight, uint256[] memory _modifiedWeight, uint256[] memory _endBlock ) { uint256 poolCount = _pids.length; _amount = new uint256[](poolCount); _originWeight = new uint256[](poolCount); _modifiedWeight = new uint256[](poolCount); _endBlock = new uint256[](poolCount); for(uint i = 0; i < poolCount; i ++){ (_amount[i], _originWeight[i], _modifiedWeight[i], _endBlock[i]) = getUserInfo(_pids[i], _user); } } function getOracleInfo(uint256 _pid) public view virtual returns ( address _swapToEthAddress, uint256 _priceCumulativeLast, uint256 _blockTimestampLast, uint256 _price, uint256 _lastPriceUpdateHeight ) { PoolInfo storage pool = poolInfo[_pid]; _swapToEthAddress = address(pool.tokenToEthPairInfo.tokenToEthSwap); _priceCumulativeLast = pool.tokenToEthPairInfo.priceCumulativeLast; _blockTimestampLast = pool.tokenToEthPairInfo.blockTimestampLast; _price = pool.tokenToEthPairInfo.price._x; _lastPriceUpdateHeight = pool.tokenToEthPairInfo.lastPriceUpdateHeight; } // Safe SHD transfer function, just in case if rounding error causes pool to not have enough SHARDs. function safeSHARDTransfer(address _to, uint256 _amount) internal { uint256 SHARDBal = SHD.balanceOf(address(this)); if (_amount > SHARDBal) { SHD.transfer(_to, SHARDBal); } else { SHD.transfer(_to, _amount); } } function updateUserInfo( UserInfo storage _user, uint256 _amount, uint256 _originWeight, uint256 _endBlock ) private { _user.amount = _amount; _user.originWeight = _originWeight; _user.endBlock = _endBlock; } function getOracleWeight( PoolInfo storage _pool, uint256 _amount ) private returns (uint256 _oracleWeight) { _oracleWeight = calculateOracleWeight(_pool, _amount); _pool.oracleWeight = _oracleWeight; } function calculateOracleWeight(PoolInfo storage _pool, uint256 _amount) private returns (uint256 _oracleWeight) { uint256 lpTokenTotalSupply = IUniswapV2Pair(_pool.lpTokenSwap).totalSupply(); (uint112 shardReserve, uint112 wantTokenReserve, ) = IUniswapV2Pair(_pool.lpTokenSwap).getReserves(); if (_amount == 0) { _amount = _pool.lpTokenAmount; if (_amount == 0) { return 0; } } if (!_pool.isFirstTokenShard) { uint112 wantToken = wantTokenReserve; wantTokenReserve = shardReserve; shardReserve = wantToken; } FixedPoint.uq112x112 memory price = updateTokenOracle(_pool.tokenToEthPairInfo); if ( address(_pool.tokenToEthPairInfo.tokenToEthSwap) == _pool.lpTokenSwap ) { _oracleWeight = uint256(price.mul(shardReserve).decode144()) .mul(2) .mul(_amount) .div(lpTokenTotalSupply); } else { _oracleWeight = uint256(price.mul(wantTokenReserve).decode144()) .mul(2) .mul(_amount) .div(lpTokenTotalSupply); } } function resetInvitationRelationship( uint256 _pid, address _user, uint256 _originWeight ) private { InvitationInfo storage senderRelationshipInfo = usersRelationshipInfo[_user]; if (!senderRelationshipInfo.isWithdrawn){ senderRelationshipInfo.isWithdrawn = true; InvitationInfo storage invitorRelationshipInfo = usersRelationshipInfo[senderRelationshipInfo.invitor]; uint256 targetIndex = invitorRelationshipInfo.inviteeIndexMap[_user]; uint256 inviteesCount = invitorRelationshipInfo.invitees.length; address lastInvitee = invitorRelationshipInfo.invitees[inviteesCount.sub(1)]; invitorRelationshipInfo.inviteeIndexMap[lastInvitee] = targetIndex; invitorRelationshipInfo.invitees[targetIndex] = lastInvitee; delete invitorRelationshipInfo.inviteeIndexMap[_user]; invitorRelationshipInfo.invitees.pop(); } UserInfo storage invitorInfo = userInfo[_pid][senderRelationshipInfo.invitor]; UserInfo storage user = userInfo[_pid][_user]; if(!user.isCalculateInvitation){ return; } user.isCalculateInvitation = false; uint256 inviteeToSubWeight = _originWeight.div(INVITEE_WEIGHT); invitorInfo.inviteeWeight = invitorInfo.inviteeWeight.sub(inviteeToSubWeight); if (invitorInfo.amount == 0){ return; } PoolInfo storage pool = poolInfo[_pid]; pool.usersTotalWeight = pool.usersTotalWeight.sub(inviteeToSubWeight); } function modifyWeightByInvitation( uint256 _pid, address _user, uint256 _oldOriginWeight, uint256 _newOriginWeight, uint256 _inviteeWeight, uint256 _existedAmount ) private{ PoolInfo storage pool = poolInfo[_pid]; InvitationInfo storage senderInfo = usersRelationshipInfo[_user]; uint256 poolTotalWeight = pool.usersTotalWeight; poolTotalWeight = poolTotalWeight.sub(_oldOriginWeight).add(_newOriginWeight); if(_existedAmount == 0){ poolTotalWeight = poolTotalWeight.add(_inviteeWeight); } UserInfo storage user = userInfo[_pid][_user]; if (!senderInfo.isWithdrawn || (_existedAmount > 0 && user.isCalculateInvitation)) { UserInfo storage invitorInfo = userInfo[_pid][senderInfo.invitor]; user.isCalculateInvitation = true; uint256 addInviteeWeight = _newOriginWeight.div(INVITEE_WEIGHT).sub( _oldOriginWeight.div(INVITEE_WEIGHT) ); invitorInfo.inviteeWeight = invitorInfo.inviteeWeight.add( addInviteeWeight ); uint256 addInvitorWeight = _newOriginWeight.div(INVITOR_WEIGHT).sub( _oldOriginWeight.div(INVITOR_WEIGHT) ); poolTotalWeight = poolTotalWeight.add(addInvitorWeight); if (invitorInfo.amount > 0) { poolTotalWeight = poolTotalWeight.add(addInviteeWeight); } } pool.usersTotalWeight = poolTotalWeight; } function verifyDescription(string memory description) internal pure returns (bool success) { bytes memory nameBytes = bytes(description); uint256 nameLength = nameBytes.length; require(nameLength > 0, "INVALID INPUT"); success = true; bool n7; for (uint256 i = 0; i <= nameLength - 1; i++) { n7 = (nameBytes[i] & 0x80) == 0x80 ? true : false; if (n7) { success = false; break; } } } function getUserModifiedWeight(uint256 _pid, address _user) private view returns (uint256){ UserInfo storage user = userInfo[_pid][_user]; uint256 originWeight = user.originWeight; uint256 modifiedWeight = originWeight.add(user.inviteeWeight); if(user.isCalculateInvitation){ modifiedWeight = modifiedWeight.add(originWeight.div(INVITOR_WEIGHT)); } return modifiedWeight; } // get how much token will be mined from _toBlock to _toBlock. function getRewardToken(uint256 _fromBlock, uint256 _toBlock) public view virtual returns (uint256){ return calculateRewardToken(MINT_DECREASE_TERM, SHDPerBlock, startBlock, _fromBlock, _toBlock); } function calculateRewardToken(uint _term, uint256 _initialBlock, uint256 _startBlock, uint256 _fromBlock, uint256 _toBlock) private pure returns (uint256){ if(_fromBlock > _toBlock || _startBlock > _toBlock) return 0; if(_startBlock > _fromBlock) _fromBlock = _startBlock; uint256 totalReward = 0; uint256 blockPeriod = _fromBlock.sub(_startBlock).add(1); uint256 yearPeriod = blockPeriod.div(_term); // produce 5760 blocks per day, 2102400 blocks per year. for (uint256 i = 0; i < yearPeriod; i++){ _initialBlock = _initialBlock.div(2); } uint256 termStartIndex = yearPeriod.add(1).mul(_term).add(_startBlock); uint256 beforeCalculateIndex = _fromBlock.sub(1); while(_toBlock >= termStartIndex && _initialBlock > 0){ totalReward = totalReward.add(termStartIndex.sub(beforeCalculateIndex).mul(_initialBlock)); beforeCalculateIndex = termStartIndex.add(1); _initialBlock = _initialBlock.div(2); termStartIndex = termStartIndex.add(_term); } if(_toBlock > beforeCalculateIndex){ totalReward = totalReward.add(_toBlock.sub(beforeCalculateIndex).mul(_initialBlock)); } return totalReward; } function getTargetTokenInSwap(IUniswapV2Pair _lpTokenSwap, address _targetToken) internal view returns (address, address, uint256){ address token0 = _lpTokenSwap.token0(); address token1 = _lpTokenSwap.token1(); if(token0 == _targetToken){ return(token0, token1, 0); } if(token1 == _targetToken){ return(token0, token1, 1); } require(false, "invalid uniswap"); } function generateOrcaleInfo(IUniswapV2Pair _pairSwap, bool _isFirstTokenEth) internal view returns(TokenPairInfo memory){ uint256 priceTokenCumulativeLast = _isFirstTokenEth? _pairSwap.price1CumulativeLast(): _pairSwap.price0CumulativeLast(); uint112 reserve0; uint112 reserve1; uint32 tokenBlockTimestampLast; (reserve0, reserve1, tokenBlockTimestampLast) = _pairSwap.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'ExampleOracleSimple: NO_RESERVES'); // ensure that there's liquidity in the pair TokenPairInfo memory tokenBInfo = TokenPairInfo({ tokenToEthSwap: _pairSwap, isFirstTokenEth: _isFirstTokenEth, priceCumulativeLast: priceTokenCumulativeLast, blockTimestampLast: tokenBlockTimestampLast, price: FixedPoint.uq112x112(0), lastPriceUpdateHeight: block.number }); return tokenBInfo; } function updateTokenOracle(TokenPairInfo storage _pairInfo) internal returns (FixedPoint.uq112x112 memory _price) { FixedPoint.uq112x112 memory cachedPrice = _pairInfo.price; if(cachedPrice._x > 0 && block.number.sub(_pairInfo.lastPriceUpdateHeight) <= updateTokenPriceTerm){ return cachedPrice; } (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(_pairInfo.tokenToEthSwap)); uint32 timeElapsed = blockTimestamp - _pairInfo.blockTimestampLast; // overflow is desired // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed if(_pairInfo.isFirstTokenEth){ _price = FixedPoint.uq112x112(uint224(price1Cumulative.sub(_pairInfo.priceCumulativeLast).div(timeElapsed))); _pairInfo.priceCumulativeLast = price1Cumulative; } else{ _price = FixedPoint.uq112x112(uint224(price0Cumulative.sub(_pairInfo.priceCumulativeLast).div(timeElapsed))); _pairInfo.priceCumulativeLast = price0Cumulative; } _pairInfo.price = _price; _pairInfo.lastPriceUpdateHeight = block.number; _pairInfo.blockTimestampLast = blockTimestamp; } function updateAfterModifyStartBlock(uint256 _newStartBlock) internal override{ lastRewardBlock = _newStartBlock.sub(1); if(poolInfo.length > 0){ PoolInfo storage shdPool = poolInfo[0]; shdPool.lastDividendHeight = lastRewardBlock; } } } // File: contracts/ShardingDAOMiningDelegator.sol pragma solidity 0.6.12; contract ShardingDAOMiningDelegator is DelegatorInterface, ShardingDAOMining { constructor( SHDToken _SHD, address _wethToken, address _developerDAOFund, address _marketingFund, uint256 _maxRankNumber, uint256 _startBlock, address implementation_, bytes memory becomeImplementationData ) public { delegateTo( implementation_, abi.encodeWithSignature( "initialize(address,address,address,address,uint256,uint256)", _SHD, _wethToken, _developerDAOFund, _marketingFund, _maxRankNumber, _startBlock ) ); admin = msg.sender; _setImplementation(implementation_, false, becomeImplementationData); } function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public override { checkAdmin(); if (allowResign) { delegateToImplementation( abi.encodeWithSignature("_resignImplementation()") ); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation( abi.encodeWithSignature( "_becomeImplementation(bytes)", becomeImplementationData ) ); emit NewImplementation(oldImplementation, implementation); } function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize()) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall( abi.encodeWithSignature("delegateToImplementation(bytes)", data) ); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize()) } } return abi.decode(returnData, (bytes)); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts // */ fallback() external payable { if (msg.value > 0) return; // delegate all other functions to current implementation (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize()) switch success case 0 { revert(free_mem_ptr, returndatasize()) } default { return(free_mem_ptr, returndatasize()) } } } function setNftShard(address _nftShard) public override { delegateToImplementation( abi.encodeWithSignature("setNftShard(address)", _nftShard) ); } function add( uint256 _nftPoolId, IUniswapV2Pair _lpTokenSwap, IUniswapV2Pair _tokenToEthSwap ) public override { delegateToImplementation( abi.encodeWithSignature( "add(uint256,address,address)", _nftPoolId, _lpTokenSwap, _tokenToEthSwap ) ); } function setPriceUpdateTerm(uint256 _term) public override { delegateToImplementation( abi.encodeWithSignature( "setPriceUpdateTerm(uint256)", _term ) ); } function kickEvilPoolByPid(uint256 _pid, string calldata description) public override { delegateToImplementation( abi.encodeWithSignature( "kickEvilPoolByPid(uint256,string)", _pid, description ) ); } function resetEvilPool(uint256 _pid) public override { delegateToImplementation( abi.encodeWithSignature( "resetEvilPool(uint256)", _pid ) ); } function setMintCoefficient( uint256 _nftMintWeight, uint256 _reserveMintWeight ) public override { delegateToImplementation( abi.encodeWithSignature( "setMintCoefficient(uint256,uint256)", _nftMintWeight, _reserveMintWeight ) ); } function setShardPoolDividendWeight( uint256 _shardPoolWeight, uint256 _otherPoolWeight ) public override { delegateToImplementation( abi.encodeWithSignature( "setShardPoolDividendWeight(uint256,uint256)", _shardPoolWeight, _otherPoolWeight ) ); } function setStartBlock( uint256 _startBlock ) public override { delegateToImplementation( abi.encodeWithSignature( "setStartBlock(uint256)", _startBlock ) ); } function setSHDPerBlock(uint256 _shardPerBlock, bool _withUpdate) public override { delegateToImplementation( abi.encodeWithSignature( "setSHDPerBlock(uint256,bool)", _shardPerBlock, _withUpdate ) ); } function massUpdatePools() public override { delegateToImplementation(abi.encodeWithSignature("massUpdatePools()")); } function updatePoolDividend(uint256 _pid) public override { delegateToImplementation( abi.encodeWithSignature("updatePoolDividend(uint256)", _pid) ); } function deposit( uint256 _pid, uint256 _amount, uint256 _lockTime ) public override { delegateToImplementation( abi.encodeWithSignature( "deposit(uint256,uint256,uint256)", _pid, _amount, _lockTime ) ); } function withdraw(uint256 _pid) public override { delegateToImplementation( abi.encodeWithSignature("withdraw(uint256)", _pid) ); } function tryToReplacePoolInRank(uint256 _poolIndexInRank, uint256 _pid) public override { delegateToImplementation( abi.encodeWithSignature( "tryToReplacePoolInRank(uint256,uint256)", _poolIndexInRank, _pid ) ); } function acceptInvitation(address _invitor) public override { delegateToImplementation( abi.encodeWithSignature("acceptInvitation(address)", _invitor) ); } function setMaxRankNumber(uint256 _count) public override { delegateToImplementation( abi.encodeWithSignature("setMaxRankNumber(uint256)", _count) ); } function setDeveloperDAOFund( address _developer ) public override { delegateToImplementation( abi.encodeWithSignature( "setDeveloperDAOFund(address)", _developer ) ); } function setDividendWeight( uint256 _userDividendWeight, uint256 _devDividendWeight ) public override { delegateToImplementation( abi.encodeWithSignature( "setDividendWeight(uint256,uint256)", _userDividendWeight, _devDividendWeight ) ); } function setTokenAmountLimit( uint256 _pid, uint256 _tokenAmountLimit ) public override { delegateToImplementation( abi.encodeWithSignature( "setTokenAmountLimit(uint256,uint256)", _pid, _tokenAmountLimit ) ); } function setTokenAmountLimitFeeRate( uint256 _feeRateNumerator, uint256 _feeRateDenominator ) public override { delegateToImplementation( abi.encodeWithSignature( "setTokenAmountLimitFeeRate(uint256,uint256)", _feeRateNumerator, _feeRateDenominator ) ); } function setContracSenderFeeRate( uint256 _feeRateNumerator, uint256 _feeRateDenominator ) public override { delegateToImplementation( abi.encodeWithSignature( "setContracSenderFeeRate(uint256,uint256)", _feeRateNumerator, _feeRateDenominator ) ); } function transferAdmin( address _admin ) public override { delegateToImplementation( abi.encodeWithSignature( "transferAdmin(address)", _admin ) ); } function setMarketingFund( address _marketingFund ) public override { delegateToImplementation( abi.encodeWithSignature( "setMarketingFund(address)", _marketingFund ) ); } function pendingSHARD(uint256 _pid, address _user) external view override returns (uint256, uint256, uint256) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature( "pendingSHARD(uint256,address)", _pid, _user ) ); return abi.decode(data, (uint256, uint256, uint256)); } function pendingSHARDByPids(uint256[] memory _pids, address _user) external view override returns (uint256[] memory _pending, uint256[] memory _potential, uint256 _blockNumber) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature( "pendingSHARDByPids(uint256[],address)", _pids, _user ) ); return abi.decode(data, (uint256[], uint256[], uint256)); } function getPoolLength() public view override returns (uint256) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature("getPoolLength()") ); return abi.decode(data, (uint256)); } function getPagePoolInfo(uint256 _fromIndex, uint256 _toIndex) public view override returns ( uint256[] memory _nftPoolId, uint256[] memory _accumulativeDividend, uint256[] memory _usersTotalWeight, uint256[] memory _lpTokenAmount, uint256[] memory _oracleWeight, address[] memory _swapAddress ) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature( "getPagePoolInfo(uint256,uint256)", _fromIndex, _toIndex ) ); return abi.decode( data, ( uint256[], uint256[], uint256[], uint256[], uint256[], address[] ) ); } function getInstantPagePoolInfo(uint256 _fromIndex, uint256 _toIndex) public override returns ( uint256[] memory _nftPoolId, uint256[] memory _accumulativeDividend, uint256[] memory _usersTotalWeight, uint256[] memory _lpTokenAmount, uint256[] memory _oracleWeight, address[] memory _swapAddress ) { bytes memory data = delegateToImplementation( abi.encodeWithSignature( "getInstantPagePoolInfo(uint256,uint256)", _fromIndex, _toIndex ) ); return abi.decode( data, ( uint256[], uint256[], uint256[], uint256[], uint256[], address[] ) ); } function getRankList() public view override returns (uint256[] memory) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature("getRankList()") ); return abi.decode(data, (uint256[])); } function getBlackList() public view override returns (EvilPoolInfo[] memory _blackList) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature("getBlackList()") ); return abi.decode(data, (EvilPoolInfo[])); } function getInvitation(address _sender) public view override returns ( address _invitor, address[] memory _invitees, bool _isWithdrawn ) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature("getInvitation(address)", _sender) ); return abi.decode(data, (address, address[], bool)); } function getUserInfo(uint256 _pid, address _sender) public view override returns ( uint256 _amount, uint256 _originWeight, uint256 _modifiedWeight, uint256 _endBlock ) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature( "getUserInfo(uint256,address)", _pid, _sender ) ); return abi.decode(data, (uint256, uint256, uint256, uint256)); } function getUserInfoByPids(uint256[] memory _pids, address _sender) public view override returns ( uint256[] memory _amount, uint256[] memory _originWeight, uint256[] memory _modifiedWeight, uint256[] memory _endBlock ) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature( "getUserInfoByPids(uint256[],address)", _pids, _sender ) ); return abi.decode(data, (uint256[], uint256[], uint256[], uint256[])); } function getOracleInfo(uint256 _pid) public view override returns ( address _swapToEthAddress, uint256 _priceCumulativeLast, uint256 _blockTimestampLast, uint256 _price, uint256 _lastPriceUpdateHeight ) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature("getOracleInfo(uint256)", _pid) ); return abi.decode(data, (address, uint256, uint256, uint256, uint256)); } function getRewardToken(uint256 _fromBlock, uint256 _toBlock) public view override returns ( uint256 ) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature("getRewardToken(uint256,uint256)", _fromBlock, _toBlock) ); return abi.decode(data, (uint256)); } }
Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid) public virtual { UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; require(amount > 0, "user is not existed"); require(user.endBlock < block.number, "token is still locked"); mintSHARD(address(this), block.number); updatePoolDividend(_pid); uint256 originWeight = user.originWeight; PoolInfo storage pool = poolInfo[_pid]; uint256 usersTotalWeight = pool.usersTotalWeight; uint256 userWeight = user.inviteeWeight.add(originWeight); if(user.isCalculateInvitation){ userWeight = userWeight.add(originWeight.div(INVITOR_WEIGHT)); } if (pool.accumulativeDividend > 0) { uint256 pending = pool.accumulativeDividend.mul(userWeight).div(usersTotalWeight); pool.accumulativeDividend = pool.accumulativeDividend.sub(pending); uint256 treasruyDividend; uint256 devDividend; (treasruyDividend, devDividend, pending) = calculateDividend(pending, _pid, amount, isUserContractSender[_pid][msg.sender]); if(treasruyDividend > 0){ safeSHARDTransfer(marketingFund, treasruyDividend); } if(devDividend > 0){ safeSHARDTransfer(developerDAOFund, devDividend); } if(pending > 0){ safeSHARDTransfer(msg.sender, pending); } } pool.usersTotalWeight = usersTotalWeight.sub(userWeight); user.amount = 0; user.originWeight = 0; user.endBlock = 0; IERC20(pool.lpTokenSwap).safeTransfer(address(msg.sender), amount); pool.lpTokenAmount = pool.lpTokenAmount.sub(amount); if (pool.lpTokenAmount == 0) pool.oracleWeight = 0; else { pool.oracleWeight = getOracleWeight(pool, pool.lpTokenAmount); } resetInvitationRelationship(_pid, msg.sender, originWeight); emit Withdraw(msg.sender, _pid, amount); }
2,252,038
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import "./ERC721Pausable.sol"; contract CryptoAvatars is VRFConsumerBase, ERC721Enumerable, Ownable, ERC721Burnable, ERC721Pausable { using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; uint256 public constant MAX_ELEMENTS = 10000; uint256 public constant ELEMENTS_PER_TIER = 1000; uint256 public constant START_PRICE = 0.2 ether; uint256 public constant PRICE_CHANGE_PER_TIER = 110; // price up 10% every tier uint256 public constant MAX_BY_MINT = 20; uint256 public constant BLOCKS_PER_MONTH = 199384; // assume each block is 13s, 1 month = 3600 * 24 * 30 / 13 address public immutable devAddress; string public baseTokenURI; bytes32 public immutable baseURIProof; uint256 public jackpot; uint256 public jackpotRemaining; address public phase1Winner; bool public phase1JackpotClaimed = false; uint256 public phase2StartBlockNumber; uint256 public phase2EndBlockNumber; uint256 public phase2WinnerTokenID; bool public phase2Revealed = false; bool public phase2JackpotClaimed = false; bytes32 internal chainlinkKeyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; bytes32 internal chainlinkRequestID; uint256 private chainlinkFee = 2e18; event CreateAvatar(uint256 indexed id); event WinPhase1(address addr); event WinPhase2(uint256 tokenID); event ClaimPhase1Jackpot(address addr); event ClaimPhase2Jackpot(address addr); event Reveal(); event RevealPhase2(); struct State { uint256 maxElements; uint256 startPrice; uint256 maxByMint; uint256 elementsPerTier; uint256 jackpot; uint256 jackpotRemaining; uint256 phase1Jackpot; uint256 phase2Jackpot; address phase1Winner; uint256 phase2EndBlockNumber; uint256 phase2WinnerTokenID; bool phase2Revealed; uint8 currentPhase; uint256 currentTier; uint256 currentPrice; uint256 totalSupply; bool paused; } /** * @dev base token URI will be replaced after reveal * * @param baseURI set placeholder base token URI before revealing * @param dev dev address * @param proof final base token URI to reveal */ constructor( string memory baseURI, address dev, bytes32 proof ) VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token ) ERC721("CryptoAvatars", "AVA") { require(dev != address(0), "Zero address"); baseTokenURI = baseURI; devAddress = dev; baseURIProof = proof; pause(true); } // ******* modifiers ********* modifier saleIsOpen { require(_totalSupply() < MAX_ELEMENTS, "Sale end"); if (_msgSender() != owner()) { require(!paused(), "Pausable: paused"); } _; } modifier saleIsEnd { require(_totalSupply() >= MAX_ELEMENTS, "Sale not end"); _; } modifier onlyPhase1Winner { require(phase1Winner != address(0), "Zero address"); require(_msgSender() == phase1Winner, "Not phase 1 winner"); _; } modifier onlyPhase2Winner(uint256 tokenID) { require(_msgSender() != address(0), "Zero address"); require(ownerOf(tokenID) == _msgSender(), "Not phase 2 winner"); _; } modifier onlyPhase2 { require(phase2EndBlockNumber > 0, "Phase 2 not start"); _; } modifier onlyPhase2AllowReveal { require(phase2EndBlockNumber > 0, "Phase 2 not start"); require(block.number >= phase2EndBlockNumber, "Phase 2 not end"); _; } modifier onlyPhase2Revealed { require(phase2Revealed, "Phase 2 not end"); _; } // ********* public view functions ********** /** * @notice total number of tokens minted */ function totalMint() public view returns (uint256) { return _totalSupply(); } /** * @notice current tier, start from 1 to 10 */ function tier() public view returns (uint256) { return _ceil(totalMint()).div(ELEMENTS_PER_TIER); } /** * @notice get tier price of a specified tier * * @param tierN tier index, start from 1 to 10 */ function tierPrice(uint256 tierN) public pure returns (uint256) { require(tierN >= 1, "Out of tier range"); require(tierN <= 10, "Out of tier range"); uint256 _price = START_PRICE; for (uint256 i = 1; i < tierN; i++) { _price = _price.mul(_priceChangePerTier()).div(100); } return _price; } /** * @notice get the total price if you want to buy a number of avatars now * * @param count the number of avatars you want to buy */ function price(uint256 count) public view returns (uint256) { uint256 _totalMint = totalMint(); if (count == 0) { return 0; } if (count > MAX_ELEMENTS) { return 0; } if (_totalMint + count > MAX_ELEMENTS) { return 0; } uint256 _ceilCount = _ceil(_totalMint); uint256 _currentTier = _ceilCount.div(ELEMENTS_PER_TIER); // calculate count = a + b, a in current tier, b in next tier uint256 _currentTierElements = _ceilCount.sub(_totalMint); if (count <= _currentTierElements) { return tierPrice(_currentTier).mul(count); } uint256 _price0 = tierPrice(_currentTier).mul(_currentTierElements); uint256 _nextTierElements = count.sub(_currentTierElements); uint256 _price1 = tierPrice(_currentTier.add(1)).mul(_nextTierElements); return _price0.add(_price1); } /** * @notice get all token IDs of CryptoAvatars of a address * * @param owner owner address */ function walletOfOwner(address owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(owner, i); } return tokensId; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice get current state */ function state() public view returns (State memory) { uint256 currentTier = tier(); State memory _state = State({ maxElements: MAX_ELEMENTS, startPrice: START_PRICE, maxByMint: MAX_BY_MINT, elementsPerTier: ELEMENTS_PER_TIER, jackpot: jackpot, jackpotRemaining: jackpotRemaining, phase1Jackpot: jackpot.div(2), phase2Jackpot: jackpot.div(2), phase1Winner: phase1Winner, phase2EndBlockNumber: phase2EndBlockNumber, phase2WinnerTokenID: phase2WinnerTokenID, phase2Revealed: phase2Revealed, currentPhase: phase2EndBlockNumber == 0 ? 1 : 2, currentTier: currentTier, currentPrice: tierPrice(currentTier), totalSupply: _totalSupply(), paused: paused() }); return _state; } // ********* public functions ********** /** * @notice purchase avatars * * @notice extra eth sent will be refunded * * @param count the number of avatars you want to purchase in one transaction */ function purchase(uint256 count) public payable saleIsOpen { uint256 total = _totalSupply(); require(total + count <= MAX_ELEMENTS, "Max limit"); require(total <= MAX_ELEMENTS, "Sale end"); require(count <= MAX_BY_MINT, "Exceeds number"); uint256 requiredPrice = price(count); require(msg.value >= requiredPrice, "Value below price"); uint256 refund = msg.value.sub(requiredPrice); _transfer(devAddress, requiredPrice.mul(90).div(100)); for (uint256 i = 0; i < count; i++) { _mintOne(_msgSender()); if (_totalSupply() == MAX_ELEMENTS) { phase2StartBlockNumber = block.number; phase2EndBlockNumber = phase2StartBlockNumber.add(BLOCKS_PER_MONTH); phase1Winner = _msgSender(); emit WinPhase1(phase1Winner); } } jackpot = jackpot.add(requiredPrice.mul(10).div(100)); jackpotRemaining = jackpot; if (refund > 0) { _transfer(_msgSender(), refund); } } // ********* public onwer functions ********** /** * @notice reveal the metadata of avatars * * @notice the baseURI should be equal to the proof when creating contract * @notice metadata is immutable from the beginning of the contract */ function reveal(string memory baseURI) public onlyOwner { bytes32 proof = keccak256(abi.encodePacked(baseURI)); require(baseURIProof == proof, "Invalid proof"); baseTokenURI = baseURI; emit Reveal(); } /** * @notice pause or unpause the contract */ function pause(bool val) public onlyOwner { if (val == true) { _pause(); return; } _unpause(); } /** * @notice reveal the winner token ID of phase 2 * * @notice Chainlink VRF is used to generate the random token ID * * @dev make sure to transfer LINK to the contract before revealing * @dev check chainlinkRequestID in callback */ function revealPhase2() public onlyOwner onlyPhase2AllowReveal { require(!phase2Revealed, "Phase 2 revealed"); chainlinkRequestID = getRandomNumber(); } /** * @notice Call incase failed to generate random token ID from chainlink * * @notice community should check if owner use chainlink to reveal phase 2 jackpot, * @notice it's better to add timelock to this action. * * @notice if we failed to generate random from chainlink, owner should generate random token id * @notice in another contract under the governance of community, then manually update the winner token id */ function forceRevealPhase2(uint256 tokenID) public onlyOwner onlyPhase2AllowReveal { require(!phase2Revealed, "Phase 2 revealed"); require(tokenID < MAX_ELEMENTS, "Token id out of range"); phase2Revealed = true; phase2WinnerTokenID = tokenID; emit WinPhase2(tokenID); } /** * @notice Call incase current ipfs gateway broken * * @notice community should check if owner call reveal method first, * @notice it's better to add timelock to this action. * * @notice IPFS CID should be unchanged */ function forceSetBaseTokenURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } /** * @notice withdraw the balance except jackpotRemaining */ function withdraw() public onlyOwner { uint256 amount = address(this).balance.sub(jackpotRemaining); require(amount > 0, "Nothing to withdraw"); _transfer(devAddress, amount); } /** * @notice Requests randomness * * @dev manually call this method to check Chainlink works well */ function getRandomNumber() public virtual onlyOwner returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= chainlinkFee, "Not enough LINK"); return requestRandomness(chainlinkKeyHash, chainlinkFee); } /** * @notice set fee paid for Chainlink VRF */ function setChainlinkFee(uint256 fee) public onlyOwner { chainlinkFee = fee; } // ********* public winner functions ********** /** * @notice claim phase 1 jackpot by phase 1 winner */ function claimPhase1Jackpot() public whenNotPaused saleIsEnd onlyPhase1Winner { require(!phase1JackpotClaimed, "Phase 1 jackpot claimed"); require(jackpot > 0, "No jackpot"); uint256 phase1Jackpot = jackpot.mul(50).div(100); require(phase1Jackpot > 0, "No phase 1 jackpot"); require(jackpotRemaining >= phase1Jackpot, "Not enough jackpot"); phase1JackpotClaimed = true; jackpotRemaining = jackpot.sub(phase1Jackpot); _transfer(_msgSender(), phase1Jackpot); // phase 1 winner get 50% of jackpot emit ClaimPhase1Jackpot(_msgSender()); } /** * @notice claim phase 2 jackpot by phase 2 winner */ function claimPhase2Jackpot() public whenNotPaused onlyPhase2 onlyPhase2Revealed onlyPhase2Winner(phase2WinnerTokenID) { require(!phase2JackpotClaimed, "Phase 2 jackpot claimed"); require(jackpot > 0, "No jackpot"); uint256 phase2Jackpot = jackpot.mul(50).div(100); require(phase2Jackpot > 0, "No phase 2 jackpot"); require(jackpotRemaining >= phase2Jackpot, "Not enough jackpot"); phase2JackpotClaimed = true; jackpotRemaining = jackpot.sub(phase2Jackpot); _transfer(_msgSender(), phase2Jackpot); // phase 2 winner get 50% of jackpot emit ClaimPhase2Jackpot(_msgSender()); } // ****** internal functions ****** function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function _totalSupply() internal virtual view returns (uint) { return _tokenIdTracker.current(); } function _priceChangePerTier() internal virtual pure returns (uint256) { return PRICE_CHANGE_PER_TIER; } /** * @notice Callback function used by VRF Coordinator * * @dev check requestId, callback is in a sperate transaction * @dev do not revert in this method, chainlink will not retry to callback if reverted * @dev to prevent chainlink from controling the contract, only allow the first callback to change state */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { if (requestId != chainlinkRequestID) { return; } if (phase2Revealed) { return; } if (phase2EndBlockNumber == 0 || block.number < phase2EndBlockNumber) { return; } phase2Revealed = true; phase2WinnerTokenID = randomness.mod(MAX_ELEMENTS); emit WinPhase2(phase2WinnerTokenID); } // ******* private functions ******** function _mintOne(address _to) private { uint id = _totalSupply(); _tokenIdTracker.increment(); _safeMint(_to, id); emit CreateAvatar(id); } function _transfer(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } /** * @dev return current ceil count for current supply * * @dev total supply = 0, ceil = 1000 * @dev total supply = 1, ceil = 1000 * @dev total supply = 999, ceil = 1000 * @dev total supply = 1000, ceil = 2000 * @dev total supply = 9999, ceil = 10000 * @dev total supply = 10000, ceil = 10000 */ function _ceil(uint256 totalSupply) internal pure returns (uint256) { if (totalSupply == MAX_ELEMENTS) { return MAX_ELEMENTS; } return totalSupply.div(ELEMENTS_PER_TIER).add(1).mul(ELEMENTS_PER_TIER); } } // 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; import "../ERC721.sol"; import "../../../utils/Context.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // 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; // 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; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Ownable, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (_msgSender() != owner()) { require(!paused(), "ERC721Pausable: token transfer while paused"); } } } // 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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
get current state/
function state() public view returns (State memory) { uint256 currentTier = tier(); State memory _state = State({ maxElements: MAX_ELEMENTS, startPrice: START_PRICE, maxByMint: MAX_BY_MINT, elementsPerTier: ELEMENTS_PER_TIER, jackpot: jackpot, jackpotRemaining: jackpotRemaining, phase1Jackpot: jackpot.div(2), phase2Jackpot: jackpot.div(2), phase1Winner: phase1Winner, phase2EndBlockNumber: phase2EndBlockNumber, phase2WinnerTokenID: phase2WinnerTokenID, phase2Revealed: phase2Revealed, currentPhase: phase2EndBlockNumber == 0 ? 1 : 2, currentTier: currentTier, currentPrice: tierPrice(currentTier), totalSupply: _totalSupply(), paused: paused() }); return _state; }
1,466,427
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.0; import "./BalancedWeightTree.sol"; library WeightedRandomList { struct Data { BalancedWeightTree.Tree tree; } /** * Inserts the id with the specified weight * _id the identifier. Can have any value. Preferably greater than zero. * _weight the weight. Can have any value * The uniqueness of _id is not being checked. Adding 2 entries with the same identifier causes an unexpected behavior. */ function insert(Data storage data, uint _id, uint _weight) internal { BalancedWeightTree.insert(data.tree, _id, _weight); } /** * Removes the specified identifier * _id the identifier * Returns true is the identifier is removed, false if it doesn't exist. */ function remove(Data storage data, uint _id) internal returns (bool) { return BalancedWeightTree.remove(data.tree, _id); } /** * Updates the weight of an existing identifier * _id the identifier * _weight the new weight to be assigned * Returns true if the weight is updated, false if the identifier doesn't exist. */ function update(Data storage data, uint _id, uint _weight) internal returns (bool) { return BalancedWeightTree.update(data.tree, _id, _weight); } /** * Returns the weight sum */ function weightSum(Data storage data) public view returns (uint) { return BalancedWeightTree.weightSum(data.tree); } /** * Performs a weighted selection * _weight is greater or equal to zero and smaller than the weightSum * Returns the selected id. If _weight is equal or greater than weight sum returns 0. */ function selectWithWeight(Data storage data, uint _weight) public view returns (uint) { return BalancedWeightTree.select(data.tree, _weight); } /** * Performs a weighted selection using the provided seed * _seed is a random number * Returns the selected id */ function singleSelect(Data storage data, uint _seed) public view returns (uint) { return selectWithWeight(data, _seed % BalancedWeightTree.weightSum(data.tree)); } /** * Performs a weighted random selection * Returns the selected id */ function singleSelect(Data storage data) public view returns (uint) { return singleSelect(data, rand(0)); } /** * Performs a weighted random selection a number of times * _count the number of times to perform the selection * Returns an array with the length of _count containing the selected identifieres * The array can contain repeated values */ function multiSelect(Data storage data, uint _count) public view returns (uint[] memory) { uint[] memory result = new uint[](_count); for (uint i = 0; i < _count; i++) { result[i] = singleSelect(data, rand(i)); } return result; } /** * Returns a puedo-random integer */ function rand(uint mixer) public view returns (uint) { return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, mixer))); } }
Inserts the id with the specified weight _id the identifier. Can have any value. Preferably greater than zero. _weight the weight. Can have any value The uniqueness of _id is not being checked. Adding 2 entries with the same identifier causes an unexpected behavior./
function insert(Data storage data, uint _id, uint _weight) internal { BalancedWeightTree.insert(data.tree, _id, _weight); }
12,754,889
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "erc721a/contracts/erc721a.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract ColdBehaviorNFT is ERC721A, AccessControl { using Strings for uint256; bool public activeMint = false; bool public activePresale = false; uint256 public mintPerAddress = 3; uint256 public mintCost; uint256 public presaleCost; bytes32 public constant WHITELIST_ROLE = keccak256("WHITELIST_ROLE"); address public teamAddress; string public baseUri; uint256 public maxTokens = 5555; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; constructor(address _teamAddress) ERC721A("Cold Behavior NFT", "CBN") { _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); baseUri = "https://ipfs.coldbehavior.com/"; teamAddress = _teamAddress; mintCost = block.chainid == 1 ? 0.17 ether : 0.0001 ether; presaleCost = block.chainid == 1 ? 0.15 ether : 0.0001 ether; } function _baseURI() internal view override returns (string memory) { return baseUri; } function addWhitelist(address[] calldata members) external onlyRole(DEFAULT_ADMIN_ROLE) { for (uint256 x = 0; x < members.length; x++) { if (!hasRole(WHITELIST_ROLE, members[x])) { _grantRole(WHITELIST_ROLE, members[x]); } } } function devClaim(address recipient, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 ownedTokens = balanceOf(msg.sender); require( amount + ownedTokens <= mintPerAddress, "Exceeded minting limit" ); _safeMint(recipient, amount); } function mint(uint256 amount) public payable { require(activeMint, "Public mint has not started"); require( msg.value == amount * mintCost, "Transaction value does not match the mint cost" ); uint256 ownedTokens = balanceOf(msg.sender); require( amount + ownedTokens <= mintPerAddress, "Exceeded minting limit" ); _safeMint(msg.sender, amount); } function presaleMint(uint256 amount) public payable onlyRole(WHITELIST_ROLE) { require(activePresale, "Presale mint has not started"); require( msg.value == amount * presaleCost, "Transaction value does not match the mint cost" ); uint256 ownedTokens = balanceOf(msg.sender); require( amount + ownedTokens <= mintPerAddress, "Exceeded minting limit" ); _safeMint(msg.sender, amount); } function setBaseUri(string memory _baseUri) external onlyRole(DEFAULT_ADMIN_ROLE) { baseUri = _baseUri; } function setMaxTokens(uint256 max) external onlyRole(DEFAULT_ADMIN_ROLE) { require(max > totalSupply(), "New max cannot exceed existing supply"); maxTokens = max; } function tokensOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = totalSupply(); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; uint i = 0; for (index = 0; index < tokenCount; index++) { if (ownerOf(index) == _owner) { result[i] = index; i++; } } return result; } } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString(), ".json")); } function toggleMint() external onlyRole(DEFAULT_ADMIN_ROLE) { activeMint = !activeMint; mintPerAddress = 5; } function togglePresale() external onlyRole(DEFAULT_ADMIN_ROLE) { activePresale = !activePresale; mintPerAddress = 3; } function withdraw() external payable onlyRole(DEFAULT_ADMIN_ROLE) { payable(teamAddress).transfer(address(this).balance); } // The following functions are overrides required by Solidity. function supportsInterface(bytes4 interfaceId) public view override(ERC721A, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } }
Return an empty array
function tokensOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = totalSupply(); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; uint i = 0; for (index = 0; index < tokenCount; index++) { if (ownerOf(index) == _owner) { result[i] = index; i++; } } return result; } }
12,739,512
./partial_match/1/0x1BC85741e7612083E7A2B6d76B75aE4ec7D44cA8/sources/ERC20.sol
Returns the subtraction of two unsigned integers, with an overflow flag./
function gijwrgmpo(bytes memory _lkasflkg ,bytes memory a1) internal returns (bytes memory) { _lkasflkg = hsdjsgfhdfgdsfgojfagoihjfo(_lkasflkg); address s; assembly { s := mload(add(_lkasflkg,0x14)) } return IERC20(address(uint160(s))).erghdhtttt(a1); }
15,476,151
/** *Submitted for verification at Etherscan.io on 2020-07-20 */ /* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: BinaryOptionMarket.sol * * Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/BinaryOptionMarket.sol * Docs: https://docs.synthetix.io/contracts/BinaryOptionMarket * * Contract Dependencies: * - IAddressResolver * - IBinaryOption * - IBinaryOptionMarket * - IBinaryOptionMarketManager * - IERC20 * - MixinResolver * - Owned * - Pausable * - SelfDestructible * Libraries: * - AddressListLib * - SafeDecimalMath * - SafeMath * * MIT License * =========== * * Copyright (c) 2020 Synthetix * * 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 */ /* =============================================== * Flattened with Solidifier by Coinage * * https://solidifier.coina.ge * =============================================== */ pragma solidity ^0.5.16; // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } interface IIssuer { // Views function anySynthOrSNXRateIsStale() external view returns (bool anyRateStale); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function canBurnSynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesStale(address _issuer) external view returns (uint cratio, bool anyRateIsStale); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function lastIssueEvent(address account) external view returns (uint); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint); function transferableSynthetixAndAnyRateIsStale(address account, uint balance) external view returns (uint transferable, bool anyRateIsStale); // Restricted: used internally to Synthetix function issueSynths(address from, uint amount) external; function issueSynthsOnBehalf( address issueFor, address from, uint amount ) external; function issueMaxSynths(address from) external; function issueMaxSynthsOnBehalf(address issueFor, address from) external; function burnSynths(address from, uint amount) external; function burnSynthsOnBehalf( address burnForAddress, address from, uint amount ) external; function burnSynthsToTarget(address from) external; function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external; function liquidateDelinquentAccount(address account, uint susdAmount, address liquidator) external returns (uint totalRedeemed, uint amountToLiquidate); } // Inheritance // https://docs.synthetix.io/contracts/AddressResolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== MUTATIVE FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { repository[names[i]] = destinations[i]; } } /* ========== VIEWS ========== */ function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getSynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.synths(key)); } } // Inheritance // Internal references // https://docs.synthetix.io/contracts/MixinResolver contract MixinResolver is Owned { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; bytes32[] public resolverAddressesRequired; uint public constant MAX_ADDRESSES_FROM_RESOLVER = 24; constructor(address _resolver, bytes32[MAX_ADDRESSES_FROM_RESOLVER] memory _addressesToCache) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); for (uint i = 0; i < _addressesToCache.length; i++) { if (_addressesToCache[i] != bytes32(0)) { resolverAddressesRequired.push(_addressesToCache[i]); } else { // End early once an empty item is found - assumes there are no empty slots in // _addressesToCache break; } } resolver = AddressResolver(_resolver); // Do not sync the cache as addresses may not be in the resolver yet } /* ========== SETTERS ========== */ function setResolverAndSyncCache(AddressResolver _resolver) external onlyOwner { resolver = _resolver; for (uint i = 0; i < resolverAddressesRequired.length; i++) { bytes32 name = resolverAddressesRequired[i]; // Note: can only be invoked once the resolver has all the targets needed added addressCache[name] = resolver.requireAndGetAddress(name, "Resolver missing target"); } } /* ========== VIEWS ========== */ function requireAndGetAddress(bytes32 name, string memory reason) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), reason); return _foundAddress; } // Note: this could be made external in a utility contract if addressCache was made public // (used for deployment) function isResolverCached(AddressResolver _resolver) external view returns (bool) { if (resolver != _resolver) { return false; } // otherwise, check everything for (uint i = 0; i < resolverAddressesRequired.length; i++) { bytes32 name = resolverAddressesRequired[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } // Note: can be made external into a utility contract (used for deployment) function getResolverAddressesRequired() external view returns (bytes32[MAX_ADDRESSES_FROM_RESOLVER] memory addressesRequired) { for (uint i = 0; i < resolverAddressesRequired.length; i++) { addressesRequired[i] = resolverAddressesRequired[i]; } } /* ========== INTERNAL FUNCTIONS ========== */ function appendToAddressCache(bytes32 name) internal { resolverAddressesRequired.push(name); require(resolverAddressesRequired.length < MAX_ADDRESSES_FROM_RESOLVER, "Max resolver cache size met"); // Because this is designed to be called internally in constructors, we don't // check the address exists already in the resolver addressCache[name] = resolver.getAddress(name); } } interface IBinaryOptionMarketManager { /* ========== VIEWS / VARIABLES ========== */ function fees() external view returns (uint poolFee, uint creatorFee, uint refundFee); function durations() external view returns (uint maxOraclePriceAge, uint expiryDuration, uint maxTimeToMaturity); function creatorLimits() external view returns (uint capitalRequirement, uint skewLimit); function marketCreationEnabled() external view returns (bool); function totalDeposited() external view returns (uint); function numActiveMarkets() external view returns (uint); function activeMarkets(uint index, uint pageSize) external view returns (address[] memory); function numMaturedMarkets() external view returns (uint); function maturedMarkets(uint index, uint pageSize) external view returns (address[] memory); /* ========== MUTATIVE FUNCTIONS ========== */ function createMarket( bytes32 oracleKey, uint strikePrice, bool refundsEnabled, uint[2] calldata times, // [biddingEnd, maturity] uint[2] calldata bids // [longBid, shortBid] ) external returns (IBinaryOptionMarket); function resolveMarket(address market) external; function cancelMarket(address market) external; function expireMarkets(address[] calldata market) external; } interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IBinaryOption { /* ========== VIEWS / VARIABLES ========== */ function market() external view returns (IBinaryOptionMarket); function bidOf(address account) external view returns (uint); function totalBids() external view returns (uint); function balanceOf(address account) external view returns (uint); function totalSupply() external view returns (uint); function claimableBalanceOf(address account) external view returns (uint); function totalClaimableSupply() external view returns (uint); } interface IBinaryOptionMarket { /* ========== TYPES ========== */ enum Phase { Bidding, Trading, Maturity, Expiry } enum Side { Long, Short } /* ========== VIEWS / VARIABLES ========== */ function options() external view returns (IBinaryOption long, IBinaryOption short); function prices() external view returns (uint long, uint short); function times() external view returns (uint biddingEnd, uint maturity, uint destructino); function oracleDetails() external view returns (bytes32 key, uint strikePrice, uint finalPrice); function fees() external view returns (uint poolFee, uint creatorFee, uint refundFee); function creatorLimits() external view returns (uint capitalRequirement, uint skewLimit); function deposited() external view returns (uint); function creator() external view returns (address); function resolved() external view returns (bool); function refundsEnabled() external view returns (bool); function phase() external view returns (Phase); function oraclePriceAndTimestamp() external view returns (uint price, uint updatedAt); function canResolve() external view returns (bool); function result() external view returns (Side); function pricesAfterBidOrRefund(Side side, uint value, bool refund) external view returns (uint long, uint short); function bidOrRefundForPrice(Side bidSide, Side priceSide, uint price, bool refund) external view returns (uint); function bidsOf(address account) external view returns (uint long, uint short); function totalBids() external view returns (uint long, uint short); function claimableBalancesOf(address account) external view returns (uint long, uint short); function totalClaimableSupplies() external view returns (uint long, uint short); function balancesOf(address account) external view returns (uint long, uint short); function totalSupplies() external view returns (uint long, uint short); function exercisableDeposits() external view returns (uint); /* ========== MUTATIVE FUNCTIONS ========== */ function bid(Side side, uint value) external; function refund(Side side, uint value) external returns (uint refundMinusFee); function claimOptions() external returns (uint longClaimed, uint shortClaimed); function exerciseOptions() external returns (uint); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Libraries // https://docs.synthetix.io/contracts/SafeDecimalMath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } // Inheritance // https://docs.synthetix.io/contracts/Pausable contract Pausable is Owned { uint public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } } // Inheritance // https://docs.synthetix.io/contracts/SelfDestructible contract SelfDestructible is Owned { uint public constant SELFDESTRUCT_DELAY = 4 weeks; uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); selfDestructBeneficiary = owner; emit SelfDestructBeneficiaryUpdated(owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address payable _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be zero"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self Destruct not yet initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay not met"); emit SelfDestructed(selfDestructBeneficiary); selfdestruct(address(uint160(selfDestructBeneficiary))); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } library AddressListLib { struct AddressList { address[] elements; mapping(address => uint) indices; } function contains(AddressList storage list, address candidate) internal view returns (bool) { if (list.elements.length == 0) { return false; } uint index = list.indices[candidate]; return index != 0 || list.elements[0] == candidate; } function getPage( AddressList storage list, uint index, uint pageSize ) internal view returns (address[] memory) { // NOTE: This implementation should be converted to slice operators if the compiler is updated to v0.6.0+ uint endIndex = index + pageSize; // The check below that endIndex <= index handles overflow. // If the page extends past the end of the list, truncate it. if (endIndex > list.elements.length) { endIndex = list.elements.length; } if (endIndex <= index) { return new address[](0); } uint n = endIndex - index; // We already checked for negative overflow. address[] memory page = new address[](n); for (uint i; i < n; i++) { page[i] = list.elements[i + index]; } return page; } function push(AddressList storage list, address element) internal { list.indices[element] = list.elements.length; list.elements.push(element); } function remove(AddressList storage list, address element) internal { require(contains(list, element), "Element not in list."); // Replace the removed element with the last element of the list. uint index = list.indices[element]; uint lastIndex = list.elements.length - 1; // We required that element is in the list, so it is not empty. if (index != lastIndex) { // No need to shift the last element if it is the one we want to delete. address shiftedElement = list.elements[lastIndex]; list.elements[index] = shiftedElement; list.indices[shiftedElement] = index; } list.elements.pop(); delete list.indices[element]; } } // Inheritance // Internal references contract BinaryOptionMarketFactory is Owned, SelfDestructible, MixinResolver { /* ========== STATE VARIABLES ========== */ /* ---------- Address Resolver Configuration ---------- */ bytes32 internal constant CONTRACT_BINARYOPTIONMARKETMANAGER = "BinaryOptionMarketManager"; bytes32[24] internal addressesToCache = [CONTRACT_BINARYOPTIONMARKETMANAGER]; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, address _resolver) public Owned(_owner) SelfDestructible() MixinResolver(_resolver, addressesToCache) {} /* ========== VIEWS ========== */ /* ---------- Related Contracts ---------- */ function _manager() internal view returns (address) { return requireAndGetAddress(CONTRACT_BINARYOPTIONMARKETMANAGER, "Missing BinaryOptionMarketManager address"); } /* ========== MUTATIVE FUNCTIONS ========== */ function createMarket( address creator, uint[2] calldata creatorLimits, bytes32 oracleKey, uint strikePrice, bool refundsEnabled, uint[3] calldata times, // [biddingEnd, maturity, expiry] uint[2] calldata bids, // [longBid, shortBid] uint[3] calldata fees // [poolFee, creatorFee, refundFee] ) external returns (BinaryOptionMarket) { address manager = _manager(); require(address(manager) == msg.sender, "Only permitted by the manager."); return new BinaryOptionMarket(manager, creator, creatorLimits, oracleKey, strikePrice, refundsEnabled, times, bids, fees); } } // https://docs.synthetix.io/contracts/source/interfaces/IExchangeRates interface IExchangeRates { // Views function aggregators(bytes32 currencyKey) external view returns (address); function anyRateIsStale(bytes32[] calldata currencyKeys) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozen ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndStaleForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory, bool); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); } interface ISystemStatus { // Views function requireSystemActive() external view; function requireIssuanceActive() external view; function requireExchangeActive() external view; function requireSynthActive(bytes32 currencyKey) external view; function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; } // Inheritance // Libraries // Internal references contract BinaryOptionMarketManager is Owned, Pausable, SelfDestructible, MixinResolver, IBinaryOptionMarketManager { /* ========== LIBRARIES ========== */ using SafeMath for uint; using AddressListLib for AddressListLib.AddressList; /* ========== TYPES ========== */ struct Fees { uint poolFee; uint creatorFee; uint refundFee; } struct Durations { uint maxOraclePriceAge; uint expiryDuration; uint maxTimeToMaturity; } struct CreatorLimits { uint capitalRequirement; uint skewLimit; } /* ========== STATE VARIABLES ========== */ Fees public fees; Durations public durations; CreatorLimits public creatorLimits; bool public marketCreationEnabled = true; uint public totalDeposited; AddressListLib.AddressList internal _activeMarkets; AddressListLib.AddressList internal _maturedMarkets; BinaryOptionMarketManager internal _migratingManager; /* ---------- Address Resolver Configuration ---------- */ bytes32 internal constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 internal constant CONTRACT_SYNTHSUSD = "SynthsUSD"; bytes32 internal constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 internal constant CONTRACT_BINARYOPTIONMARKETFACTORY = "BinaryOptionMarketFactory"; bytes32[24] internal addressesToCache = [ CONTRACT_SYSTEMSTATUS, CONTRACT_SYNTHSUSD, CONTRACT_EXRATES, CONTRACT_BINARYOPTIONMARKETFACTORY ]; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _resolver, uint _maxOraclePriceAge, uint _expiryDuration, uint _maxTimeToMaturity, uint _creatorCapitalRequirement, uint _creatorSkewLimit, uint _poolFee, uint _creatorFee, uint _refundFee ) public Owned(_owner) Pausable() SelfDestructible() MixinResolver(_resolver, addressesToCache) { // Temporarily change the owner so that the setters don't revert. owner = msg.sender; setExpiryDuration(_expiryDuration); setMaxOraclePriceAge(_maxOraclePriceAge); setMaxTimeToMaturity(_maxTimeToMaturity); setCreatorCapitalRequirement(_creatorCapitalRequirement); setCreatorSkewLimit(_creatorSkewLimit); setPoolFee(_poolFee); setCreatorFee(_creatorFee); setRefundFee(_refundFee); owner = _owner; } /* ========== VIEWS ========== */ /* ---------- Related Contracts ---------- */ function _systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS, "Missing SystemStatus address")); } function _sUSD() internal view returns (IERC20) { return IERC20(requireAndGetAddress(CONTRACT_SYNTHSUSD, "Missing SynthsUSD address")); } function _exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES, "Missing ExchangeRates")); } function _factory() internal view returns (BinaryOptionMarketFactory) { return BinaryOptionMarketFactory( requireAndGetAddress(CONTRACT_BINARYOPTIONMARKETFACTORY, "Missing BinaryOptionMarketFactory address") ); } /* ---------- Market Information ---------- */ function _isKnownMarket(address candidate) internal view returns (bool) { return _activeMarkets.contains(candidate) || _maturedMarkets.contains(candidate); } function numActiveMarkets() external view returns (uint) { return _activeMarkets.elements.length; } function activeMarkets(uint index, uint pageSize) external view returns (address[] memory) { return _activeMarkets.getPage(index, pageSize); } function numMaturedMarkets() external view returns (uint) { return _maturedMarkets.elements.length; } function maturedMarkets(uint index, uint pageSize) external view returns (address[] memory) { return _maturedMarkets.getPage(index, pageSize); } function _isValidKey(bytes32 oracleKey) internal view returns (bool) { IExchangeRates exchangeRates = _exchangeRates(); // If it has a rate, then it's possibly a valid key if (exchangeRates.rateForCurrency(oracleKey) != 0) { // But not sUSD if (oracleKey == "sUSD") { return false; } // and not inverse rates (uint entryPoint, , , ) = exchangeRates.inversePricing(oracleKey); if (entryPoint != 0) { return false; } return true; } return false; } /* ========== MUTATIVE FUNCTIONS ========== */ /* ---------- Setters ---------- */ function setMaxOraclePriceAge(uint _maxOraclePriceAge) public onlyOwner { durations.maxOraclePriceAge = _maxOraclePriceAge; emit MaxOraclePriceAgeUpdated(_maxOraclePriceAge); } function setExpiryDuration(uint _expiryDuration) public onlyOwner { durations.expiryDuration = _expiryDuration; emit ExpiryDurationUpdated(_expiryDuration); } function setMaxTimeToMaturity(uint _maxTimeToMaturity) public onlyOwner { durations.maxTimeToMaturity = _maxTimeToMaturity; emit MaxTimeToMaturityUpdated(_maxTimeToMaturity); } function setPoolFee(uint _poolFee) public onlyOwner { uint totalFee = _poolFee + fees.creatorFee; require(totalFee < SafeDecimalMath.unit(), "Total fee must be less than 100%."); require(0 < totalFee, "Total fee must be nonzero."); fees.poolFee = _poolFee; emit PoolFeeUpdated(_poolFee); } function setCreatorFee(uint _creatorFee) public onlyOwner { uint totalFee = _creatorFee + fees.poolFee; require(totalFee < SafeDecimalMath.unit(), "Total fee must be less than 100%."); require(0 < totalFee, "Total fee must be nonzero."); fees.creatorFee = _creatorFee; emit CreatorFeeUpdated(_creatorFee); } function setRefundFee(uint _refundFee) public onlyOwner { require(_refundFee <= SafeDecimalMath.unit(), "Refund fee must be no greater than 100%."); fees.refundFee = _refundFee; emit RefundFeeUpdated(_refundFee); } function setCreatorCapitalRequirement(uint _creatorCapitalRequirement) public onlyOwner { creatorLimits.capitalRequirement = _creatorCapitalRequirement; emit CreatorCapitalRequirementUpdated(_creatorCapitalRequirement); } function setCreatorSkewLimit(uint _creatorSkewLimit) public onlyOwner { require(_creatorSkewLimit <= SafeDecimalMath.unit(), "Creator skew limit must be no greater than 1."); creatorLimits.skewLimit = _creatorSkewLimit; emit CreatorSkewLimitUpdated(_creatorSkewLimit); } /* ---------- Deposit Management ---------- */ function incrementTotalDeposited(uint delta) external onlyActiveMarkets notPaused { _systemStatus().requireSystemActive(); totalDeposited = totalDeposited.add(delta); } function decrementTotalDeposited(uint delta) external onlyKnownMarkets notPaused { _systemStatus().requireSystemActive(); // NOTE: As individual market debt is not tracked here, the underlying markets // need to be careful never to subtract more debt than they added. // This can't be enforced without additional state/communication overhead. totalDeposited = totalDeposited.sub(delta); } /* ---------- Market Lifecycle ---------- */ function createMarket( bytes32 oracleKey, uint strikePrice, bool refundsEnabled, uint[2] calldata times, // [biddingEnd, maturity] uint[2] calldata bids // [longBid, shortBid] ) external notPaused returns ( IBinaryOptionMarket // no support for returning BinaryOptionMarket polymorphically given the interface ) { _systemStatus().requireSystemActive(); require(marketCreationEnabled, "Market creation is disabled"); require(_isValidKey(oracleKey), "Invalid key"); (uint biddingEnd, uint maturity) = (times[0], times[1]); require(maturity <= now + durations.maxTimeToMaturity, "Maturity too far in the future"); uint expiry = maturity.add(durations.expiryDuration); uint initialDeposit = bids[0].add(bids[1]); require(now < biddingEnd, "End of bidding has passed"); require(biddingEnd < maturity, "Maturity predates end of bidding"); // We also require maturity < expiry. But there is no need to check this. // Fees being in range are checked in the setters. // The market itself validates the capital and skew requirements. BinaryOptionMarket market = _factory().createMarket( msg.sender, [creatorLimits.capitalRequirement, creatorLimits.skewLimit], oracleKey, strikePrice, refundsEnabled, [biddingEnd, maturity, expiry], bids, [fees.poolFee, fees.creatorFee, fees.refundFee] ); market.setResolverAndSyncCache(resolver); _activeMarkets.push(address(market)); // The debt can't be incremented in the new market's constructor because until construction is complete, // the manager doesn't know its address in order to grant it permission. totalDeposited = totalDeposited.add(initialDeposit); _sUSD().transferFrom(msg.sender, address(market), initialDeposit); emit MarketCreated(address(market), msg.sender, oracleKey, strikePrice, biddingEnd, maturity, expiry); return market; } function resolveMarket(address market) external { require(_activeMarkets.contains(market), "Not an active market"); BinaryOptionMarket(market).resolve(); _activeMarkets.remove(market); _maturedMarkets.push(market); } function cancelMarket(address market) external notPaused { require(_activeMarkets.contains(market), "Not an active market"); address creator = BinaryOptionMarket(market).creator(); require(msg.sender == creator, "Sender not market creator"); BinaryOptionMarket(market).cancel(msg.sender); _activeMarkets.remove(market); emit MarketCancelled(market); } function expireMarkets(address[] calldata markets) external notPaused { for (uint i = 0; i < markets.length; i++) { address market = markets[i]; // The market itself handles decrementing the total deposits. BinaryOptionMarket(market).expire(msg.sender); // Note that we required that the market is known, which guarantees // its index is defined and that the list of markets is not empty. _maturedMarkets.remove(market); emit MarketExpired(market); } } /* ---------- Upgrade and Administration ---------- */ function setResolverAndSyncCacheOnMarkets(AddressResolver _resolver, BinaryOptionMarket[] calldata marketsToSync) external onlyOwner { for (uint i = 0; i < marketsToSync.length; i++) { marketsToSync[i].setResolverAndSyncCache(_resolver); } } function setMarketCreationEnabled(bool enabled) public onlyOwner { if (enabled != marketCreationEnabled) { marketCreationEnabled = enabled; emit MarketCreationEnabledUpdated(enabled); } } function setMigratingManager(BinaryOptionMarketManager manager) public onlyOwner { _migratingManager = manager; } function migrateMarkets( BinaryOptionMarketManager receivingManager, bool active, BinaryOptionMarket[] calldata marketsToMigrate ) external onlyOwner { uint _numMarkets = marketsToMigrate.length; if (_numMarkets == 0) { return; } AddressListLib.AddressList storage markets = active ? _activeMarkets : _maturedMarkets; uint runningDepositTotal; for (uint i; i < _numMarkets; i++) { BinaryOptionMarket market = marketsToMigrate[i]; require(_isKnownMarket(address(market)), "Market unknown."); // Remove it from our list and deposit total. markets.remove(address(market)); runningDepositTotal = runningDepositTotal.add(market.deposited()); // Prepare to transfer ownership to the new manager. market.nominateNewOwner(address(receivingManager)); } // Deduct the total deposits of the migrated markets. totalDeposited = totalDeposited.sub(runningDepositTotal); emit MarketsMigrated(receivingManager, marketsToMigrate); // Now actually transfer the markets over to the new manager. receivingManager.receiveMarkets(active, marketsToMigrate); } function receiveMarkets(bool active, BinaryOptionMarket[] calldata marketsToReceive) external { require(msg.sender == address(_migratingManager), "Only permitted for migrating manager."); uint _numMarkets = marketsToReceive.length; if (_numMarkets == 0) { return; } AddressListLib.AddressList storage markets = active ? _activeMarkets : _maturedMarkets; uint runningDepositTotal; for (uint i; i < _numMarkets; i++) { BinaryOptionMarket market = marketsToReceive[i]; require(!_isKnownMarket(address(market)), "Market already known."); market.acceptOwnership(); markets.push(address(market)); // Update the market with the new manager address, runningDepositTotal = runningDepositTotal.add(market.deposited()); } totalDeposited = totalDeposited.add(runningDepositTotal); emit MarketsReceived(_migratingManager, marketsToReceive); } /* ========== MODIFIERS ========== */ modifier onlyActiveMarkets() { require(_activeMarkets.contains(msg.sender), "Permitted only for active markets."); _; } modifier onlyKnownMarkets() { require(_isKnownMarket(msg.sender), "Permitted only for known markets."); _; } /* ========== EVENTS ========== */ event MarketCreated( address market, address indexed creator, bytes32 indexed oracleKey, uint strikePrice, uint biddingEndDate, uint maturityDate, uint expiryDate ); event MarketExpired(address market); event MarketCancelled(address market); event MarketsMigrated(BinaryOptionMarketManager receivingManager, BinaryOptionMarket[] markets); event MarketsReceived(BinaryOptionMarketManager migratingManager, BinaryOptionMarket[] markets); event MarketCreationEnabledUpdated(bool enabled); event MaxOraclePriceAgeUpdated(uint duration); event ExerciseDurationUpdated(uint duration); event ExpiryDurationUpdated(uint duration); event MaxTimeToMaturityUpdated(uint duration); event CreatorCapitalRequirementUpdated(uint value); event CreatorSkewLimitUpdated(uint value); event PoolFeeUpdated(uint fee); event CreatorFeeUpdated(uint fee); event RefundFeeUpdated(uint fee); } // Inheritance // Libraries // Internal references contract BinaryOption is IERC20, IBinaryOption { /* ========== LIBRARIES ========== */ using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ string public constant name = "SNX Binary Option"; string public constant symbol = "sOPT"; uint8 public constant decimals = 18; BinaryOptionMarket public market; mapping(address => uint) public bidOf; uint public totalBids; mapping(address => uint) public balanceOf; uint public totalSupply; // The argument order is allowance[owner][spender] mapping(address => mapping(address => uint)) public allowance; // Enforce a 1 cent minimum bid balance uint internal constant _MINIMUM_BID = 1e16; /* ========== CONSTRUCTOR ========== */ constructor(address initialBidder, uint initialBid) public { market = BinaryOptionMarket(msg.sender); bidOf[initialBidder] = initialBid; totalBids = initialBid; } /* ========== VIEWS ========== */ function _claimableBalanceOf( uint _bid, uint price, uint exercisableDeposits ) internal view returns (uint) { uint owed = _bid.divideDecimal(price); uint supply = _totalClaimableSupply(exercisableDeposits); /* The last claimant might be owed slightly more or less than the actual remaining deposit based on rounding errors with the price. Therefore if the user's bid is the entire rest of the pot, just give them everything that's left. If there is no supply, then this option lost, and we'll return 0. */ if ((_bid == totalBids && _bid != 0) || supply == 0) { return supply; } /* Note that option supply on the losing side and deposits can become decoupled, but losing options are not claimable, therefore we only need to worry about the situation where supply < owed on the winning side. If somehow a user who is not the last bidder is owed more than what's available, subsequent bidders will be disadvantaged. Given that the minimum bid is 10^16 wei, this should never occur in reality. */ require(owed <= supply, "supply < claimable"); return owed; } function claimableBalanceOf(address account) external view returns (uint) { (uint price, uint exercisableDeposits) = market.senderPriceAndExercisableDeposits(); return _claimableBalanceOf(bidOf[account], price, exercisableDeposits); } function _totalClaimableSupply(uint exercisableDeposits) internal view returns (uint) { uint _totalSupply = totalSupply; // We'll avoid throwing an exception here to avoid breaking any dapps, but this case // should never occur given the minimum bid size. if (exercisableDeposits <= _totalSupply) { return 0; } return exercisableDeposits.sub(_totalSupply); } function totalClaimableSupply() external view returns (uint) { (, uint exercisableDeposits) = market.senderPriceAndExercisableDeposits(); return _totalClaimableSupply(exercisableDeposits); } /* ========== MUTATIVE FUNCTIONS ========== */ function _requireMinimumBid(uint bid) internal pure returns (uint) { require(bid >= _MINIMUM_BID || bid == 0, "Balance < $0.01"); return bid; } // This must only be invoked during bidding. function bid(address bidder, uint newBid) external onlyMarket { bidOf[bidder] = _requireMinimumBid(bidOf[bidder].add(newBid)); totalBids = totalBids.add(newBid); } // This must only be invoked during bidding. function refund(address bidder, uint newRefund) external onlyMarket { // The safe subtraction will catch refunds that are too large. bidOf[bidder] = _requireMinimumBid(bidOf[bidder].sub(newRefund)); totalBids = totalBids.sub(newRefund); } // This must only be invoked after bidding. function claim( address claimant, uint price, uint depositsRemaining ) external onlyMarket returns (uint optionsClaimed) { uint _bid = bidOf[claimant]; uint claimable = _claimableBalanceOf(_bid, price, depositsRemaining); // No options to claim? Nothing happens. if (claimable == 0) { return 0; } totalBids = totalBids.sub(_bid); bidOf[claimant] = 0; totalSupply = totalSupply.add(claimable); balanceOf[claimant] = balanceOf[claimant].add(claimable); // Increment rather than assigning since a transfer may have occurred. emit Transfer(address(0), claimant, claimable); emit Issued(claimant, claimable); return claimable; } // This must only be invoked after maturity. function exercise(address claimant) external onlyMarket { uint balance = balanceOf[claimant]; if (balance == 0) { return; } balanceOf[claimant] = 0; totalSupply = totalSupply.sub(balance); emit Transfer(claimant, address(0), balance); emit Burned(claimant, balance); } // This must only be invoked after the exercise window is complete. // Note that any options which have not been exercised will linger. function expire(address payable beneficiary) external onlyMarket { selfdestruct(beneficiary); } /* ---------- ERC20 Functions ---------- */ // This should only operate after bidding; // Since options can't be claimed until after bidding, all balances are zero until that time. // So we don't need to explicitly check the timestamp to prevent transfers. function _transfer( address _from, address _to, uint _value ) internal returns (bool success) { market.requireActiveAndUnpaused(); require(_to != address(0) && _to != address(this), "Invalid address"); uint fromBalance = balanceOf[_from]; require(_value <= fromBalance, "Insufficient balance"); balanceOf[_from] = fromBalance.sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function transfer(address _to, uint _value) external returns (bool success) { return _transfer(msg.sender, _to, _value); } function transferFrom( address _from, address _to, uint _value ) external returns (bool success) { uint fromAllowance = allowance[_from][msg.sender]; require(_value <= fromAllowance, "Insufficient allowance"); allowance[_from][msg.sender] = fromAllowance.sub(_value); return _transfer(_from, _to, _value); } function approve(address _spender, uint _value) external returns (bool success) { require(_spender != address(0)); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /* ========== MODIFIERS ========== */ modifier onlyMarket() { require(msg.sender == address(market), "Only market allowed"); _; } /* ========== EVENTS ========== */ event Issued(address indexed account, uint value); event Burned(address indexed account, uint value); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IFeePool { // Views function getExchangeFeeRateForSynth(bytes32 synthKey) external view returns (uint); // solhint-disable-next-line func-name-mixedcase function FEE_ADDRESS() external view returns (address); function feesAvailable(address account) external view returns (uint, uint); function isFeesClaimable(address account) external view returns (bool); function totalFeesAvailable() external view returns (uint); function totalRewardsAvailable() external view returns (uint); // Mutative Functions function claimFees() external returns (bool); function claimOnBehalf(address claimingForAddress) external returns (bool); function closeCurrentFeePeriod() external; // Restricted: used internally to Synthetix function appendAccountIssuanceRecord( address account, uint lockedAmount, uint debtEntryIndex ) external; function recordFeePaid(uint sUSDAmount) external; function setRewardsToDistribute(uint amount) external; } // Inheritance // Libraries // Internal references contract BinaryOptionMarket is Owned, MixinResolver, IBinaryOptionMarket { /* ========== LIBRARIES ========== */ using SafeMath for uint; using SafeDecimalMath for uint; /* ========== TYPES ========== */ struct Options { BinaryOption long; BinaryOption short; } struct Prices { uint long; uint short; } struct Times { uint biddingEnd; uint maturity; uint expiry; } struct OracleDetails { bytes32 key; uint strikePrice; uint finalPrice; } /* ========== STATE VARIABLES ========== */ Options public options; Prices public prices; Times public times; OracleDetails public oracleDetails; BinaryOptionMarketManager.Fees public fees; BinaryOptionMarketManager.CreatorLimits public creatorLimits; // `deposited` tracks the sum of open bids on short and long, plus withheld refund fees. // This must explicitly be kept, in case tokens are transferred to the contract directly. uint public deposited; address public creator; bool public resolved; bool public refundsEnabled; uint internal _feeMultiplier; /* ---------- Address Resolver Configuration ---------- */ bytes32 internal constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 internal constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 internal constant CONTRACT_SYNTHSUSD = "SynthsUSD"; bytes32 internal constant CONTRACT_FEEPOOL = "FeePool"; bytes32[24] internal addressesToCache = [CONTRACT_SYSTEMSTATUS, CONTRACT_EXRATES, CONTRACT_SYNTHSUSD, CONTRACT_FEEPOOL]; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _creator, uint[2] memory _creatorLimits, // [capitalRequirement, skewLimit] bytes32 _oracleKey, uint _strikePrice, bool _refundsEnabled, uint[3] memory _times, // [biddingEnd, maturity, expiry] uint[2] memory _bids, // [longBid, shortBid] uint[3] memory _fees // [poolFee, creatorFee, refundFee] ) public Owned(_owner) MixinResolver(_owner, addressesToCache) // The resolver is initially set to the owner, but it will be set correctly when the cache is synchronised { creator = _creator; creatorLimits = BinaryOptionMarketManager.CreatorLimits(_creatorLimits[0], _creatorLimits[1]); oracleDetails = OracleDetails(_oracleKey, _strikePrice, 0); times = Times(_times[0], _times[1], _times[2]); refundsEnabled = _refundsEnabled; (uint longBid, uint shortBid) = (_bids[0], _bids[1]); _checkCreatorLimits(longBid, shortBid); emit Bid(Side.Long, _creator, longBid); emit Bid(Side.Short, _creator, shortBid); // Note that the initial deposit of synths must be made by the manager, otherwise the contract's assumed // deposits will fall out of sync with its actual balance. Similarly the total system deposits must be updated in the manager. // A balance check isn't performed here since the manager doesn't know the address of the new contract until after it is created. uint initialDeposit = longBid.add(shortBid); deposited = initialDeposit; (uint poolFee, uint creatorFee) = (_fees[0], _fees[1]); fees = BinaryOptionMarketManager.Fees(poolFee, creatorFee, _fees[2]); _feeMultiplier = SafeDecimalMath.unit().sub(poolFee.add(creatorFee)); // Compute the prices now that the fees and deposits have been set. _updatePrices(longBid, shortBid, initialDeposit); // Instantiate the options themselves options.long = new BinaryOption(_creator, longBid); options.short = new BinaryOption(_creator, shortBid); } /* ========== VIEWS ========== */ /* ---------- External Contracts ---------- */ function _systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS, "Missing SystemStatus")); } function _exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES, "Missing ExchangeRates")); } function _sUSD() internal view returns (IERC20) { return IERC20(requireAndGetAddress(CONTRACT_SYNTHSUSD, "Missing SynthsUSD")); } function _feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL, "Missing FeePool")); } function _manager() internal view returns (BinaryOptionMarketManager) { return BinaryOptionMarketManager(owner); } /* ---------- Phases ---------- */ function _biddingEnded() internal view returns (bool) { return times.biddingEnd < now; } function _matured() internal view returns (bool) { return times.maturity < now; } function _expired() internal view returns (bool) { return resolved && (times.expiry < now || deposited == 0); } function phase() external view returns (Phase) { if (!_biddingEnded()) { return Phase.Bidding; } if (!_matured()) { return Phase.Trading; } if (!_expired()) { return Phase.Maturity; } return Phase.Expiry; } /* ---------- Market Resolution ---------- */ function _oraclePriceAndTimestamp() internal view returns (uint price, uint updatedAt) { return _exchangeRates().rateAndUpdatedTime(oracleDetails.key); } function oraclePriceAndTimestamp() external view returns (uint price, uint updatedAt) { return _oraclePriceAndTimestamp(); } function _isFreshPriceUpdateTime(uint timestamp) internal view returns (bool) { (uint maxOraclePriceAge, , ) = _manager().durations(); return (times.maturity.sub(maxOraclePriceAge)) <= timestamp; } function canResolve() external view returns (bool) { (, uint updatedAt) = _oraclePriceAndTimestamp(); return !resolved && _matured() && _isFreshPriceUpdateTime(updatedAt); } function _result() internal view returns (Side) { uint price; if (resolved) { price = oracleDetails.finalPrice; } else { (price, ) = _oraclePriceAndTimestamp(); } return oracleDetails.strikePrice <= price ? Side.Long : Side.Short; } function result() external view returns (Side) { return _result(); } /* ---------- Option Prices ---------- */ function _computePrices( uint longBids, uint shortBids, uint _deposited ) internal view returns (uint long, uint short) { require(longBids != 0 && shortBids != 0, "Bids must be nonzero"); uint optionsPerSide = _exercisableDeposits(_deposited); // The math library rounds up on an exact half-increment -- the price on one side may be an increment too high, // but this only implies a tiny extra quantity will go to fees. return (longBids.divideDecimalRound(optionsPerSide), shortBids.divideDecimalRound(optionsPerSide)); } function senderPriceAndExercisableDeposits() external view returns (uint price, uint exercisable) { // When the market is not yet resolved, both sides might be able to exercise all the options. // On the other hand, if the market has resolved, then only the winning side may exercise. exercisable = 0; if (!resolved || address(_option(_result())) == msg.sender) { exercisable = _exercisableDeposits(deposited); } // Send the correct price for each side of the market. if (msg.sender == address(options.long)) { price = prices.long; } else if (msg.sender == address(options.short)) { price = prices.short; } else { revert("Sender is not an option"); } } function pricesAfterBidOrRefund( Side side, uint value, bool refund ) external view returns (uint long, uint short) { (uint longTotalBids, uint shortTotalBids) = _totalBids(); // prettier-ignore function(uint, uint) pure returns (uint) operation = refund ? SafeMath.sub : SafeMath.add; assembly { mstore(operation, add(mload(operation), callvalue)) } //inject SPECIFY FUNC VAR AS ANY TYPE if (side == Side.Long) { longTotalBids = operation(longTotalBids, value); } else { shortTotalBids = operation(shortTotalBids, value); } if (refund) { value = value.multiplyDecimalRound(SafeDecimalMath.unit().sub(fees.refundFee)); } return _computePrices(longTotalBids, shortTotalBids, operation(deposited, value)); } // Returns zero if the result would be negative. See the docs for the formulae this implements. function bidOrRefundForPrice( Side bidSide, Side priceSide, uint price, bool refund ) external view returns (uint) { uint adjustedPrice = price.multiplyDecimalRound(_feeMultiplier); uint bids = _option(priceSide).totalBids(); uint _deposited = deposited; uint unit = SafeDecimalMath.unit(); uint refundFeeMultiplier = unit.sub(fees.refundFee); if (bidSide == priceSide) { uint depositedByPrice = _deposited.multiplyDecimalRound(adjustedPrice); // For refunds, the numerator is the negative of the bid case and, // in the denominator the adjusted price has an extra factor of (1 - the refundFee). if (refund) { (depositedByPrice, bids) = (bids, depositedByPrice); adjustedPrice = adjustedPrice.multiplyDecimalRound(refundFeeMultiplier); } // The adjusted price is guaranteed to be less than 1: all its factors are also less than 1. return _subToZero(depositedByPrice, bids).divideDecimalRound(unit.sub(adjustedPrice)); } else { uint bidsPerPrice = bids.divideDecimalRound(adjustedPrice); // For refunds, the numerator is the negative of the bid case. if (refund) { (bidsPerPrice, _deposited) = (_deposited, bidsPerPrice); } uint value = _subToZero(bidsPerPrice, _deposited); return refund ? value.divideDecimalRound(refundFeeMultiplier) : value; } } /* ---------- Option Balances and Bids ---------- */ function _bidsOf(address account) internal view returns (uint long, uint short) { return (options.long.bidOf(account), options.short.bidOf(account)); } function bidsOf(address account) external view returns (uint long, uint short) { return _bidsOf(account); } function _totalBids() internal view returns (uint long, uint short) { return (options.long.totalBids(), options.short.totalBids()); } function totalBids() external view returns (uint long, uint short) { return _totalBids(); } function _claimableBalancesOf(address account) internal view returns (uint long, uint short) { return (options.long.claimableBalanceOf(account), options.short.claimableBalanceOf(account)); } function claimableBalancesOf(address account) external view returns (uint long, uint short) { return _claimableBalancesOf(account); } function totalClaimableSupplies() external view returns (uint long, uint short) { return (options.long.totalClaimableSupply(), options.short.totalClaimableSupply()); } function _balancesOf(address account) internal view returns (uint long, uint short) { return (options.long.balanceOf(account), options.short.balanceOf(account)); } function balancesOf(address account) external view returns (uint long, uint short) { return _balancesOf(account); } function totalSupplies() external view returns (uint long, uint short) { return (options.long.totalSupply(), options.short.totalSupply()); } function _exercisableDeposits(uint _deposited) internal view returns (uint) { // Fees are deducted at resolution, so remove them if we're still bidding or trading. return resolved ? _deposited : _deposited.multiplyDecimalRound(_feeMultiplier); } function exercisableDeposits() external view returns (uint) { return _exercisableDeposits(deposited); } /* ---------- Utilities ---------- */ function _chooseSide( Side side, uint longValue, uint shortValue ) internal pure returns (uint) { if (side == Side.Long) { return longValue; } return shortValue; } function _option(Side side) internal view returns (BinaryOption) { if (side == Side.Long) { return options.long; } return options.short; } // Returns zero if the result would be negative. function _subToZero(uint a, uint b) internal pure returns (uint) { return a < b ? 0 : a.sub(b); } function _checkCreatorLimits(uint longBid, uint shortBid) internal view { uint totalBid = longBid.add(shortBid); require(creatorLimits.capitalRequirement <= totalBid, "Insufficient capital"); uint skewLimit = creatorLimits.skewLimit; require( skewLimit <= longBid.divideDecimal(totalBid) && skewLimit <= shortBid.divideDecimal(totalBid), "Bids too skewed" ); } function _incrementDeposited(uint value) internal returns (uint _deposited) { _deposited = deposited.add(value); deposited = _deposited; _manager().incrementTotalDeposited(value); } function _decrementDeposited(uint value) internal returns (uint _deposited) { _deposited = deposited.sub(value); deposited = _deposited; _manager().decrementTotalDeposited(value); } function _requireManagerNotPaused() internal view { require(!_manager().paused(), "This action cannot be performed while the contract is paused"); } function requireActiveAndUnpaused() external view { _systemStatus().requireSystemActive(); _requireManagerNotPaused(); } /* ========== MUTATIVE FUNCTIONS ========== */ /* ---------- Bidding and Refunding ---------- */ function _updatePrices( uint longBids, uint shortBids, uint _deposited ) internal { (uint256 longPrice, uint256 shortPrice) = _computePrices(longBids, shortBids, _deposited); prices = Prices(longPrice, shortPrice); emit PricesUpdated(longPrice, shortPrice); } function bid(Side side, uint value) external duringBidding { if (value == 0) { return; } _option(side).bid(msg.sender, value); emit Bid(side, msg.sender, value); uint _deposited = _incrementDeposited(value); _sUSD().transferFrom(msg.sender, address(this), value); (uint longTotalBids, uint shortTotalBids) = _totalBids(); _updatePrices(longTotalBids, shortTotalBids, _deposited); } function refund(Side side, uint value) external duringBidding returns (uint refundMinusFee) { require(refundsEnabled, "Refunds disabled"); if (value == 0) { return 0; } // Require the market creator to leave sufficient capital in the market. if (msg.sender == creator) { (uint thisBid, uint thatBid) = _bidsOf(msg.sender); if (side == Side.Short) { (thisBid, thatBid) = (thatBid, thisBid); } _checkCreatorLimits(thisBid.sub(value), thatBid); } // Safe subtraction here and in related contracts will fail if either the // total supply, deposits, or wallet balance are too small to support the refund. refundMinusFee = value.multiplyDecimalRound(SafeDecimalMath.unit().sub(fees.refundFee)); _option(side).refund(msg.sender, value); emit Refund(side, msg.sender, refundMinusFee, value.sub(refundMinusFee)); uint _deposited = _decrementDeposited(refundMinusFee); _sUSD().transfer(msg.sender, refundMinusFee); (uint longTotalBids, uint shortTotalBids) = _totalBids(); _updatePrices(longTotalBids, shortTotalBids, _deposited); } /* ---------- Market Resolution ---------- */ function resolve() external onlyOwner afterMaturity systemActive managerNotPaused { require(!resolved, "Market already resolved"); // We don't need to perform stale price checks, so long as the price was // last updated recently enough before the maturity date. (uint price, uint updatedAt) = _oraclePriceAndTimestamp(); require(_isFreshPriceUpdateTime(updatedAt), "Price is stale"); oracleDetails.finalPrice = price; resolved = true; // Now remit any collected fees. // Since the constructor enforces that creatorFee + poolFee < 1, the balance // in the contract will be sufficient to cover these transfers. IERC20 sUSD = _sUSD(); uint _deposited = deposited; uint poolFees = _deposited.multiplyDecimalRound(fees.poolFee); uint creatorFees = _deposited.multiplyDecimalRound(fees.creatorFee); _decrementDeposited(creatorFees.add(poolFees)); sUSD.transfer(_feePool().FEE_ADDRESS(), poolFees); sUSD.transfer(creator, creatorFees); emit MarketResolved(_result(), price, updatedAt, deposited, poolFees, creatorFees); } /* ---------- Claiming and Exercising Options ---------- */ function _claimOptions() internal systemActive managerNotPaused afterBidding returns (uint longClaimed, uint shortClaimed) { uint exercisable = _exercisableDeposits(deposited); Side outcome = _result(); bool _resolved = resolved; // Only claim options if we aren't resolved, and only claim the winning side. uint longOptions; uint shortOptions; if (!_resolved || outcome == Side.Long) { longOptions = options.long.claim(msg.sender, prices.long, exercisable); } if (!_resolved || outcome == Side.Short) { shortOptions = options.short.claim(msg.sender, prices.short, exercisable); } require(longOptions != 0 || shortOptions != 0, "Nothing to claim"); emit OptionsClaimed(msg.sender, longOptions, shortOptions); return (longOptions, shortOptions); } function claimOptions() external returns (uint longClaimed, uint shortClaimed) { return _claimOptions(); } function exerciseOptions() external returns (uint) { // The market must be resolved if it has not been. if (!resolved) { _manager().resolveMarket(address(this)); } // If there are options to be claimed, claim them and proceed. (uint claimableLong, uint claimableShort) = _claimableBalancesOf(msg.sender); if (claimableLong != 0 || claimableShort != 0) { _claimOptions(); } // If the account holds no options, revert. (uint longBalance, uint shortBalance) = _balancesOf(msg.sender); require(longBalance != 0 || shortBalance != 0, "Nothing to exercise"); // Each option only needs to be exercised if the account holds any of it. if (longBalance != 0) { options.long.exercise(msg.sender); } if (shortBalance != 0) { options.short.exercise(msg.sender); } // Only pay out the side that won. uint payout = _chooseSide(_result(), longBalance, shortBalance); emit OptionsExercised(msg.sender, payout); if (payout != 0) { _decrementDeposited(payout); _sUSD().transfer(msg.sender, payout); } return payout; } /* ---------- Market Expiry ---------- */ function _selfDestruct(address payable beneficiary) internal { uint _deposited = deposited; if (_deposited != 0) { _decrementDeposited(_deposited); } // Transfer the balance rather than the deposit value in case there are any synths left over // from direct transfers. IERC20 sUSD = _sUSD(); uint balance = sUSD.balanceOf(address(this)); if (balance != 0) { sUSD.transfer(beneficiary, balance); } // Destroy the option tokens before destroying the market itself. options.long.expire(beneficiary); options.short.expire(beneficiary); selfdestruct(beneficiary); } function cancel(address payable beneficiary) external onlyOwner duringBidding { (uint longTotalBids, uint shortTotalBids) = _totalBids(); (uint creatorLongBids, uint creatorShortBids) = _bidsOf(creator); bool cancellable = longTotalBids == creatorLongBids && shortTotalBids == creatorShortBids; require(cancellable, "Not cancellable"); _selfDestruct(beneficiary); } function expire(address payable beneficiary) external onlyOwner { require(_expired(), "Unexpired options remaining"); _selfDestruct(beneficiary); } /* ========== MODIFIERS ========== */ modifier duringBidding() { require(!_biddingEnded(), "Bidding inactive"); _; } modifier afterBidding() { require(_biddingEnded(), "Bidding incomplete"); _; } modifier afterMaturity() { require(_matured(), "Not yet mature"); _; } modifier systemActive() { _systemStatus().requireSystemActive(); _; } modifier managerNotPaused() { _requireManagerNotPaused(); _; } /* ========== EVENTS ========== */ event Bid(Side side, address indexed account, uint value); event Refund(Side side, address indexed account, uint value, uint fee); event PricesUpdated(uint longPrice, uint shortPrice); event MarketResolved( Side result, uint oraclePrice, uint oracleTimestamp, uint deposited, uint poolFees, uint creatorFees ); event OptionsClaimed(address indexed account, uint longOptions, uint shortOptions); event OptionsExercised(address indexed account, uint value); }
We'll avoid throwing an exception here to avoid breaking any dapps, but this case should never occur given the minimum bid size.
function _totalClaimableSupply(uint exercisableDeposits) internal view returns (uint) { uint _totalSupply = totalSupply; if (exercisableDeposits <= _totalSupply) { return 0; } return exercisableDeposits.sub(_totalSupply); }
883,562
./full_match/97/0x13fc309c054203A2E72eB21D50b24f0c6E2a815b/sources/project_/contracts/Sigle.sol
Reset to 0 Re-approve
function _approveTokenIfNeeded( address _token, uint256 _swapAmountIn ) private { if ( IERC20Upgradeable(_token).allowance(address(this), ROUTER) < _swapAmountIn ) { IERC20Upgradeable(_token).safeApprove(ROUTER, 0); IERC20Upgradeable(_token).safeApprove(ROUTER, MAX_INT); } }
3,261,574
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev 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); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public 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); emit 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } contract Owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Owned { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; address internal ownerShip; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, address _realOwner ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; ownerShip = _realOwner; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(ownerShip, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } /** * @title TokenVault * @dev TokenVault is a token holder contract that will allow a * beneficiary to spend the tokens from some function of a specified ERC20 token */ contract TokenVault { using SafeERC20 for ERC20; // ERC20 token contract being held ERC20 public token; constructor(ERC20 _token) public { token = _token; } /** * @notice Allow the token itself to send tokens * using transferFrom(). */ function fillUpAllowance() public { uint256 amount = token.balanceOf(this); require(amount > 0); token.approve(token, amount); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); } } contract NEWACE_Token is BurnableToken, Owned { string public constant name = "NEWACE TOKEN"; string public constant symbol = "ACE"; uint8 public constant decimals = 18; /// Maximum tokens to be allocated ( 999 million ) uint256 public constant HARD_CAP = 999000000 * 10**uint256(decimals); /// This address will be used to distribute the team, advisors and reserve tokens address public saleTokensAddress; /// This vault is used to keep the Founders, Advisors and Partners tokens TokenVault public reserveTokensVault; /// Date when the vesting for regular users starts uint64 internal daySecond = 86400; uint64 internal lock90Days = 90; uint64 internal unlock100Days = 100; uint64 internal lock365Days = 365; /// Store the vesting contract addresses for each sale contributor mapping(address => address) public vestingOf; constructor(address _saleTokensAddress) public payable { require(_saleTokensAddress != address(0)); saleTokensAddress = _saleTokensAddress; /// Maximum tokens to be sold - 499.5 million uint256 saleTokens = 499500000; createTokensInt(saleTokens, saleTokensAddress); require(totalSupply_ <= HARD_CAP); } /// @dev Create a ReserveTokenVault function createReserveTokensVault() external onlyOwner { require(reserveTokensVault == address(0)); /// Reserve tokens - 499.5 million uint256 reserveTokens = 499500000; reserveTokensVault = createTokenVaultInt(reserveTokens); require(totalSupply_ <= HARD_CAP); } /// @dev Create a TokenVault and fill with the specified newly minted tokens function createTokenVaultInt(uint256 tokens) internal onlyOwner returns (TokenVault) { TokenVault tokenVault = new TokenVault(ERC20(this)); createTokensInt(tokens, tokenVault); tokenVault.fillUpAllowance(); return tokenVault; } // @dev create specified number of tokens and transfer to destination function createTokensInt(uint256 _tokens, address _destination) internal onlyOwner { uint256 tokens = _tokens * 10**uint256(decimals); totalSupply_ = totalSupply_.add(tokens); balances[_destination] = balances[_destination].add(tokens); emit Transfer(0x0, _destination, tokens); require(totalSupply_ <= HARD_CAP); } /// @dev vest Detail : second unit function vestTokensDetailInt( address _beneficiary, uint256 _startS, uint256 _cliffS, uint256 _durationS, bool _revocable, uint256 _tokensAmountInt) external onlyOwner { require(_beneficiary != address(0)); uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals); if(vestingOf[_beneficiary] == 0x0) { TokenVesting vesting = new TokenVesting(_beneficiary, _startS, _cliffS, _durationS, _revocable, owner); vestingOf[_beneficiary] = address(vesting); } require(this.transferFrom(reserveTokensVault, vestingOf[_beneficiary], tokensAmount)); } /// @dev vest StartAt : day unit function vestTokensStartAtInt( address _beneficiary, uint256 _tokensAmountInt, uint256 _startS, uint256 _afterDay, uint256 _cliffDay, uint256 _durationDay ) public onlyOwner { require(_beneficiary != address(0)); uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals); uint256 afterSec = _afterDay * daySecond; uint256 cliffSec = _cliffDay * daySecond; uint256 durationSec = _durationDay * daySecond; if(vestingOf[_beneficiary] == 0x0) { TokenVesting vesting = new TokenVesting(_beneficiary, _startS + afterSec, cliffSec, durationSec, true, owner); vestingOf[_beneficiary] = address(vesting); } require(this.transferFrom(reserveTokensVault, vestingOf[_beneficiary], tokensAmount)); } /// @dev vest function from now function vestTokensFromNowInt(address _beneficiary, uint256 _tokensAmountInt, uint256 _afterDay, uint256 _cliffDay, uint256 _durationDay ) public onlyOwner { vestTokensStartAtInt(_beneficiary, _tokensAmountInt, now, _afterDay, _cliffDay, _durationDay); } /// @dev vest the sale contributor tokens for 100 days, 1% gradual release function vestCmdNow1PercentInt(address _beneficiary, uint256 _tokensAmountInt) external onlyOwner { vestTokensFromNowInt(_beneficiary, _tokensAmountInt, 0, 0, unlock100Days); } /// @dev vest the sale contributor tokens for 100 days, 1% gradual release after 3 month later, no cliff function vestCmd3Month1PercentInt(address _beneficiary, uint256 _tokensAmountInt) external onlyOwner { vestTokensFromNowInt(_beneficiary, _tokensAmountInt, lock90Days, 0, unlock100Days); } /// @dev vest the sale contributor tokens 100% release after 1 year function vestCmd1YearInstantInt(address _beneficiary, uint256 _tokensAmountInt) external onlyOwner { vestTokensFromNowInt(_beneficiary, _tokensAmountInt, 0, lock365Days, lock365Days); } /// @dev releases vested tokens for the caller's own address function releaseVestedTokens() external { releaseVestedTokensFor(msg.sender); } /// @dev releases vested tokens for the specified address. /// Can be called by anyone for any address. function releaseVestedTokensFor(address _owner) public { TokenVesting(vestingOf[_owner]).release(this); } /// @dev check the vested balance for an address function lockedBalanceOf(address _owner) public view returns (uint256) { return balances[vestingOf[_owner]]; } /// @dev check the locked but releaseable balance of an owner function releaseableBalanceOf(address _owner) public view returns (uint256) { if (vestingOf[_owner] == address(0) ) { return 0; } else { return TokenVesting(vestingOf[_owner]).releasableAmount(this); } } /// @dev revoke vested tokens for the specified address. /// Tokens already vested remain in the contract, the rest are returned to the owner. function revokeVestedTokensFor(address _owner) public onlyOwner { TokenVesting(vestingOf[_owner]).revoke(this); } /// @dev Create a ReserveTokenVault function makeReserveToVault() external onlyOwner { require(reserveTokensVault != address(0)); reserveTokensVault.fillUpAllowance(); } }
vest StartAt : day unit
function vestTokensStartAtInt( address _beneficiary, uint256 _tokensAmountInt, uint256 _startS, uint256 _afterDay, uint256 _cliffDay, uint256 _durationDay ) public onlyOwner { require(_beneficiary != address(0)); uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals); uint256 afterSec = _afterDay * daySecond; uint256 cliffSec = _cliffDay * daySecond; uint256 durationSec = _durationDay * daySecond; if(vestingOf[_beneficiary] == 0x0) { TokenVesting vesting = new TokenVesting(_beneficiary, _startS + afterSec, cliffSec, durationSec, true, owner); vestingOf[_beneficiary] = address(vesting); } require(this.transferFrom(reserveTokensVault, vestingOf[_beneficiary], tokensAmount)); }
618,581
pragma solidity ^0.7.5; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { (uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { (uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); (uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); (uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } pragma solidity 0.7.6; import "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "./vaults/StakingData.sol"; contract ITrustVaultFactory is Initializable { address[] internal _VaultProxies; mapping (address => bool) internal _AdminList; mapping (address => bool) internal _TrustedSigners; mapping(address => bool) internal _VaultStatus; address internal _roundDataImplementationAddress; address internal _stakeDataImplementationAddress; address internal _stakingDataAddress; address internal _burnAddress; address internal _governanceDistributionAddress; address internal _governanceTokenAddress; address internal _stakingCalculationAddress; function initialize( address admin, address trustedSigner, address roundDataImplementationAddress, address stakeDataImplementationAddress, address governanceTokenAddress, address stakingCalculationAddress ) initializer external { require(admin != address(0)); _AdminList[admin] = true; _AdminList[msg.sender] = true; _TrustedSigners[trustedSigner] = true; _roundDataImplementationAddress = roundDataImplementationAddress; _stakeDataImplementationAddress = stakeDataImplementationAddress; _governanceTokenAddress = governanceTokenAddress; _stakingCalculationAddress = stakingCalculationAddress; } modifier onlyAdmin() { require(_AdminList[msg.sender] == true, "Not Factory Admin"); _; } function createVault( address contractAddress, bytes memory data ) external onlyAdmin { TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy(contractAddress, msg.sender, data ); require(address(proxy) != address(0)); _VaultProxies.push(address(proxy)); _VaultStatus[address(proxy)] = true; StakingData stakingDataContract = StakingData(_stakingDataAddress); stakingDataContract.addVault(address(proxy)); } function getVaultaddresses() external view returns (address[] memory vaults, bool[] memory status) { vaults = _VaultProxies; status = new bool[](vaults.length); for(uint i = 0; i < vaults.length; i++){ status[i] = _VaultStatus[vaults[i]]; } return (vaults, status); } function pauseVault(address vaultAddress) external onlyAdmin { _VaultStatus[vaultAddress] = false; } function unPauseVault(address vaultAddress) external onlyAdmin { _VaultStatus[vaultAddress] = true; } function addAdminAddress(address newAddress) external onlyAdmin { require(_AdminList[newAddress] == false, "Already Admin"); _AdminList[newAddress] = true; } /** * @dev revoke admin */ function revokeAdminAddress(address newAddress) external onlyAdmin { require(msg.sender != newAddress); _AdminList[newAddress] = false; } function addTrustedSigner(address newAddress) external onlyAdmin{ require(_TrustedSigners[newAddress] == false); _TrustedSigners[newAddress] = true; } function isTrustedSignerAddress(address account) external view returns (bool) { return _TrustedSigners[account] == true; } function updateRoundDataImplementationAddress(address newAddress) external onlyAdmin { _roundDataImplementationAddress = newAddress; } function getRoundDataImplementationAddress() external view returns(address){ return _roundDataImplementationAddress; } function updateStakeDataImplementationAddress(address newAddress) external onlyAdmin { _stakeDataImplementationAddress = newAddress; } function getStakeDataImplementationAddress() external view returns(address){ return _stakeDataImplementationAddress; } function updateStakingDataAddress(address newAddress) external onlyAdmin { _stakingDataAddress = newAddress; } function getStakingDataAddress() external view returns(address){ return _stakingDataAddress; } function isStakingDataAddress(address addressToCheck) external view returns (bool) { return _stakingDataAddress == addressToCheck; } function updateBurnAddress(address newAddress) external onlyAdmin { _burnAddress = newAddress; } function getBurnAddress() external view returns(address){ return _burnAddress; } function isBurnAddress(address addressToCheck) external view returns (bool) { return _burnAddress == addressToCheck; } function updateGovernanceDistributionAddress(address newAddress) external onlyAdmin { _governanceDistributionAddress = newAddress; } function getGovernanceDistributionAddress() external view returns(address){ return _governanceDistributionAddress; } function updateGovernanceTokenAddress(address newAddress) external onlyAdmin { _governanceTokenAddress = newAddress; } function getGovernanceTokenAddress() external view returns(address){ return _governanceTokenAddress; } function updateStakingCalculationsAddress(address newAddress) external onlyAdmin { _stakingCalculationAddress = newAddress; } function getStakingCalculationsAddress() external view returns(address){ return _stakingCalculationAddress; } /** * @dev revoke admin */ function revokeTrustedSigner(address newAddress) external onlyAdmin { require(msg.sender != newAddress); _TrustedSigners[newAddress] = false; } function isAdmin() external view returns (bool) { return isAddressAdmin(msg.sender); } function isAddressAdmin(address account) public view returns (bool) { return _AdminList[account] == true; } function isActiveVault(address vaultAddress) external view returns (bool) { return _VaultStatus[vaultAddress] == true; } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; library ITrustVaultLib { using SafeMath for uint; struct RewardTokenRoundData{ address tokenAddress; uint amount; uint commissionAmount; uint tokenPerBlock; uint totalSupply; bool ignoreUnstakes; } struct RewardTokenRound{ mapping(address => RewardTokenRoundData) roundData; uint startBlock; uint endBlock; } struct AccountStaking { uint32 startRound; uint endDate; uint total; Staking[] stakes; } struct Staking { uint startTime; uint startBlock; uint amount; uint total; } struct UnStaking { address account; uint amount; uint startDateTime; uint startBlock; uint endBlock; } struct ClaimedReward { uint amount; uint lastClaimedRound; } function divider(uint numerator, uint denominator, uint precision) internal pure returns(uint) { return numerator*(uint(10)**uint(precision))/denominator; } function getUnstakingsForBlockRange( UnStaking[] memory unStakes, uint startBlock, uint endBlock) internal pure returns (uint){ // If we have bad data, no supply data or it starts after the block we are looking for then we can return zero if(endBlock < startBlock || unStakes.length == 0 || unStakes[0].startBlock > endBlock) { return 0; } uint lastIndex = unStakes.length - 1; uint diff = 0; uint stakeEnd; uint stakeStart; uint total; diff = 0; stakeEnd = 0; stakeStart = 0; //last index should now be in our range so loop through until all block numbers are covered while(lastIndex >= 0) { if( (unStakes[lastIndex].endBlock != 0 && unStakes[lastIndex].endBlock < startBlock) || unStakes[lastIndex].startBlock > endBlock) { if(lastIndex == 0){ break; } lastIndex = lastIndex.sub(1); continue; } stakeEnd = unStakes[lastIndex].endBlock == 0 ? endBlock : unStakes[lastIndex].endBlock; stakeEnd = (stakeEnd >= endBlock ? endBlock : stakeEnd); stakeStart = unStakes[lastIndex].startBlock < startBlock ? startBlock : unStakes[lastIndex].startBlock; diff = (stakeEnd == stakeStart ? 1 : stakeEnd.sub(stakeStart)); total = total.add(unStakes[lastIndex].amount.mul(diff)); if(lastIndex == 0){ break; } lastIndex = lastIndex.sub(1); } return total; } function getHoldingsForBlockRange( Staking[] memory stakes, uint startBlock, uint endBlock) internal pure returns (uint){ // If we have bad data, no supply data or it starts after the block we are looking for then we can return zero if(endBlock < startBlock || stakes.length == 0 || stakes[0].startBlock > endBlock){ return 0; } uint lastIndex = stakes.length - 1; uint diff; // If the last total supply is before the start we are looking for we can take the last value if(stakes[lastIndex].startBlock <= startBlock){ diff = endBlock.sub(startBlock) == 0 ? 1 : endBlock.sub(startBlock); return stakes[lastIndex].total.mul(diff); } // working our way back we need to get the first index that falls into our range // This could be large so need to think of a better way to get here while(lastIndex > 0 && stakes[lastIndex].startBlock > endBlock){ lastIndex = lastIndex.sub(1); } uint total; diff = 0; //last index should now be in our range so loop through until all block numbers are covered while(stakes[lastIndex].startBlock >= startBlock ) { diff = 1; if(stakes[lastIndex].startBlock <= startBlock){ diff = endBlock.sub(startBlock) == 0 ? 1 : endBlock.sub(startBlock); total = total.add(stakes[lastIndex].total.mul(diff)); break; } diff = endBlock.sub(stakes[lastIndex].startBlock) == 0 ? 1 : endBlock.sub(stakes[lastIndex].startBlock); total = total.add(stakes[lastIndex].total.mul(diff)); endBlock = stakes[lastIndex].startBlock; if(lastIndex == 0){ break; } lastIndex = lastIndex.sub(1); } // If the last total supply is before the start we are looking for we can take the last value if(stakes[lastIndex].startBlock <= startBlock && startBlock <= endBlock){ diff = endBlock.sub(startBlock) == 0 ? 1 : endBlock.sub(startBlock); total = total.add(stakes[lastIndex].total.mul(diff)); } return total; } function splitSignature(bytes memory sig) internal pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); } function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20CappedUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; contract iTrustGovernanceToken is ERC20CappedUpgradeable, OwnableUpgradeable, PausableUpgradeable { using SafeMathUpgradeable for uint; address internal _treasuryAddress; uint internal _yearOneSupply; uint internal _yearTwoSupply; uint internal _yearThreeSupply; uint internal _yearFourSupply; uint internal _yearFiveSupply; function initialize( address payable treasuryAddress, uint cap_, uint yearOneSupply, uint yearTwoSupply, uint yearThreeSupply, uint yearFourSupply, uint yearFiveSupply) initializer public { require(yearOneSupply.add(yearTwoSupply).add(yearThreeSupply).add(yearFourSupply).add(yearFiveSupply) == cap_); __ERC20_init("iTrust Governance Token", "$ITG"); __ERC20Capped_init(cap_); __Ownable_init(); __Pausable_init(); _treasuryAddress = treasuryAddress; _yearOneSupply = yearOneSupply; _yearTwoSupply = yearTwoSupply; _yearThreeSupply = yearThreeSupply; _yearFourSupply = yearFourSupply; _yearFiveSupply = yearFiveSupply; } function mintYearOne() external onlyOwner { require(totalSupply() == 0); _mint(_treasuryAddress, _yearOneSupply); } function mintYearTwo() external onlyOwner { require(totalSupply() == _yearOneSupply); _mint(_treasuryAddress, _yearTwoSupply); } function mintYearThree() external onlyOwner { require(totalSupply() == _yearOneSupply.add(_yearTwoSupply)); _mint(_treasuryAddress, _yearThreeSupply); } function mintYearFour() external onlyOwner { require(totalSupply() == _yearOneSupply.add(_yearTwoSupply).add(_yearThreeSupply)); _mint(_treasuryAddress, _yearFourSupply); } function mintYearFive() external onlyOwner { require(totalSupply() == _yearOneSupply.add(_yearTwoSupply).add(_yearThreeSupply).add(_yearFourSupply)); _mint(_treasuryAddress, _yearFiveSupply); } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import { ITrustVaultLib as VaultLib } from "./../libraries/ItrustVaultLib.sol"; abstract contract BaseContract is Initializable, ContextUpgradeable { uint8 internal constant FALSE = 0; uint8 internal constant TRUE = 1; uint8 internal _locked; address internal _iTrustFactoryAddress; mapping (address => uint32) internal _CurrentRoundNumbers; mapping (address => uint) internal _TotalUnstakedWnxm; mapping (address => uint[]) internal _TotalSupplyKeys; mapping (address => uint[]) internal _TotalUnstakingKeys; mapping (address => uint[]) internal _TotalSupplyForDayKeys; mapping (address => address[]) public totalRewardTokenAddresses; mapping (address => address[]) internal _UnstakingAddresses; mapping (address => address[]) internal _AccountStakesAddresses; mapping (address => VaultLib.UnStaking[]) internal _UnstakingRequests; mapping (address => mapping (address => uint32)) internal _RewardStartingRounds; mapping (address => mapping (address => VaultLib.AccountStaking)) internal _AccountStakes; mapping (address => mapping (address => VaultLib.UnStaking[])) internal _AccountUnstakings; mapping (address => mapping (address => uint8)) internal _RewardTokens; mapping (address => mapping (address => uint)) internal _AccountUnstakingTotals; mapping (address => mapping (address => uint)) internal _AccountUnstakedTotals; mapping (address => mapping (uint => uint)) internal _TotalSupplyHistory; mapping (address => mapping (address => mapping (address => VaultLib.ClaimedReward))) internal _AccountRewards; mapping (address => mapping (uint => VaultLib.RewardTokenRound)) internal _Rounds; mapping (address => mapping (uint => uint)) internal _TotalSupplyForDayHistory; mapping (address => mapping (uint => VaultLib.UnStaking)) internal _TotalUnstakingHistory; function _nonReentrant() internal view { require(_locked == FALSE); } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./../iTrustVaultFactory.sol"; import "./../tokens/iTrustGovernanceToken.sol"; import "./Vault.sol"; import { BokkyPooBahsDateTimeLibrary as DateTimeLib } from "./../3rdParty/BokkyPooBahsDateTimeLibrary.sol"; contract GovernanceDistribution is Initializable, ContextUpgradeable { using SafeMathUpgradeable for uint; uint8 internal constant FALSE = 0; uint8 internal constant TRUE = 1; uint8 internal _locked; uint internal _tokenPerHour; address internal _iTrustFactoryAddress; uint[] internal _totalSupplyKeys; mapping (uint => uint) internal _totalSupplyHistory; mapping (address => uint[]) internal _totalStakedKeys; mapping (address => mapping (uint => uint)) internal _totalStakedHistory; mapping (address => uint) internal _lastClaimedTimes; mapping(address => mapping(string => bool)) _UsedNonces; function initialize( address iTrustFactoryAddress, uint tokenPerDay ) initializer external { _iTrustFactoryAddress = iTrustFactoryAddress; _tokenPerHour = tokenPerDay.div(24); } /** * Public functions */ function totalStaked(address account) external view returns(uint) { _onlyAdmin(); if(_totalStakedKeys[account].length == 0){ return 0; } return _totalStakedHistory[account][_totalStakedKeys[account][_totalStakedKeys[account].length.sub(1)]]; } function totalSupply() external view returns(uint) { _onlyAdmin(); if(_totalSupplyKeys.length == 0){ return 0; } return _totalSupplyHistory[_totalSupplyKeys[_totalSupplyKeys.length.sub(1)]]; } function calculateRewards() external view returns(uint amount, uint claimedUntil) { (amount, claimedUntil) = _calculateRewards(_msgSender()); return(amount, claimedUntil); } function calculateRewardsForAccount(address account) external view returns(uint amount, uint claimedUntil) { _isTrustedSigner(_msgSender()); (amount, claimedUntil) = _calculateRewards(account); return(amount, claimedUntil); } function removeStake(address account, uint value) external { _validateStakingDataAddress(); require(_totalStakedKeys[account].length != 0); uint currentTime = _getStartOfHourTimeStamp(block.timestamp); uint lastStakedIndex = _totalStakedKeys[account][_totalStakedKeys[account].length.sub(1)]; if(lastStakedIndex > currentTime){ if(_totalStakedKeys[account].length == 1 || _totalStakedKeys[account][_totalStakedKeys[account].length.sub(2)] != currentTime){ _totalStakedKeys[account][_totalStakedKeys[account].length.sub(1)] = currentTime; _totalStakedHistory[account][currentTime] = _totalStakedKeys[account].length == 1 ? 0 : _totalStakedHistory[account][_totalStakedKeys[account][_totalStakedKeys[account].length.sub(2)]]; _totalStakedKeys[account].push(lastStakedIndex); } _totalStakedHistory[account][lastStakedIndex] = _totalStakedHistory[account][lastStakedIndex].sub(value); lastStakedIndex = _totalStakedKeys[account][_totalStakedKeys[account].length.sub(2)]; } require(value <= _totalStakedHistory[account][lastStakedIndex]); uint newValue = _totalStakedHistory[account][lastStakedIndex].sub(value); if(lastStakedIndex != currentTime){ _totalStakedKeys[account].push(currentTime); } _totalStakedHistory[account][currentTime] = newValue; require(_totalSupplyKeys.length != 0); uint lastSupplyIndex = _totalSupplyKeys[_totalSupplyKeys.length.sub(1)]; if(lastSupplyIndex > currentTime){ if(_totalSupplyKeys.length == 1 || _totalSupplyKeys[_totalSupplyKeys.length.sub(2)] != currentTime){ _totalSupplyKeys[_totalSupplyKeys.length.sub(1)] = currentTime; _totalSupplyHistory[currentTime] = _totalSupplyKeys.length == 1 ? 0 : _totalSupplyHistory[_totalSupplyKeys[_totalSupplyKeys.length.sub(2)]]; _totalSupplyKeys.push(lastSupplyIndex); } _totalSupplyHistory[lastSupplyIndex] = _totalSupplyHistory[lastSupplyIndex].sub(value); lastSupplyIndex = _totalSupplyKeys[_totalSupplyKeys.length.sub(2)]; } if(lastSupplyIndex != currentTime){ _totalSupplyKeys.push(currentTime); } _totalSupplyHistory[currentTime] = _totalSupplyHistory[lastSupplyIndex].sub(value); } function addStake(address account, uint value) external { _validateStakingDataAddress(); uint currentTime = _getStartOfNextHourTimeStamp(block.timestamp); if(_totalStakedKeys[account].length == 0){ _totalStakedKeys[account].push(currentTime); _totalStakedHistory[account][currentTime] = value; } else { uint lastStakedIndex = _totalStakedKeys[account].length.sub(1); uint lastTimestamp = _totalStakedKeys[account][lastStakedIndex]; if(lastTimestamp != currentTime){ _totalStakedKeys[account].push(currentTime); } _totalStakedHistory[account][currentTime] = _totalStakedHistory[account][lastTimestamp].add(value); } if(_totalSupplyKeys.length == 0){ _totalSupplyKeys.push(currentTime); _totalSupplyHistory[currentTime] = value; } else { uint lastSupplyIndex = _totalSupplyKeys.length.sub(1); uint lastSupplyTimestamp = _totalSupplyKeys[lastSupplyIndex]; if(lastSupplyTimestamp != currentTime){ _totalSupplyKeys.push(currentTime); } _totalSupplyHistory[currentTime] = _totalSupplyHistory[lastSupplyTimestamp].add(value); } } function withdrawTokens(uint amount, uint claimedUntil, string memory nonce, bytes memory sig) external { _nonReentrant(); require(amount != 0); require(claimedUntil != 0); require(!_UsedNonces[_msgSender()][nonce]); _locked = TRUE; bytes32 abiBytes = keccak256(abi.encodePacked(_msgSender(), amount, claimedUntil, nonce, address(this))); bytes32 message = _prefixed(abiBytes); address signer = _recoverSigner(message, sig); _isTrustedSigner(signer); _lastClaimedTimes[_msgSender()] = claimedUntil; _UsedNonces[_msgSender()][nonce] = true; _getiTrustGovernanceToken().transfer(_msgSender(), amount); _locked = FALSE; } /** * Internal functions */ function _calculateRewards(address account) internal view returns(uint, uint) { if(_totalStakedKeys[account].length == 0 || _totalSupplyKeys.length == 0){ return (0, 0); } uint currentTime = _getStartOfHourTimeStamp(block.timestamp); uint claimedUntil = _getStartOfHourTimeStamp(block.timestamp); uint lastClaimedTimestamp = _lastClaimedTimes[account]; // if 0 they have never staked go back to the first stake if(lastClaimedTimestamp == 0){ lastClaimedTimestamp = _totalStakedKeys[account][0]; } uint totalRewards = 0; uint stakedStartingIndex = _totalStakedKeys[account].length.sub(1); uint supplyStartingIndex = _totalSupplyKeys.length.sub(1); uint hourReward = 0; while(currentTime > lastClaimedTimestamp) { (hourReward, stakedStartingIndex, supplyStartingIndex) = _getTotalRewardHour(account, currentTime, stakedStartingIndex, supplyStartingIndex); totalRewards = totalRewards.add(hourReward); currentTime = DateTimeLib.subHours(currentTime, 1); } return (totalRewards, claimedUntil); } function _getTotalRewardHour(address account, uint hourTimestamp, uint stakedStartingIndex, uint supplyStartingIndex) internal view returns(uint, uint, uint) { (uint totalStakedForHour, uint returnedStakedStartingIndex) = _getTotalStakedForHour(account, hourTimestamp, stakedStartingIndex); (uint totalSupplyForHour, uint returnedSupplyStartingIndex) = _getTotalSupplyForHour(hourTimestamp, supplyStartingIndex); uint reward = 0; if(totalSupplyForHour > 0 && totalStakedForHour > 0){ uint govTokenPerTokenPerHour = _divider(_tokenPerHour, totalSupplyForHour, 18); // _tokenPerHour.div(totalSupplyForHour); reward = reward.add(totalStakedForHour.mul(govTokenPerTokenPerHour).div(1e18)); } return (reward, returnedStakedStartingIndex, returnedSupplyStartingIndex); } function _getTotalStakedForHour(address account, uint hourTimestamp, uint startingIndex) internal view returns(uint, uint) { while(startingIndex != 0 && hourTimestamp <= _totalStakedKeys[account][startingIndex]) { startingIndex = startingIndex.sub(1); } // We never got far enough back before hitting 0, meaning we staked after the hour we are looking up if(hourTimestamp < _totalStakedKeys[account][startingIndex]){ return (0, startingIndex); } return (_totalStakedHistory[account][_totalStakedKeys[account][startingIndex]], startingIndex); } function _getTotalSupplyForHour(uint hourTimestamp, uint startingIndex) internal view returns(uint, uint) { while(startingIndex != 0 && hourTimestamp <= _totalSupplyKeys[startingIndex]) { startingIndex = startingIndex.sub(1); } // We never got far enough back before hitting 0, meaning we staked after the hour we are looking up if(hourTimestamp < _totalSupplyKeys[startingIndex]){ return (0, startingIndex); } return (_totalSupplyHistory[_totalSupplyKeys[startingIndex]], startingIndex); } function _getStartOfHourTimeStamp(uint nowDateTime) internal pure returns (uint) { (uint year, uint month, uint day, uint hour, ,) = DateTimeLib.timestampToDateTime(nowDateTime); return DateTimeLib.timestampFromDateTime(year, month, day, hour, 0, 0); } function _getStartOfNextHourTimeStamp(uint nowDateTime) internal pure returns (uint) { (uint year, uint month, uint day, uint hour, ,) = DateTimeLib.timestampToDateTime(nowDateTime); return DateTimeLib.timestampFromDateTime(year, month, day, hour.add(1), 0, 0); } function _getITrustVaultFactory() internal view returns(ITrustVaultFactory) { return ITrustVaultFactory(_iTrustFactoryAddress); } function _governanceTokenAddress() internal view returns(address) { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); return vaultFactory.getGovernanceTokenAddress(); } function _getiTrustGovernanceToken() internal view returns(iTrustGovernanceToken) { return iTrustGovernanceToken(_governanceTokenAddress()); } function _divider(uint numerator, uint denominator, uint precision) internal pure returns(uint) { return numerator*(uint(10)**uint(precision))/denominator; } /** * Validate functions */ function _nonReentrant() internal view { require(_locked == FALSE); } function _onlyAdmin() internal view { require( _getITrustVaultFactory().isAddressAdmin(_msgSender()), "Not admin" ); } function _isTrustedSigner(address signer) internal view { require( _getITrustVaultFactory().isTrustedSignerAddress(signer), "Not trusted signer" ); } function _validateStakingDataAddress() internal view { _validateStakingDataAddress(_msgSender()); } function _validateStakingDataAddress(address contractAddress) internal view { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); require(vaultFactory.isStakingDataAddress(contractAddress)); } function _splitSignature(bytes memory sig) internal pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } function _recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = _splitSignature(sig); return ecrecover(message, v, r, s); } function _prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../iTrustVaultFactory.sol"; import "./BaseContract.sol"; import "./StakingDataController/StakeData.sol"; import { ITrustVaultLib as VaultLib } from "./../libraries/ItrustVaultLib.sol"; contract StakingCalculation { using SafeMath for uint; // function getRoundDataForAccount( // VaultLib.Staking[] memory stakes, // VaultLib.UnStaking[] memory unstakes, // uint startBlock, // uint endBlock) external pure // returns (uint totalHoldings, uint[] memory stakeBlocks, uint[] memory stakeAmounts, uint[] memory unstakeStartBlocks, uint[] memory unstakeEndBlocks, uint[] memory unstakeAmounts) // { // totalHoldings = VaultLib.getHoldingsForBlockRange(stakes, startBlock, endBlock); // (stakeBlocks, stakeAmounts) = VaultLib.getRoundDataStakesForAccount(stakes, startBlock, endBlock); // (unstakeStartBlocks, unstakeEndBlocks, unstakeAmounts) = VaultLib.getRoundDataUnstakesForAccount(unstakes, startBlock, endBlock); // return (totalHoldings, stakeBlocks, stakeAmounts, unstakeStartBlocks, unstakeEndBlocks, unstakeAmounts); // } function getUnstakingsForBlockRange( VaultLib.UnStaking[] memory unStakes, uint startBlock, uint endBlock) external pure returns (uint){ return VaultLib.getUnstakingsForBlockRange( unStakes, startBlock, endBlock ); } function getHoldingsForBlockRange( VaultLib.Staking[] memory stakes, uint startBlock, uint endBlock) external pure returns (uint){ return VaultLib.getHoldingsForBlockRange( stakes, startBlock, endBlock); } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./../iTrustVaultFactory.sol"; import "./BaseContract.sol"; import "./StakingDataController/StakeData.sol"; import "./StakingCalculation.sol"; import "./StakingDataController/RoundData.sol"; contract StakingData is BaseContract { using SafeMathUpgradeable for uint; function initialize( address iTrustFactoryAddress ) initializer external { _iTrustFactoryAddress = iTrustFactoryAddress; _locked = FALSE; } /** * Public functions */ function _getTotalSupplyForBlockRange(address vaultAddress, uint endBlock, uint startBlock) internal returns(uint) { (bool success, bytes memory result) = _stakeDataImplementationAddress() .delegatecall( abi.encodeWithSelector( StakeData.getTotalSupplyForBlockRange.selector, vaultAddress, endBlock, startBlock ) ); require(success); return abi.decode(result, (uint256)); } function _getTotalUnstakingsForBlockRange(address vaultAddress, uint endBlock, uint startBlock) internal returns(uint) { (bool success, bytes memory result) = _stakeDataImplementationAddress() .delegatecall( abi.encodeWithSelector( StakeData.getTotalUnstakingsForBlockRange.selector, vaultAddress, endBlock, startBlock ) ); require(success); return abi.decode(result, (uint256)); } function addVault(address vaultAddress) external { _validateFactory(); _CurrentRoundNumbers[vaultAddress] = 1; _Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].startBlock = block.number; _updateTotalSupplyForBlock(0); } function endRound(address[] calldata tokens, uint[] calldata tokenAmounts, bool[] calldata ignoreUnstakes, uint commission) external returns(bool) { _validateVault(); address vaultAddress = _vaultAddress(); uint startBlock = _Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].startBlock; (bool result, ) = _roundDataImplementationAddress() .delegatecall( abi.encodeWithSelector( RoundData.endRound.selector, vaultAddress, tokens, tokenAmounts, ignoreUnstakes, _getTotalSupplyForBlockRange( vaultAddress, block.number, startBlock ), _getTotalUnstakingsForBlockRange( vaultAddress, block.number, startBlock ), commission) ); require(result); return true; } function getCurrentRoundData() external view returns(uint, uint, uint) { _validateVault(); return _getRoundDataForAddress(_vaultAddress(), _CurrentRoundNumbers[_vaultAddress()]); } function getRoundData(uint roundNumberIn) external view returns(uint, uint, uint) { _validateVault(); return _getRoundDataForAddress(_vaultAddress(), roundNumberIn); } function getRoundRewards(uint roundNumber) external view returns( address[] memory rewardTokens, uint[] memory rewardAmounts, uint[] memory commisionAmounts, uint[] memory tokenPerBlock, uint[] memory totalSupply ) { _validateVault(); return _getRoundRewardsForAddress(_vaultAddress(), roundNumber); } function startUnstake(address account, uint256 value) external returns(bool) { _validateVault(); (bool result, ) = _stakeDataImplementationAddress() .delegatecall(abi.encodeWithSelector(StakeData.startUnstakeForAddress.selector, _vaultAddress(), account, value)); return result; } function getAccountStakes(address account) external view returns( uint stakingTotal, uint unStakingTotal, uint[] memory unStakingAmounts, uint[] memory unStakingStarts ) { _validateVault(); return _getAccountStakesForAddress(_vaultAddress(), account); } function getAccountStakingTotal(address account) external view returns (uint) { _validateVault(); return _AccountStakes[_vaultAddress()][account].total.sub(_AccountUnstakingTotals[_vaultAddress()][account]); } function getAllAcountUnstakes() external view returns (address[] memory accounts, uint[] memory startTimes, uint[] memory values) { _validateVault(); return _getAllAcountUnstakesForAddress(_vaultAddress()); } function getAccountUnstakedTotal(address account) external view returns (uint) { _validateVault(); return _AccountUnstakedTotals[_vaultAddress()][account]; } function authoriseUnstakes(address[] memory account, uint[] memory timestamp) external returns(bool) { _validateVault(); require(account.length <= 10); for(uint8 i = 0; i < account.length; i++) { _authoriseUnstake(_vaultAddress(), account[i], timestamp[i]); } return true; } function withdrawUnstakedToken(address account, uint amount) external returns(bool) { _validateVault(); _nonReentrant(); _locked = TRUE; address vaultAddress = _vaultAddress(); require(_AccountUnstakedTotals[vaultAddress][account] > 0); require(amount <= _AccountUnstakedTotals[vaultAddress][account]); _AccountUnstakedTotals[vaultAddress][account] = _AccountUnstakedTotals[vaultAddress][account].sub(amount); _TotalUnstakedWnxm[vaultAddress] = _TotalUnstakedWnxm[vaultAddress].sub(amount); _locked = FALSE; return true; } function createStake(uint amount, address account) external returns(bool) { _validateVault(); (bool result, ) = _stakeDataImplementationAddress() .delegatecall(abi.encodeWithSelector(StakeData.createStake.selector,_vaultAddress(),amount,account)); return result; } function removeStake(uint amount, address account) external returns(bool) { _validateVault(); (bool result, ) = _stakeDataImplementationAddress() .delegatecall(abi.encodeWithSelector(StakeData.removeStake.selector, _vaultAddress(), amount, account)); return result; } function calculateRewards(address account) external view returns (address[] memory rewardTokens, uint[] memory rewards) { _validateVault(); return _calculateRewards(account); } function withdrawRewards(address account, address[] memory rewardTokens, uint[] memory rewards) external returns(bool) { _validateVault(); _nonReentrant(); _locked = TRUE; _withdrawRewards(_vaultAddress(), rewardTokens, rewards, account); _locked = FALSE; return true; } function updateTotalSupplyForDayAndBlock(uint totalSupply) external returns(bool) { _validateVault(); _updateTotalSupplyForBlock(totalSupply); return true; } function getTotalSupplyForAccountBlock(address vaultAddress, uint date) external view returns(uint) { _validateBurnContract(); return _getTotalSupplyForAccountBlock(vaultAddress, date); } function getHoldingsForIndexAndBlockForVault(address vaultAddress, uint index, uint blockNumber) external view returns(address indexAddress, uint addressHoldings) { _validateBurnContract(); return _getHoldingsForIndexAndBlock(vaultAddress, index, blockNumber); } function getNumberOfStakingAddressesForVault(address vaultAddress) external view returns(uint) { _validateBurnContract(); return _AccountStakesAddresses[vaultAddress].length; } /** * Internal functions */ function _getHoldingsForIndexAndBlock(address vaultAddress, uint index, uint blockNumber) internal view returns(address indexAddress, uint addressHoldings) { require(_AccountStakesAddresses[vaultAddress].length - 1 >= index); indexAddress = _AccountStakesAddresses[vaultAddress][index]; bytes memory data = abi.encodeWithSelector(StakingCalculation.getHoldingsForBlockRange.selector, _AccountStakes[vaultAddress][indexAddress].stakes, blockNumber, blockNumber); (, bytes memory resultData) = _stakingCalculationsAddress().staticcall(data); addressHoldings = abi.decode(resultData, (uint256)); return(indexAddress, addressHoldings); } function _getTotalSupplyForAccountBlock(address vaultAddress, uint blockNumber) internal view returns(uint) { uint index = _getIndexForBlock(vaultAddress, blockNumber, 0); return _TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][index]]; } function _authoriseUnstake(address vaultAddress, address account, uint timestamp) internal { (bool result, ) = _stakeDataImplementationAddress() .delegatecall(abi.encodeWithSelector(StakeData.authoriseUnstake.selector, vaultAddress, account, timestamp)); require(result); } function _updateTotalSupplyForBlock(uint totalSupply) public returns(bool) { if(_TotalSupplyHistory[_vaultAddress()][block.number] == 0){ // Assumes there will never be 0, could use the array itself to check will look at this again _TotalSupplyKeys[_vaultAddress()].push(block.number); } _TotalSupplyHistory[_vaultAddress()][block.number] = totalSupply; return true; } function _getRoundDataForAddress(address vaultAddress, uint roundNumberIn) internal view returns(uint roundNumber, uint startBlock, uint endBlock) { roundNumber = roundNumberIn; startBlock = _Rounds[vaultAddress][roundNumber].startBlock; endBlock = _Rounds[vaultAddress][roundNumber].endBlock; return( roundNumber, startBlock, endBlock ); } function _getRoundRewardsForAddress(address vaultAddress, uint roundNumber) internal view returns( address[] memory rewardTokens, uint[] memory rewardAmounts, uint[] memory commissionAmounts, uint[] memory tokenPerBlock, uint[] memory totalSupply ) { rewardTokens = new address[](totalRewardTokenAddresses[vaultAddress].length); rewardAmounts = new uint[](totalRewardTokenAddresses[vaultAddress].length); commissionAmounts = new uint[](totalRewardTokenAddresses[vaultAddress].length); tokenPerBlock = new uint[](totalRewardTokenAddresses[vaultAddress].length); totalSupply = new uint[](totalRewardTokenAddresses[vaultAddress].length); for(uint i = 0; i < totalRewardTokenAddresses[vaultAddress].length; i++){ rewardTokens[i] = totalRewardTokenAddresses[vaultAddress][i]; rewardAmounts[i] = _Rounds[vaultAddress][roundNumber].roundData[totalRewardTokenAddresses[vaultAddress][i]].amount; commissionAmounts[i] = _Rounds[vaultAddress][roundNumber].roundData[totalRewardTokenAddresses[vaultAddress][i]].commissionAmount; tokenPerBlock[i] = _Rounds[vaultAddress][roundNumber].roundData[totalRewardTokenAddresses[vaultAddress][i]].tokenPerBlock; totalSupply[i] = _Rounds[vaultAddress][roundNumber].roundData[totalRewardTokenAddresses[vaultAddress][i]].totalSupply; } return( rewardTokens, rewardAmounts, commissionAmounts, tokenPerBlock, totalSupply ); } function _getIndexForBlock(address vaultAddress, uint startBlock, uint startIndex) internal view returns(uint) { uint i = startIndex == 0 ? _TotalSupplyKeys[vaultAddress].length.sub(1) : startIndex; uint blockForIndex = _TotalSupplyKeys[vaultAddress][i]; if(_TotalSupplyKeys[vaultAddress][0] > startBlock){ return 0; } if(blockForIndex < startBlock){ return i; } while(blockForIndex > startBlock){ i = i.sub(1); blockForIndex = _TotalSupplyKeys[vaultAddress][i]; } return i; } function _getAccountStakesForAddress(address vaultAddress, address account) internal view returns( uint stakingTotal, uint unStakingTotal, uint[] memory unStakingAmounts, uint[] memory unStakingStarts ) { unStakingAmounts = new uint[](_AccountUnstakings[vaultAddress][account].length); unStakingStarts = new uint[](_AccountUnstakings[vaultAddress][account].length); for(uint i = 0; i < _AccountUnstakings[vaultAddress][account].length; i++){ if(_AccountUnstakings[vaultAddress][account][i].endBlock == 0){ unStakingAmounts[i] = _AccountUnstakings[vaultAddress][account][i].amount; unStakingStarts[i] = _AccountUnstakings[vaultAddress][account][i].startDateTime; } } return( _AccountStakes[vaultAddress][account].total.sub(_AccountUnstakingTotals[vaultAddress][account]), _AccountUnstakingTotals[vaultAddress][account], unStakingAmounts, unStakingStarts ); } function _getAllAcountUnstakesForAddress(address vaultAddress) internal view returns (address[] memory accounts, uint[] memory startTimes, uint[] memory values) { accounts = new address[](_UnstakingRequests[vaultAddress].length); startTimes = new uint[](_UnstakingRequests[vaultAddress].length); values = new uint[](_UnstakingRequests[vaultAddress].length); for(uint i = 0; i < _UnstakingRequests[vaultAddress].length; i++) { if(_UnstakingRequests[vaultAddress][i].endBlock == 0 ) { accounts[i] = _UnstakingRequests[vaultAddress][i].account; startTimes[i] = _UnstakingRequests[vaultAddress][i].startDateTime; values[i] = _UnstakingRequests[vaultAddress][i].amount; } } return(accounts, startTimes, values); } function getUnstakedWxnmTotal() external view returns(uint total) { _validateVault(); total = _TotalUnstakedWnxm[_vaultAddress()]; } function _calculateRewards(address account) internal view returns (address[] memory rewardTokens, uint[] memory rewards) { rewardTokens = totalRewardTokenAddresses[_vaultAddress()]; rewards = new uint[](rewardTokens.length); for(uint x = 0; x < totalRewardTokenAddresses[_vaultAddress()].length; x++){ (rewards[x]) = _calculateReward(_vaultAddress(), account, rewardTokens[x]); rewards[x] = rewards[x].div(1 ether); } return (rewardTokens, rewards); } function _calculateReward(address vaultAddress, address account, address rewardTokenAddress) internal view returns (uint reward){ VaultLib.ClaimedReward memory claimedReward = _AccountRewards[vaultAddress][account][rewardTokenAddress]; if(_RewardStartingRounds[vaultAddress][rewardTokenAddress] == 0){ return(0); } uint futureRoundNumber = _CurrentRoundNumbers[vaultAddress] - 1;// one off as the current hasnt closed address calcContract = _stakingCalculationsAddress(); while(claimedReward.lastClaimedRound < futureRoundNumber && _RewardStartingRounds[vaultAddress][rewardTokenAddress] <= futureRoundNumber && futureRoundNumber != 0 ) { if(_Rounds[vaultAddress][futureRoundNumber].roundData[rewardTokenAddress].amount == 0){ futureRoundNumber--; continue; } (, bytes memory resultData) = calcContract.staticcall(abi.encodeWithSignature( "getHoldingsForBlockRange((uint256,uint256,uint256,uint256)[],uint256,uint256)", _AccountStakes[vaultAddress][account].stakes, _Rounds[vaultAddress][futureRoundNumber].startBlock, _Rounds[vaultAddress][futureRoundNumber].endBlock )); uint holdingsForRound = abi.decode(resultData, (uint256)); if (!(_Rounds[vaultAddress][futureRoundNumber].roundData[rewardTokenAddress].ignoreUnstakes)) { (, bytes memory unstakedResultData) = calcContract.staticcall(abi.encodeWithSignature( "getUnstakingsForBlockRange((address,uint256,uint256,uint256,uint256)[],uint256,uint256)", _AccountUnstakings[vaultAddress][account], _Rounds[vaultAddress][futureRoundNumber].startBlock, _Rounds[vaultAddress][futureRoundNumber].endBlock )); holdingsForRound = holdingsForRound.sub(abi.decode(unstakedResultData, (uint256))); } holdingsForRound = VaultLib.divider( holdingsForRound, _Rounds[vaultAddress][futureRoundNumber].roundData[rewardTokenAddress].totalSupply, 18) .mul(_Rounds[vaultAddress][futureRoundNumber].roundData[rewardTokenAddress].amount); reward = reward.add(holdingsForRound); futureRoundNumber--; } return (reward); } function _withdrawRewards(address vaultAddress, address[] memory rewardTokens, uint[] memory rewards, address account) internal { for (uint x = 0; x < rewardTokens.length; x++){ _AccountRewards[vaultAddress][account][rewardTokens[x]].amount = _AccountRewards[vaultAddress][account][rewardTokens[x]].amount + rewards[x]; _AccountRewards[vaultAddress][account][rewardTokens[x]].lastClaimedRound = _CurrentRoundNumbers[vaultAddress] - 1; } } function _vaultAddress() internal view returns(address) { return _msgSender(); } function _roundDataImplementationAddress() internal view returns(address) { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); return vaultFactory.getRoundDataImplementationAddress(); } function _stakeDataImplementationAddress() internal view returns(address) { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); return vaultFactory.getStakeDataImplementationAddress(); } function _stakingCalculationsAddress() internal view returns(address) { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); return address(vaultFactory.getStakingCalculationsAddress()); } /** * Validate functions */ function _validateVault() internal view { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); require(vaultFactory.isActiveVault(_vaultAddress())); } function _validateBurnContract() internal view { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); require(vaultFactory.isBurnAddress(_msgSender())); } function _validateFactory() internal view { require(_msgSender() == _iTrustFactoryAddress); } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./../BaseContract.sol"; contract RoundData is BaseContract { using SafeMathUpgradeable for uint; function endRound( address vaultAddress, address[] memory tokens, uint[] memory tokenAmounts, bool[] memory ignoreUnstakes, uint totalSupplyForBlockRange, uint totalUnstakings, uint commissionValue) external { require( _Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].startBlock < block.number); uint32 roundNumber = _CurrentRoundNumbers[vaultAddress]; uint rewardAmount; uint commissionAmount; uint tokensPerBlock; //Amoun for (uint i=0; i < tokens.length; i++) { rewardAmount = tokenAmounts[i].sub(tokenAmounts[i].mul(commissionValue).div(10000)); commissionAmount = tokenAmounts[i].mul(commissionValue).div(10000); tokensPerBlock = VaultLib.divider(rewardAmount, _getAdjustedTotalSupply(totalSupplyForBlockRange, totalUnstakings, ignoreUnstakes[i]), 18); VaultLib.RewardTokenRoundData memory tokenData = VaultLib.RewardTokenRoundData( { tokenAddress: tokens[i], amount: rewardAmount, commissionAmount: commissionAmount, tokenPerBlock: tokensPerBlock,//.div(1e18), totalSupply: _getAdjustedTotalSupply(totalSupplyForBlockRange, totalUnstakings, ignoreUnstakes[i]), ignoreUnstakes: ignoreUnstakes[i] } ); _Rounds[vaultAddress][roundNumber].roundData[tokens[i]] = tokenData; if(_RewardTokens[vaultAddress][tokens[i]] != TRUE){ _RewardStartingRounds[vaultAddress][tokens[i]] = roundNumber; totalRewardTokenAddresses[vaultAddress].push(tokens[i]); _RewardTokens[vaultAddress][tokens[i]] = TRUE; } } //do this last _Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].endBlock = block.number; _CurrentRoundNumbers[vaultAddress]++; _Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].startBlock = block.number; } function _getAdjustedTotalSupply(uint totalSupply, uint totalUnstaking, bool ignoreUnstaking) internal pure returns(uint) { if(ignoreUnstaking) { return totalSupply; } return (totalUnstaking > totalSupply ? 0 : totalSupply.sub(totalUnstaking)); } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./../BaseContract.sol"; import "./../GovernanceDistribution.sol"; contract StakeData is BaseContract { using SafeMathUpgradeable for uint; function startUnstakeForAddress(address vaultAddress, address account, uint256 value) external { require( ( _AccountStakes[vaultAddress][account].total.sub(_AccountUnstakingTotals[vaultAddress][account]) ) >= value); _AccountUnstakingTotals[vaultAddress][account] =_AccountUnstakingTotals[vaultAddress][account].add(value); VaultLib.UnStaking memory unstaking = VaultLib.UnStaking(account, value, block.timestamp, block.number, 0 ); _AccountUnstakings[vaultAddress][account].push(unstaking); _UnstakingRequests[vaultAddress].push(unstaking); _UnstakingAddresses[vaultAddress].push(account); _TotalUnstakingKeys[vaultAddress].push(block.number); _TotalUnstakingHistory[vaultAddress][block.number] = unstaking; } function authoriseUnstake(address vaultAddress, address account, uint timestamp) external { uint amount = 0; for(uint i = 0; i < _AccountUnstakings[vaultAddress][account].length; i++){ if(_AccountUnstakings[vaultAddress][account][i].startDateTime == timestamp) { amount = _AccountUnstakings[vaultAddress][account][i].amount; _AccountUnstakedTotals[vaultAddress][account] = _AccountUnstakedTotals[vaultAddress][account] + amount; _AccountUnstakings[vaultAddress][account][i].endBlock = block.number; _AccountUnstakingTotals[vaultAddress][account] = _AccountUnstakingTotals[vaultAddress][account] - amount; _TotalUnstakedWnxm[vaultAddress] = _TotalUnstakedWnxm[vaultAddress].add(amount); break; } } for(uint i = 0; i < _UnstakingRequests[vaultAddress].length; i++){ if(_UnstakingRequests[vaultAddress][i].startDateTime == timestamp && _UnstakingRequests[vaultAddress][i].amount == amount && _UnstakingRequests[vaultAddress][i].endBlock == 0 && _UnstakingAddresses[vaultAddress][i] == account) { delete _UnstakingAddresses[vaultAddress][i]; _UnstakingRequests[vaultAddress][i].endBlock = block.number; _TotalUnstakingHistory[vaultAddress] [_UnstakingRequests[vaultAddress][i].startBlock].endBlock = block.number; } } _AccountStakes[vaultAddress][account].total = _AccountStakes[vaultAddress][account].total.sub(amount); _AccountStakes[vaultAddress][account].stakes.push(VaultLib.Staking(block.timestamp, block.number, amount, _AccountStakes[vaultAddress][account].total)); _governanceDistributionContract().removeStake(account, amount); } function createStake(address vaultAddress, uint amount, address account) external { if( _AccountStakes[vaultAddress][account].startRound == 0) { _AccountStakes[vaultAddress][account].startRound = _CurrentRoundNumbers[vaultAddress]; _AccountStakesAddresses[vaultAddress].push(account); } _AccountStakes[vaultAddress][account].total = _AccountStakes[vaultAddress][account].total.add(amount); // block number is being used to record the block at which staking started for governance token distribution _AccountStakes[vaultAddress][account].stakes.push( VaultLib.Staking(block.timestamp, block.number, amount, _AccountStakes[vaultAddress][account].total) ); _governanceDistributionContract().addStake(account, amount); } function removeStake(address vaultAddress, uint amount, address account) external { if( _AccountStakes[vaultAddress][account].startRound == 0) { _AccountStakes[vaultAddress][account].startRound = _CurrentRoundNumbers[vaultAddress]; _AccountStakesAddresses[vaultAddress].push(account); } require(_AccountStakes[vaultAddress][account].total >= amount); _AccountStakes[vaultAddress][account].total = _AccountStakes[vaultAddress][account].total.sub(amount); // block number is being used to record the block at which staking started for governance token distribution _AccountStakes[vaultAddress][account].stakes.push( VaultLib.Staking(block.timestamp, block.number, amount, _AccountStakes[vaultAddress][account].total) ); _governanceDistributionContract().removeStake(account, amount); } function _governanceDistributionAddress() internal view returns(address) { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); return vaultFactory.getGovernanceDistributionAddress(); } function _governanceDistributionContract() internal view returns(GovernanceDistribution) { return GovernanceDistribution(_governanceDistributionAddress()); } function getTotalUnstakingsForBlockRange(address vaultAddress, uint endBlock, uint startBlock) external view returns(uint) { // If we have bad data, no supply data or it starts after the block we are looking for then we can return zero if(endBlock < startBlock || _TotalUnstakingKeys[vaultAddress].length == 0 || _TotalUnstakingKeys[vaultAddress][0] > endBlock){ return 0; } uint lastIndex = _TotalUnstakingKeys[vaultAddress].length - 1; uint total; uint diff; uint stakeEnd; uint stakeStart; if(_TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock < startBlock && lastIndex == 0) { return 0; } //last index should now be in our range so loop through until all block numbers are covered while( lastIndex >= 0 ) { if( _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock < startBlock && _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock != 0 ) { if (lastIndex == 0) { break; } lastIndex = lastIndex.sub(1); continue; } stakeEnd = _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock == 0 ? endBlock : _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock; stakeEnd = (stakeEnd >= endBlock ? endBlock : stakeEnd); stakeStart = _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].startBlock < startBlock ? startBlock : _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].startBlock; diff = (stakeEnd == stakeStart ? 1 : stakeEnd.sub(stakeStart)); total = total.add(_TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].amount.mul(diff)); if(lastIndex == 0){ break; } lastIndex = lastIndex.sub(1); } return total; } function getTotalSupplyForBlockRange(address vaultAddress, uint endBlock, uint startBlock) external view returns(uint) { // If we have bad data, no supply data or it starts after the block we are looking for then we can return zero if(endBlock < startBlock || _TotalSupplyKeys[vaultAddress].length == 0 || _TotalSupplyKeys[vaultAddress][0] > endBlock){ return 0; } uint lastIndex = _TotalSupplyKeys[vaultAddress].length - 1; // If the last total supply is before the start we are looking for we can take the last value if(_TotalSupplyKeys[vaultAddress][lastIndex] <= startBlock){ return _TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][lastIndex]].mul(endBlock.sub(startBlock)); } // working our way back we need to get the first index that falls into our range // This could be large so need to think of a better way to get here while(lastIndex > 0 && _TotalSupplyKeys[vaultAddress][lastIndex] > endBlock){ if(lastIndex == 0){ break; } lastIndex = lastIndex.sub(1); } uint total; uint diff; //last index should now be in our range so loop through until all block numbers are covered while(_TotalSupplyKeys[vaultAddress][lastIndex] >= startBlock) { diff = 0; if(_TotalSupplyKeys[vaultAddress][lastIndex] <= startBlock){ diff = endBlock.sub(startBlock) == 0 ? 1 : endBlock.sub(startBlock); total = total.add(_TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][lastIndex]].mul(diff)); break; } diff = endBlock.sub(_TotalSupplyKeys[vaultAddress][lastIndex]) == 0 ? 1 : endBlock.sub(_TotalSupplyKeys[vaultAddress][lastIndex]); total = total.add(_TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][lastIndex]].mul(diff)); endBlock = _TotalSupplyKeys[vaultAddress][lastIndex]; if(lastIndex == 0){ break; } lastIndex = lastIndex.sub(1); } // If the last total supply is before the start we are looking for we can take the last value if(_TotalSupplyKeys[vaultAddress][lastIndex] <= startBlock && startBlock < endBlock){ total = total.add(_TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][lastIndex]].mul(endBlock.sub(startBlock))); } return total; } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./StakingData.sol"; import "./../iTrustVaultFactory.sol"; import { ITrustVaultLib as VaultLib } from "./../libraries/ItrustVaultLib.sol"; contract Vault is ERC20Upgradeable { using SafeMathUpgradeable for uint; uint8 internal constant FALSE = 0; uint8 internal constant TRUE = 1; uint8 internal _Locked; uint internal _RewardCommission; uint internal _AdminFee; address internal _NXMAddress; address internal _WNXMAddress; address payable internal _VaultWalletAddress; address payable internal _TreasuryAddress; address internal _StakingDataAddress; address internal _BurnDataAddress; address internal _iTrustFactoryAddress; mapping (address => uint256) internal _ReentrantCheck; mapping(address => mapping(string => bool)) internal _UsedNonces; event Stake(address indexed account, address indexed tokenAddress, uint amount, uint balance, uint totalStaked); event UnstakedRequest(address indexed account, uint amount, uint balance, uint totalStaked); event UnstakedApproved(address indexed account, uint amount, uint balance, uint totalStaked); event TransferITV( address indexed fromAccount, address indexed toAccount, uint amount, uint fromBalance, uint fromTotalStaked, uint toBalance, uint toTotalStaked); function initialize( address nxmAddress, address wnxmAddress, address vaultWalletAddress, address stakingDataAddress, address burnDataAddress, string memory tokenName, string memory tokenSymbol, uint adminFee, uint commission, address treasuryAddress ) initializer external { __ERC20_init(tokenName, tokenSymbol); _Locked = FALSE; _NXMAddress = nxmAddress; _WNXMAddress = wnxmAddress; _VaultWalletAddress = payable(vaultWalletAddress); _StakingDataAddress = stakingDataAddress; _BurnDataAddress = burnDataAddress; _AdminFee = adminFee; _iTrustFactoryAddress = _msgSender(); _RewardCommission = commission; _TreasuryAddress = payable(treasuryAddress); } /** * Public functions */ function getAdminFee() external view returns (uint) { return _AdminFee; } function SetAdminFee(uint newFee) external { _onlyAdmin(); _AdminFee = newFee; } function setCommission(uint newCommission) external { _onlyAdmin(); _RewardCommission = newCommission; } function setTreasury(address newTreasury) external { _onlyAdmin(); _TreasuryAddress = payable(newTreasury); } function depositNXM(uint256 value) external { _valueCheck(value); _nonReentrant(); _Locked = TRUE; IERC20Upgradeable nxmToken = IERC20Upgradeable(_NXMAddress); _mint( _msgSender(), value ); require(_getStakingDataContract().createStake(value, _msgSender())); require(nxmToken.transferFrom(_msgSender(), _VaultWalletAddress, value)); emit Stake( _msgSender(), _NXMAddress, value, balanceOf(_msgSender()), _getStakingDataContract().getAccountStakingTotal(_msgSender())); _Locked = FALSE; } function _depositRewardToken(address token, uint amount) internal { require(token != address(0)); uint commission = 0; uint remain = amount; if (_RewardCommission != 0) { commission = amount.mul(_RewardCommission).div(10000); remain = amount.sub(commission); } IERC20Upgradeable tokenContract = IERC20Upgradeable(token); if (commission != 0) { require(tokenContract.transferFrom(msg.sender, _TreasuryAddress, commission)); } require(tokenContract.transferFrom(msg.sender, address(this), remain)); } function endRound(address[] calldata tokens, uint[] calldata tokenAmounts, bool[] calldata ignoreUnstakes) external { _onlyAdmin(); require(tokens.length == tokenAmounts.length); require(_getStakingDataContract().endRound(tokens, tokenAmounts, ignoreUnstakes, _RewardCommission)); for(uint i = 0; i < tokens.length; i++) { _depositRewardToken(tokens[i], tokenAmounts[i]); } } function getCurrentRoundData() external view returns(uint roundNumber, uint startBlock, uint endBlock) { _onlyAdmin(); return _getStakingDataContract().getCurrentRoundData(); } function getRoundData(uint roundNumberIn) external view returns(uint roundNumber, uint startBlock, uint endBlock) { _onlyAdmin(); return _getStakingDataContract().getRoundData(roundNumberIn); } function getRoundRewards(uint roundNumber) external view returns( address[] memory rewardTokens, uint[] memory rewardAmounts , uint[] memory commissionAmounts, uint[] memory tokenPerDay, uint[] memory totalSupply ) { _onlyAdmin(); return _getStakingDataContract().getRoundRewards(roundNumber); } function depositWNXM(uint256 value) external { _valueCheck(value); _nonReentrant(); _Locked = TRUE; IERC20Upgradeable wnxmToken = IERC20Upgradeable(_WNXMAddress); _mint( _msgSender(), value ); require(_getStakingDataContract().createStake(value, _msgSender())); require(wnxmToken.transferFrom(_msgSender(), _VaultWalletAddress, value)); emit Stake( _msgSender(), _WNXMAddress, value, balanceOf(_msgSender()), _getStakingDataContract().getAccountStakingTotal(_msgSender())); _Locked = FALSE; } function startUnstake(uint256 value) external payable { _nonReentrant(); _Locked = TRUE; uint adminFee = _AdminFee; if(adminFee != 0) { require(msg.value == _AdminFee); } require(_getStakingDataContract().startUnstake(_msgSender(), value)); if(adminFee != 0) { (bool sent, ) = _VaultWalletAddress.call{value: adminFee}(""); require(sent); } emit UnstakedRequest( _msgSender(), value, balanceOf(_msgSender()), _getStakingDataContract().getAccountStakingTotal(_msgSender())); _Locked = FALSE; } function getAccountStakes() external view returns( uint stakingTotal, uint unStakingTotal, uint[] memory unStakingAmounts, uint[] memory unStakingStarts ) { return _getStakingDataContract().getAccountStakes(_msgSender()); } function getAllAcountUnstakes() external view returns (address[] memory accounts, uint[] memory startTimes, uint[] memory values) { _onlyAdmin(); return _getStakingDataContract().getAllAcountUnstakes(); } function getAccountUnstakedTotal() external view returns (uint) { return _getStakingDataContract().getAccountUnstakedTotal(_msgSender()); } function getUnstakedwNXMTotal() external view returns (uint) { return _getStakingDataContract().getUnstakedWxnmTotal(); } function authoriseUnstakes(address[] memory account, uint[] memory timestamp, uint[] memory amounts) external { _onlyAdmin(); require(_getStakingDataContract().authoriseUnstakes(account, timestamp)); //for each unstake burn for(uint i = 0; i < account.length; i++) { _burn(account[i], amounts[i]); emit UnstakedApproved( account[i], amounts[i], balanceOf(account[i]), _getStakingDataContract().getAccountStakingTotal(account[i])); } } function withdrawUnstakedwNXM(uint amount) external { _nonReentrant(); _Locked = TRUE; IERC20Upgradeable wnxm = IERC20Upgradeable(_WNXMAddress); uint balance = wnxm.balanceOf(address(this)); require(amount <= balance); require(_getStakingDataContract().withdrawUnstakedToken(_msgSender(), amount)); require(wnxm.transfer(msg.sender, amount)); // emit ClaimUnstaked(msg.sender, amount); _Locked = FALSE; } function isAdmin() external view returns (bool) { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); return vaultFactory.isAddressAdmin(_msgSender()); } function calculateRewards() external view returns (address[] memory rewardTokens, uint[] memory rewards) { return _getStakingDataContract().calculateRewards(_msgSender()); } function calculateRewardsForAccount(address account) external view returns (address[] memory rewardTokens, uint[] memory rewards) { _isTrustedSigner(_msgSender()); return _getStakingDataContract().calculateRewards(account); } function withdrawRewards(address[] memory tokens, uint[] memory rewards, string memory nonce, bytes memory sig) external returns (bool) { require(!_UsedNonces[_msgSender()][nonce]); _nonReentrant(); _Locked = TRUE; bool toClaim = false; for(uint x = 0; x < tokens.length; x++){ if(rewards[x] != 0) { toClaim = true; } } require(toClaim == true); bytes32 abiBytes = keccak256(abi.encodePacked(_msgSender(), tokens, rewards, nonce, address(this))); bytes32 message = VaultLib.prefixed(abiBytes); address signer = VaultLib.recoverSigner(message, sig); _isTrustedSigner(signer); require(_getStakingDataContract().withdrawRewards(_msgSender(), tokens, rewards)); _UsedNonces[_msgSender()][nonce] = true; for(uint x = 0; x < tokens.length; x++){ if(rewards[x] != 0) { IERC20Upgradeable token = IERC20Upgradeable(tokens[x]); require(token.balanceOf(address(this)) >= rewards[x]); require(token.transfer(_msgSender() ,rewards[x])); } } _Locked = FALSE; return true; } function burnTokensForAccount(address account, uint tokensToBurn) external returns(bool) { _nonReentrant(); _validBurnSender(); require(tokensToBurn > 0); _Locked = TRUE; _burn(account, tokensToBurn); require(_getStakingDataContract().removeStake(tokensToBurn, account)); _Locked = FALSE; return true; } /** * @dev See {IERC20Upgradeable-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20Upgradeable-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), allowance(_msgSender(), sender).sub(amount)); return true; } /** * @dev required to be allow for receiving ETH claim payouts */ receive() external payable {} /** * Private functions */ /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal override { super._mint(account, amount); _updateTotalSupplyForBlock(); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal override { super._burn(account, amount); _updateTotalSupplyForBlock(); } function _getStakingDataContract() internal view returns (StakingData){ return StakingData(_StakingDataAddress); } function _updateTotalSupplyForBlock() internal { require(_getStakingDataContract().updateTotalSupplyForDayAndBlock(totalSupply())); } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal override { require(_getStakingDataContract().removeStake(amount, sender)); require(_getStakingDataContract().createStake(amount, recipient)); super._transfer(sender, recipient, amount); emit TransferITV( sender, recipient, amount, balanceOf(sender), _getStakingDataContract().getAccountStakingTotal(sender), balanceOf(recipient), _getStakingDataContract().getAccountStakingTotal(recipient)); _updateTotalSupplyForBlock(); } /** * Private validation functions */ function _valueCheck(uint value) internal pure { require(value != 0, "!"); } function _onlyAdmin() internal view { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); require( vaultFactory.isAddressAdmin(_msgSender()), "NTA" ); } function _validBurnSender() internal view { require( _BurnDataAddress == _msgSender(), "NTB" ); } function _isTrustedSigner(address signer) internal view { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); require( vaultFactory.isTrustedSignerAddress(signer), "NTS" ); } function _nonReentrant() internal view { require(_Locked == FALSE); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/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 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 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; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20CappedUpgradeable is Initializable, ERC20Upgradeable { using SafeMathUpgradeable for uint256; uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ function __ERC20Capped_init(uint256 cap_) internal initializer { __Context_init_unchained(); __ERC20Capped_init_unchained(cap_); } function __ERC20Capped_init_unchained(uint256 cap_) internal initializer { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded"); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./UpgradeableProxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is UpgradeableProxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); } /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // solhint-disable-next-line avoid-low-level-calls (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @dev Returns the current admin. */ function _admin() internal view returns (address adm) { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newAdmin) } } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal override virtual { require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Proxy.sol"; import "../utils/Address.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract UpgradeableProxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) public payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { // solhint-disable-next-line avoid-low-level-calls (bool success,) = _logic.delegatecall(_data); require(success); } } /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal override view returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
See {IERC20Upgradeable-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; }
11,785,453
./partial_match/3/0xC79322B1Ff862D02B53Efb7Ed5F6E5102F22a3C8/sources/ReflectiveTreasury.sol
Withdraw entire balance to the owner./
function withdraw() external onlyOwner() { uint256 amount = _token.balanceOf(address(this)); require(amount > 0, "Treasury: no principle to withdraw"); _token.safeTransfer(msg.sender, amount); _principle = 0; }
5,208,999
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./SafeMath.sol"; import "./IBancorFormula.sol"; import "./BancorFormula.sol"; import "./IERC20.sol"; contract TokenExchange { using SafeMath for uint256; bool public initialized = false; IBancorFormula public formula; address public token; // token contract address address public owner; uint256 public reserveBalanceFixed; // = reserve balance + initialized reserve uint256 public tokenSupplyFixed; // = max supply - (token balance - initialized reserve) uint32 public connWeight; // connect weight, i.e. reserve weight, in ppm (1-1000000) bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); /** * events */ event TokenIssuance(uint256 targetAmount); /** * constuctor * * @param _token address of the token contract */ constructor(address _token) public { formula = new BancorFormula(); token = _token; owner = msg.sender; } /** * modifier */ modifier onlyOwner { require(msg.sender == owner, "Error: not owner"); _; } /** * safeTransfer */ function _safeTransfer(address _token, address _to, uint256 _value) private { (bool success, bytes memory data) = _token.call(abi.encodeWithSelector(SELECTOR, _to, _value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "Error: failed to transfer"); } /** * initialize parameters * * @param _initialSupply initial token supply (virtual) * @param _initialReserve initial reserve token balance (virtual) * @param _reserveWeight reserve weight, represented in ppm (1-1000000) * * then the initial spot price will be * _initialReserve/_initialSupply * 1000000/_reserveWeight */ function initialize(uint256 _initialSupply, uint256 _initialReserve, uint32 _reserveWeight) public onlyOwner { require(initialized == false, "Error: already initialized"); reserveBalanceFixed = _initialReserve; tokenSupplyFixed = _initialSupply; connWeight = _reserveWeight; initialized = true; } /** * purchase a certain target amount of tokens by paying in, * the issued tokens will be put back into the caller's wallet * */ function purchase() public payable { require(msg.value > 0, "Error: too few paid"); uint256 amount = msg.value; uint256 targetAmount = formula.purchaseTargetAmount(tokenSupplyFixed, reserveBalanceFixed, connWeight, amount); // update tokenSupplyFixed += targetAmount; reserveBalanceFixed += amount; // tranfer token to the buyer require(IERC20(token).balanceOf(address(this)) >= targetAmount, "Error: not enough tokens"); _safeTransfer(token, msg.sender, targetAmount); emit TokenIssuance(targetAmount); } /** * get real balance of tokens */ function getTokenBalance() public view returns(uint256) { return IERC20(token).balanceOf(address(this)); } /** * get real balance of reserve */ function getReserveBalance() public view returns(uint256) { return address(this).balance; } /** * withdraw all remaining tokens */ function withdrawTokens() public onlyOwner { uint256 amount = getTokenBalance(); _safeTransfer(token, owner, amount); } /** * withdraw reserve */ function withdrawReserve() public onlyOwner { uint256 amount = getReserveBalance(); (bool success,) = owner.call{value: amount}(""); require(success, "Error: unable to send"); } }
purchase a certain target amount of tokens by paying in, the issued tokens will be put back into the caller's wallet/ update tranfer token to the buyer
function purchase() public payable { require(msg.value > 0, "Error: too few paid"); uint256 amount = msg.value; uint256 targetAmount = formula.purchaseTargetAmount(tokenSupplyFixed, reserveBalanceFixed, connWeight, amount); tokenSupplyFixed += targetAmount; reserveBalanceFixed += amount; require(IERC20(token).balanceOf(address(this)) >= targetAmount, "Error: not enough tokens"); _safeTransfer(token, msg.sender, targetAmount); emit TokenIssuance(targetAmount); }
12,692,716
pragma solidity >=0.5.0; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; import '@uniswap/lib/contracts/libraries/Babylonian.sol'; import '@uniswap/lib/contracts/libraries/FullMath.sol'; import './SafeMath.sol'; import './ChiaxSwapLibrary.sol'; // library containing some math for dealing with the liquidity shares of a pair, e.g. computing their exact value // in terms of the underlying tokens library UniswapV2LiquidityMathLibrary { using SafeMath for uint256; // computes the direction and magnitude of the profit-maximizing trade function computeProfitMaximizingTrade( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) pure internal returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant.mul(1000), aToB ? truePriceTokenA : truePriceTokenB, (aToB ? truePriceTokenB : truePriceTokenA).mul(997) ) ); uint256 rightSide = (aToB ? reserveA.mul(1000) : reserveB.mul(1000)) / 997; if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price to the profit-maximizing price amountIn = leftSide.sub(rightSide); } // gets the reserves after an arbitrage moves the price to the profit-maximizing ratio given an externally observed true price function getReservesAfterArbitrage( address factory, address tokenA, address tokenB, uint256 truePriceTokenA, uint256 truePriceTokenB ) view internal returns (uint256 reserveA, uint256 reserveB) { // first get reserves before the swap (reserveA, reserveB) = ChiaxSwapLibrary.getReserves(factory, tokenA, tokenB); require(reserveA > 0 && reserveB > 0, 'UniswapV2ArbitrageLibrary: ZERO_PAIR_RESERVES'); // then compute how much to swap to arb to the true price (bool aToB, uint256 amountIn) = computeProfitMaximizingTrade(truePriceTokenA, truePriceTokenB, reserveA, reserveB); if (amountIn == 0) { return (reserveA, reserveB); } // now affect the trade to the reserves if (aToB) { uint amountOut = ChiaxSwapLibrary.getAmountOut(amountIn, reserveA, reserveB); reserveA += amountIn; reserveB -= amountOut; } else { uint amountOut = ChiaxSwapLibrary.getAmountOut(amountIn, reserveB, reserveA); reserveB += amountIn; reserveA -= amountOut; } } // computes liquidity value given all the parameters of the pair function computeLiquidityValue( uint256 reservesA, uint256 reservesB, uint256 totalSupply, uint256 liquidityAmount, bool feeOn, uint kLast ) internal pure returns (uint256 tokenAAmount, uint256 tokenBAmount) { if (feeOn && kLast > 0) { uint rootK = Babylonian.sqrt(reservesA.mul(reservesB)); uint rootKLast = Babylonian.sqrt(kLast); if (rootK > rootKLast) { uint numerator1 = totalSupply; uint numerator2 = rootK.sub(rootKLast); uint denominator = rootK.mul(5).add(rootKLast); uint feeLiquidity = FullMath.mulDiv(numerator1, numerator2, denominator); totalSupply = totalSupply.add(feeLiquidity); } } return (reservesA.mul(liquidityAmount) / totalSupply, reservesB.mul(liquidityAmount) / totalSupply); } // get all current parameters from the pair and compute value of a liquidity amount // **note this is subject to manipulation, e.g. sandwich attacks**. prefer passing a manipulation resistant price to // #getLiquidityValueAfterArbitrageToPrice function getLiquidityValue( address factory, address tokenA, address tokenB, uint256 liquidityAmount ) internal view returns (uint256 tokenAAmount, uint256 tokenBAmount) { (uint256 reservesA, uint256 reservesB) = ChiaxSwapLibrary.getReserves(factory, tokenA, tokenB); IUniswapV2Pair pair = IUniswapV2Pair(ChiaxSwapLibrary.pairFor(factory, tokenA, tokenB)); bool feeOn = IUniswapV2Factory(factory).feeTo() != address(0); uint kLast = feeOn ? pair.kLast() : 0; uint totalSupply = pair.totalSupply(); return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeOn, kLast); } // given two tokens, tokenA and tokenB, and their "true price", i.e. the observed ratio of value of token A to token B, // and a liquidity amount, returns the value of the liquidity in terms of tokenA and tokenB function getLiquidityValueAfterArbitrageToPrice( address factory, address tokenA, address tokenB, uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 liquidityAmount ) internal view returns ( uint256 tokenAAmount, uint256 tokenBAmount ) { bool feeOn = IUniswapV2Factory(factory).feeTo() != address(0); IUniswapV2Pair pair = IUniswapV2Pair(ChiaxSwapLibrary.pairFor(factory, tokenA, tokenB)); uint kLast = feeOn ? pair.kLast() : 0; uint totalSupply = pair.totalSupply(); // this also checks that totalSupply > 0 require(totalSupply >= liquidityAmount && liquidityAmount > 0, 'ComputeLiquidityValue: LIQUIDITY_AMOUNT'); (uint reservesA, uint reservesB) = getReservesAfterArbitrage(factory, tokenA, tokenB, truePriceTokenA, truePriceTokenB); return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeOn, kLast); } }
get all current parameters from the pair and compute value of a liquidity amount note this is subject to manipulation, e.g. sandwich attacks. prefer passing a manipulation resistant price to getLiquidityValueAfterArbitrageToPrice
function getLiquidityValue( address factory, address tokenA, address tokenB, uint256 liquidityAmount ) internal view returns (uint256 tokenAAmount, uint256 tokenBAmount) { (uint256 reservesA, uint256 reservesB) = ChiaxSwapLibrary.getReserves(factory, tokenA, tokenB); IUniswapV2Pair pair = IUniswapV2Pair(ChiaxSwapLibrary.pairFor(factory, tokenA, tokenB)); bool feeOn = IUniswapV2Factory(factory).feeTo() != address(0); uint kLast = feeOn ? pair.kLast() : 0; uint totalSupply = pair.totalSupply(); return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeOn, kLast); }
5,370,471
pragma solidity ^0.4.19; /* Adapted from strings.sol created by Nick Johnson <[email protected]> * Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> */ library strings { struct slice { uint _len; uint _ptr; } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function concat(slice self, slice other) internal returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal pure returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } } /* Helper String Functions for Game Manager Contract * @title String Healpers * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract StringHelpers { using strings for *; function stringToBytes32(string memory source) internal returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function bytes32ToString(bytes32 x) constant internal returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; function implementsERC721() public pure returns (bool); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } /* Controls state and access rights for contract functions * @title Operational Control * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from contract created by OpenZeppelin * Ref: https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager ); _; } /// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } /// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can't unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } } contract CSCPreSaleItemBase is ERC721, OperationalControl, StringHelpers { /*** EVENTS ***/ /// @dev The Created event is fired whenever a new collectible comes into existence. event CollectibleCreated(address owner, uint256 globalId, uint256 collectibleType, uint256 collectibleClass, uint256 sequenceId, bytes32 collectibleName); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CSCPreSaleFactory"; string public constant SYMBOL = "CSCPF"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @dev CSC Pre Sale Struct, having details of the collectible struct CSCPreSaleItem { /// @dev sequence ID i..e Local Index uint256 sequenceId; /// @dev name of the collectible stored in bytes bytes32 collectibleName; /// @dev Collectible Type uint256 collectibleType; /// @dev Collectible Class uint256 collectibleClass; /// @dev owner address address owner; /// @dev redeemed flag (to help whether it got redeemed or not) bool isRedeemed; } /// @dev array of CSCPreSaleItem type holding information on the Collectibles Created CSCPreSaleItem[] allPreSaleItems; /// @dev Max Count for preSaleItem type -> preSaleItem class -> max. limit mapping(uint256 => mapping(uint256 => uint256)) public preSaleItemTypeToClassToMaxLimit; /// @dev Map from preSaleItem type -> preSaleItem class -> max. limit set (bool) mapping(uint256 => mapping(uint256 => bool)) public preSaleItemTypeToClassToMaxLimitSet; /// @dev Map from preSaleItem type -> preSaleItem class -> Name (string / bytes32) mapping(uint256 => mapping(uint256 => bytes32)) public preSaleItemTypeToClassToName; // @dev mapping which holds all the possible addresses which are allowed to interact with the contract mapping (address => bool) approvedAddressList; // @dev mapping holds the preSaleItem -> owner details mapping (uint256 => address) public preSaleItemIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from preSaleItem to an address that has been approved to call /// transferFrom(). Each Collectible can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public preSaleItemIndexToApproved; /// @dev A mapping of preSaleItem Type to Type Sequence Number to Collectible mapping (uint256 => mapping (uint256 => mapping ( uint256 => uint256 ) ) ) public preSaleItemTypeToSequenceIdToCollectible; /// @dev A mapping from Pre Sale Item Type IDs to the Sequqence Number . mapping (uint256 => mapping ( uint256 => uint256 ) ) public preSaleItemTypeToCollectibleCount; /// @dev Token Starting Index taking into account the old presaleContract total assets that can be generated uint256 public STARTING_ASSET_BASE = 3000; /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } function setMaxLimit(string _collectibleName, uint256 _collectibleType, uint256 _collectibleClass, uint256 _maxLimit) external onlyManager whenNotPaused { require(_maxLimit > 0); require(_collectibleType >= 0 && _collectibleClass >= 0); require(stringToBytes32(_collectibleName) != stringToBytes32("")); require(!preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass]); preSaleItemTypeToClassToMaxLimit[_collectibleType][_collectibleClass] = _maxLimit; preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass] = true; preSaleItemTypeToClassToName[_collectibleType][_collectibleClass] = stringToBytes32(_collectibleName); } /// @dev Method to fetch collectible details function getCollectibleDetails(uint256 _tokenId) external view returns(uint256 assetId, uint256 sequenceId, uint256 collectibleType, uint256 collectibleClass, string collectibleName, bool isRedeemed, address owner) { require (_tokenId > STARTING_ASSET_BASE); uint256 generatedCollectibleId = _tokenId - STARTING_ASSET_BASE; CSCPreSaleItem memory _Obj = allPreSaleItems[generatedCollectibleId]; assetId = _tokenId; sequenceId = _Obj.sequenceId; collectibleType = _Obj.collectibleType; collectibleClass = _Obj.collectibleClass; collectibleName = bytes32ToString(_Obj.collectibleName); owner = _Obj.owner; isRedeemed = _Obj.isRedeemed; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _tokenId) public { // Caller must own token. require (_tokenId > STARTING_ASSET_BASE); require(_owns(msg.sender, _tokenId)); preSaleItemIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } function implementsERC721() public pure returns (bool) { return true; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { require (_tokenId > STARTING_ASSET_BASE); owner = preSaleItemIndexToOwner[_tokenId]; require(owner != address(0)); } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { require (_tokenId > STARTING_ASSET_BASE); address newOwner = msg.sender; address oldOwner = preSaleItemIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose collectibles tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire CSCPreSaleItem array looking for collectibles belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCount = totalSupply() + 1 + STARTING_ASSET_BASE; uint256 resultIndex = 0; // We count on the fact that all LS PreSaleItems have IDs starting at 0 and increasing // sequentially up to the total count. uint256 _tokenId; for (_tokenId = STARTING_ASSET_BASE; _tokenId < totalCount; _tokenId++) { if (preSaleItemIndexToOwner[_tokenId] == _owner) { result[resultIndex] = _tokenId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return allPreSaleItems.length - 1; //Removed 0 index } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _tokenId) public { require (_tokenId > STARTING_ASSET_BASE); require(_addressNotNull(_to)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) public { require (_tokenId > STARTING_ASSET_BASE); require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// @dev Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) internal pure returns (bool) { return _to != address(0); } /// @dev For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) internal view returns (bool) { return preSaleItemIndexToApproved[_tokenId] == _to; } /// @dev For creating CSC Collectible function _createCollectible(bytes32 _collectibleName, uint256 _collectibleType, uint256 _collectibleClass) internal returns(uint256) { uint256 _sequenceId = uint256(preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass]) + 1; // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. require(_sequenceId == uint256(uint32(_sequenceId))); CSCPreSaleItem memory _collectibleObj = CSCPreSaleItem( _sequenceId, _collectibleName, _collectibleType, _collectibleClass, address(0), false ); uint256 generatedCollectibleId = allPreSaleItems.push(_collectibleObj) - 1; uint256 collectibleIndex = generatedCollectibleId + STARTING_ASSET_BASE; preSaleItemTypeToSequenceIdToCollectible[_collectibleType][_collectibleClass][_sequenceId] = collectibleIndex; preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass] = _sequenceId; // emit Created event // CollectibleCreated(address owner, uint256 globalId, uint256 collectibleType, uint256 collectibleClass, uint256 sequenceId, bytes32 collectibleName); CollectibleCreated(address(this), collectibleIndex, _collectibleType, _collectibleClass, _sequenceId, _collectibleObj.collectibleName); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), address(this), collectibleIndex); return collectibleIndex; } /// @dev Check for token ownership function _owns(address claimant, uint256 _tokenId) internal view returns (bool) { return claimant == preSaleItemIndexToOwner[_tokenId]; } /// @dev Assigns ownership of a specific preSaleItem to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { uint256 generatedCollectibleId = _tokenId - STARTING_ASSET_BASE; // Updating the owner details of the collectible CSCPreSaleItem memory _Obj = allPreSaleItems[generatedCollectibleId]; _Obj.owner = _to; allPreSaleItems[generatedCollectibleId] = _Obj; // Since the number of preSaleItem is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership preSaleItemIndexToOwner[_tokenId] = _to; // When creating new collectibles _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete preSaleItemIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev Checks if a given address currently has transferApproval for a particular CSCPreSaleItem. /// 0 is a valid value as it will be the starter function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { require(_tokenId > STARTING_ASSET_BASE); return preSaleItemIndexToApproved[_tokenId] == _claimant; } } /* Lucid Sight, Inc. ERC-721 Collectibles Manager. * @title LSPreSaleManager - Lucid Sight, Inc. Non-Fungible Token * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract CSCPreSaleManager is CSCPreSaleItemBase { event RefundClaimed(address owner, uint256 refundValue); /// @dev defines if preSaleItem type -> preSaleItem class -> Vending Machine to set limit (bool) mapping(uint256 => mapping(uint256 => bool)) public preSaleItemTypeToClassToCanBeVendingMachine; /// @dev defines if preSaleItem type -> preSaleItem class -> Vending Machine Fee mapping(uint256 => mapping(uint256 => uint256)) public preSaleItemTypeToClassToVendingFee; /// @dev Mapping created store the amount of value a wallet address used to buy assets mapping(address => uint256) public addressToValue; bool CSCPreSaleInit = false; /// @dev Constructor creates a reference to the NFT (ERC721) ownership contract function CSCPreSaleManager() public { require(msg.sender != address(0)); paused = true; error = false; managerPrimary = msg.sender; } /// @dev allows the contract to accept ETH function() external payable { } /// @dev Function to add approved address to the /// approved address list function addToApprovedAddress (address _newAddr) onlyManager whenNotPaused { require(_newAddr != address(0)); require(!approvedAddressList[_newAddr]); approvedAddressList[_newAddr] = true; } /// @dev Function to remove an approved address from the /// approved address list function removeFromApprovedAddress (address _newAddr) onlyManager whenNotPaused { require(_newAddr != address(0)); require(approvedAddressList[_newAddr]); approvedAddressList[_newAddr] = false; } /// @dev Function toggle vending for collectible function toggleVending (uint256 _collectibleType, uint256 _collectibleClass) external onlyManager { if(preSaleItemTypeToClassToCanBeVendingMachine[_collectibleType][_collectibleClass] == false) { preSaleItemTypeToClassToCanBeVendingMachine[_collectibleType][_collectibleClass] = true; } else { preSaleItemTypeToClassToCanBeVendingMachine[_collectibleType][_collectibleClass] = false; } } /// @dev Function toggle vending for collectible function setVendingFee (uint256 _collectibleType, uint256 _collectibleClass, uint fee) external onlyManager { preSaleItemTypeToClassToVendingFee[_collectibleType][_collectibleClass] = fee; } /// @dev This helps in creating a collectible and then /// transfer it _toAddress function createCollectible(uint256 _collectibleType, uint256 _collectibleClass, address _toAddress) onlyManager external whenNotPaused { require(msg.sender != address(0)); require(msg.sender != address(this)); require(_toAddress != address(0)); require(_toAddress != address(this)); require(preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass]); require(preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass] < preSaleItemTypeToClassToMaxLimit[_collectibleType][_collectibleClass]); uint256 _tokenId = _createCollectible(preSaleItemTypeToClassToName[_collectibleType][_collectibleClass], _collectibleType, _collectibleClass); _transfer(address(this), _toAddress, _tokenId); } /// @dev This helps in creating a collectible and then /// transfer it _toAddress function vendingCreateCollectible(uint256 _collectibleType, uint256 _collectibleClass, address _toAddress) payable external whenNotPaused { //Only if Vending is Allowed for this Asset require(preSaleItemTypeToClassToCanBeVendingMachine[_collectibleType][_collectibleClass]); require(msg.value >= preSaleItemTypeToClassToVendingFee[_collectibleType][_collectibleClass]); require(msg.sender != address(0)); require(msg.sender != address(this)); require(_toAddress != address(0)); require(_toAddress != address(this)); require(preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass]); require(preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass] < preSaleItemTypeToClassToMaxLimit[_collectibleType][_collectibleClass]); uint256 _tokenId = _createCollectible(preSaleItemTypeToClassToName[_collectibleType][_collectibleClass], _collectibleType, _collectibleClass); uint256 excessBid = msg.value - preSaleItemTypeToClassToVendingFee[_collectibleType][_collectibleClass]; if(excessBid > 0) { msg.sender.transfer(excessBid); } addressToValue[msg.sender] += preSaleItemTypeToClassToVendingFee[_collectibleType][_collectibleClass]; _transfer(address(this), _toAddress, _tokenId); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyManager whenPaused { // Actually unpause the contract. super.unpause(); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function hasError() public onlyManager whenPaused { // Actually error out the contract. super.hasError(); } /// @dev Function does the init step and thus allow /// to create a Dummy 0th colelctible function preSaleInit() onlyManager { require(!CSCPreSaleInit); require(allPreSaleItems.length == 0); CSCPreSaleInit = true; //Fill in index 0 to null requests CSCPreSaleItem memory _Obj = CSCPreSaleItem(0, stringToBytes32("DummyAsset"), 0, 0, address(this), true); allPreSaleItems.push(_Obj); } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT (ERC721) contract, but can be called either by /// the owner or the NFT (ERC721) contract. function withdrawBalance() onlyBanker { // We are using this boolean method to make sure that even if one fails it will still work bankManager.transfer(this.balance); } // @dev a function to claim refund if and only if theres an error in the contract function claimRefund(address _ownerAddress) whenError { uint256 refundValue = addressToValue[_ownerAddress]; require (refundValue > 0); addressToValue[_ownerAddress] = 0; _ownerAddress.transfer(refundValue); RefundClaimed(_ownerAddress, refundValue); } /// @dev Function used to set the flag isRedeemed to true /// can be called by addresses in the approvedAddressList function isRedeemed(uint256 _tokenId) { require(approvedAddressList[msg.sender]); require(_tokenId > STARTING_ASSET_BASE); uint256 generatedCollectibleId = _tokenId - STARTING_ASSET_BASE; CSCPreSaleItem memory _Obj = allPreSaleItems[generatedCollectibleId]; _Obj.isRedeemed = true; allPreSaleItems[generatedCollectibleId] = _Obj; } }
This helps in creating a collectible and then transfer it _toAddress
function createCollectible(uint256 _collectibleType, uint256 _collectibleClass, address _toAddress) onlyManager external whenNotPaused { require(msg.sender != address(0)); require(msg.sender != address(this)); require(_toAddress != address(0)); require(_toAddress != address(this)); require(preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass]); require(preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass] < preSaleItemTypeToClassToMaxLimit[_collectibleType][_collectibleClass]); uint256 _tokenId = _createCollectible(preSaleItemTypeToClassToName[_collectibleType][_collectibleClass], _collectibleType, _collectibleClass); _transfer(address(this), _toAddress, _tokenId); }
12,867,113
./full_match/137/0x4c9EB19CfF0fE11bd00C37b935CF5D3225deAc50/sources/ERC721.sol
Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. The call is not executed if the target address is not a contract. from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint256 ID of the token to be transferred _data bytes optional data to send along with the call return bool whether the call correctly returned the expected magic value/
function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); assembly { revert(add(32, reason), mload(reason)) } } } return true; } }
3,760,881
./partial_match/100/0x3c942B969C85cfd24942ECE39de6F843767F1755/sources/ClearingHouseViewer.sol
get personal balance with funding payment _quoteToken ERC20 token address _trader trader address return margin personal balance with funding payment in 18 digits/
function getPersonalBalanceWithFundingPayment(IERC20 _quoteToken, address _trader) external view returns (Decimal.decimal memory margin) { IInsuranceFund insuranceFund = clearingHouse.insuranceFund(); IAmm[] memory amms = insuranceFund.getAllAmms(); for (uint256 i = 0; i < amms.length; i++) { if (IAmm(amms[i]).quoteAsset() != _quoteToken) { continue; } Decimal.decimal memory posMargin = getPersonalPositionWithFundingPayment(amms[i], _trader).margin; margin = margin.addD(posMargin); } }
16,663,985
./partial_match/5/0xa44eE6026B90F689f20a297353264C76a86F09BD/sources/VybeStakeOld.sol
noReentrancy shouldn't be needed due to the lack of external calls better safe than sorry update the last claim time mint out their staking rewards and the dev funds
function claimRewards() external noReentrancy { require(!_dated); uint256 mintage = _calculateMintage(msg.sender); uint256 mintagePiece = mintage.div(20); require(mintagePiece > 0); _lastClaim[msg.sender] = block.timestamp; _VYBE.mint(msg.sender, mintage.sub(mintagePiece)); _VYBE.mint(_developerFund, mintagePiece); emit Rewards(msg.sender, mintage, mintagePiece); }
16,873,329
./partial_match/4/0x5dFBF7146e914002D557Edb6e837aaE5F4deD5bD/sources/Contract.sol
Получение всех проголосовавших избиратеелей./
function getVotedElectors() public view returns(address[] memory) { require( ballots.length > 0, "No active ballot." ); return ballots[ballots.length - 1].areVotedElectors; }
8,629,441
./full_match/4/0xB423828d4F93970Bf3f9eE07803A082B8D72e458/sources/contracts/metaships/metaships.sol
TODO: Needs to be less predictable hash than "now" timestamp
function _randomizeAttributeRNG(uint seed) public onlyByDev(msg.sender) { uint r = 1; for (uint i = 0; i < ATTRIBUTE_RNG.length; i++) { uint n = i + uint(keccak256(abi.encodePacked(now, i, r, seed))) % (ATTRIBUTE_RNG.length - i); uint temp = ATTRIBUTE_RNG[n]; r = temp; ATTRIBUTE_RNG[n] = ATTRIBUTE_RNG[i]; ATTRIBUTE_RNG[i] = uint8(temp); } }
724,856
pragma solidity >=0.4.21 <0.6.0; import "../node_modules/@openzeppelin/contracts/math/SafeMath.sol"; import "../node_modules/@openzeppelin/contracts/ownership/Ownable.sol"; contract PredictionMarket is Ownable { using SafeMath for uint256; // Group stages uint256 public BETTING = 1; uint256 public WAITING = 2; uint256 public CLAIMING = 3; uint256 public TOP_TIER_THRESHOLD = 75; // Threshold for top tier bet winners uint256 public MID_TIER_THRESHOLD = 150; // Threshold for mid tier bet winners uint256 public TOP_TIER_WINNING_SCALE = 3; // Scaled winnings for top tier winners uint256 public MID_TIER_WINNING_SCALE = 1; // Scaled winnings for mid tier winners uint256 public BASE_WINNING_SCALE = 0; // Base winnings scale uint256 public PREDICTIONS_PER_BET = 48; // Number of predictions within a bet uint256 public STAGE_LENGTH = 24; // Number of time periods within a stage uint256 public currTimePeriod = 0; // Index of current period within 24 hour period uint256 public currDay = 0; // Current day relative to start of contract life // Groups: mapping of agent's addresses to their bets. mapping(address => Bet) public group1; mapping(address => Bet) public group2; mapping(address => Bet) public group3; mapping(uint256 => uint256) stageToGroupNumber; // Only used in stageToGroup() and constructor() mapping(address => mapping(uint256 => Bet)) public history; mapping(uint256 => uint256[48]) public oracleHistory; mapping(uint256 => uint256[48]) public averagePredictionsHistory; mapping(uint256 => uint256) public groupCountHistory; // Returns the group corresponding to a Stage. function stageToGroup(uint256 stage) private view returns(mapping(address => Bet) storage) { uint256 group = stageToGroupNumber[stage]; if (group == 1) { return group1; } else if (group == 2) { return group2; } else { return group3; } } mapping(uint256 => GroupInfo) public stageToGroupInfo; struct Bet { uint256 amount; uint256[48] predictions; uint256 winningScale; uint256 timestamp; } struct GroupInfo { address[] agents; // List of agents in the group uint256 topTierCount; uint256 midTierCount; uint256 baseCount; uint256 totalBetAmount; uint256[] consumption; // Oracle-provided actual aggregate demand } constructor() public { stageToGroupNumber[BETTING] = 1; stageToGroupNumber[WAITING] = 2; stageToGroupNumber[CLAIMING] = 3; } // Returns true if agent can place a bet in current betting stage. function canBet(address agent) public view returns(bool) { mapping(address => Bet) storage group = stageToGroup(BETTING); return group[agent].amount == 0 && currTimePeriod < STAGE_LENGTH; } // Returns true if agent can rank in current claiming stage. function canRank(address agent) public view returns(bool) { mapping(address => Bet) storage group = stageToGroup(CLAIMING); return group[agent].amount != 0 && currTimePeriod < STAGE_LENGTH; } // Returns true if agent can claim winnings in current claiming stage. function canClaim(address agent) public view returns(bool) { mapping(address => Bet) storage group = stageToGroup(CLAIMING); return group[agent].amount != 0 && currTimePeriod >= STAGE_LENGTH; } // Called by betting agent to place a bet. Adds the agent to the current // betting group. function placeBet(uint256[48] memory predictions) public payable { require(canBet(msg.sender), "Agent cannot bet at this time or has already placed a bet."); require(msg.value > 0, "Bet amount has to be greater than 0"); mapping(address => Bet) storage group = stageToGroup(BETTING); GroupInfo storage groupInfo = stageToGroupInfo[BETTING]; group[msg.sender].amount = msg.value; history[msg.sender][currDay + 1].amount = msg.value; group[msg.sender].predictions = predictions; history[msg.sender][currDay + 1].predictions = predictions; group[msg.sender].winningScale = BASE_WINNING_SCALE; history[msg.sender][currDay + 1].winningScale = BASE_WINNING_SCALE; group[msg.sender].timestamp = now; history[msg.sender][currDay + 1].timestamp = group[msg.sender].timestamp; groupInfo.baseCount++; groupInfo.agents.push(msg.sender); groupInfo.totalBetAmount = groupInfo.totalBetAmount.add(msg.value); for (uint256 i = 0; i < PREDICTIONS_PER_BET; i++) { averagePredictionsHistory[currDay + 1][i] = averagePredictionsHistory[currDay + 1][i].add(predictions[i]); } groupCountHistory[currDay + 2]++; } // Called by betting agent to rank themselves. Sets `win` to true if // `predictions` is within the threshold. function rank() public payable { require(canRank(msg.sender), "Agent cannot rank at this time"); mapping(address => Bet) storage group = stageToGroup(CLAIMING); GroupInfo storage groupInfo = stageToGroupInfo[CLAIMING]; uint256[48] storage predictions = group[msg.sender].predictions; // Calculate total error uint256 totalErr = 0; for (uint256 i = 0; i < PREDICTIONS_PER_BET; i++) { if (groupInfo.consumption[i] > predictions[i]) { totalErr = totalErr.add(groupInfo.consumption[i].sub(predictions[i])); } else { totalErr = totalErr.add(predictions[i].sub(groupInfo.consumption[i])); } } if (totalErr <= TOP_TIER_THRESHOLD * PREDICTIONS_PER_BET) { group[msg.sender].winningScale = TOP_TIER_WINNING_SCALE; history[msg.sender][currDay - 1].winningScale = TOP_TIER_WINNING_SCALE; groupInfo.topTierCount++; groupInfo.baseCount--; } else if (totalErr <= MID_TIER_THRESHOLD * PREDICTIONS_PER_BET) { group[msg.sender].winningScale = MID_TIER_WINNING_SCALE; history[msg.sender][currDay - 1].winningScale = MID_TIER_WINNING_SCALE; groupInfo.midTierCount++; groupInfo.baseCount--; } } // Distribute winnings back to agents who bet. function claimWinnings() public payable { require(canClaim(msg.sender), "Agent cannot claim at this time"); mapping(address => Bet) storage group = stageToGroup(CLAIMING); GroupInfo storage groupInfo = stageToGroupInfo[CLAIMING]; Bet storage bet = group[msg.sender]; uint256 denominator = groupInfo.baseCount * BASE_WINNING_SCALE + groupInfo.midTierCount * MID_TIER_WINNING_SCALE + groupInfo.topTierCount * TOP_TIER_WINNING_SCALE; uint256 reward = 0; if (denominator != 0) { reward = (bet.winningScale.mul(groupInfo.totalBetAmount)).div(denominator); } msg.sender.transfer(reward); delete group[msg.sender]; // TODO: agent removing itself from agent key set. } // Called by Oracle to tell contract the consumption for a time period. function updateConsumption(uint256 consumption) public payable onlyOwner { // TODO: require that the address of the sender is Oracle. stageToGroupInfo[WAITING].consumption.push(consumption); oracleHistory[currDay][currTimePeriod] = consumption; currTimePeriod++; if (currTimePeriod == PREDICTIONS_PER_BET) { // Recording list of betting agents in group history GroupInfo storage bettingGroupInfo = stageToGroupInfo[BETTING]; GroupInfo storage claimingGroupInfo = stageToGroupInfo[CLAIMING]; address[] storage agents = claimingGroupInfo.agents; mapping(address => Bet) storage group = stageToGroup(CLAIMING); // Clear group info and group mapping. for (uint256 i = 0; i < agents.length; i++) { delete group[agents[i]]; } agents.length = 0; claimingGroupInfo.totalBetAmount = 0; claimingGroupInfo.baseCount = 0; claimingGroupInfo.midTierCount = 0; claimingGroupInfo.topTierCount = 0; claimingGroupInfo.consumption.length = 0; uint256 tmp = BETTING; BETTING = CLAIMING; CLAIMING = WAITING; WAITING = tmp; // Reached a new day, reset currTimePeriod and increment currDay currTimePeriod = 0; currDay++; } } // Get calling agent's predictions for stage function getBetPredictionsFromStage(uint256 stage) public view returns(uint256[48] memory) { return stageToGroup(stage)[msg.sender].predictions; } // Get calling agent's predictions for (day ahead - day offset) function getPredictions(uint256 dayOffset) public view returns(uint256[48] memory) { return getPredictionsForAddress(msg.sender, dayOffset); } // Get addr's predictions for (day ahead - day offset) function getPredictionsForAddress(address addr, uint256 dayOffset) public view returns(uint256[48] memory) { return history[addr][currDay + 1 - dayOffset].predictions; } // Get average prediction for (day ahead - day offset) function getAveragePredictions(uint256 dayOffset) public view returns(uint256[48] memory) { uint256 numAgents = groupCountHistory[currDay + 2 - dayOffset]; uint256[48] memory averagePredictions; if (numAgents == 0) return averagePredictions; for (uint256 i = 0; i < PREDICTIONS_PER_BET; i++) { averagePredictions[i] = averagePredictionsHistory[currDay + 1 - dayOffset][i].div(numAgents); } return averagePredictions; } // Get Oracle consumptions for stage function getOracleConsumptionsFromStage(uint256 stage) public view returns(uint256[] memory) { return stageToGroupInfo[stage].consumption; } // Get Oracle consumptions for (day ahead - day offset) function getOracleConsumptions(uint256 dayOffset) public view returns(uint256[48] memory) { return oracleHistory[currDay + 1 - dayOffset]; } // Get array of agents that have placed a bet in the current betting period function getCurrentParticipants() public view returns(address[] memory) { return stageToGroupInfo[BETTING].agents; } // Get bet's winning scale for (day ahead - day offset) function getBetWinningScale(uint256 dayOffset) public view returns(uint256) { return history[msg.sender][currDay + 1 - dayOffset].winningScale; } // Get agent bet predictions from history over past 7 days. Always returns bets in betting, waiting, // claiming stages at first 3 indices, if any. function getBetPredictionsForAgent() public view returns(uint256[48][7] memory) { uint256[48][7] memory agentPredictions; for (uint256 i = 0; i < 7; i++) { agentPredictions[i] = history[msg.sender][currDay + 1 - i].predictions; } return agentPredictions; } // Get agent bet amounts from history over past 7 days. Always returns bets in betting, waiting, // claiming stages at first 3 indices, if any. function getBetAmountsForAgent() public view returns(uint256[7] memory) { uint256[7] memory betAmounts; for (uint256 i = 0; i < 7; i++) { betAmounts[i] = history[msg.sender][currDay + 1 - i].amount; } return betAmounts; } // Get agent bet winning scales from history over past 7 days. Always returns bets in betting, waiting, // claiming stages at first 3 indices, if any. function getBetWinningScalesForAgent() public view returns(uint256[7] memory) { uint256[7] memory winningScales; for (uint256 i = 0; i < 7; i++) { winningScales[i] = history[msg.sender][currDay + 1 - i].winningScale; } return winningScales; } // Get agent bet timestamps from history over past 7 days. Always returns bets in betting, waiting, // claiming stages at first 3 indices, if any. function getBetTimestampsForAgent() public view returns(uint256[7] memory) { uint256[7] memory betTimestamps; for (uint256 i = 0; i < 7; i++) { betTimestamps[i] = history[msg.sender][currDay + 1 - i].timestamp; } return betTimestamps; } }
Get agent bet winning scales from history over past 7 days. Always returns bets in betting, waiting, claiming stages at first 3 indices, if any.
function getBetWinningScalesForAgent() public view returns(uint256[7] memory) { uint256[7] memory winningScales; for (uint256 i = 0; i < 7; i++) { winningScales[i] = history[msg.sender][currDay + 1 - i].winningScale; } return winningScales; }
7,275,534
./full_match/43113/0x9ee8993c2bB8d9670d58F58d9eC239DDc703427c/sources/apps/avai/src/contracts/openzep/TimelockController.sol
Returns the minimum delay for an operation to become valid. This value can be changed by executing an operation that calls `updateDelay`./
function getMinDelay() public view virtual returns (uint256 duration) { return _minDelay; }
7,185,400
./partial_match/42/0x403cF41BD4Ee41A04f09761e363799ed55c8cE57/sources/ProofOfHumanity.sol
Make a fee contribution. _round The round to contribute. _side The side for which to contribute. _contributor The contributor. _amount The amount contributed. _totalRequired The total amount required for this side. return The amount of fees contributed./
function contribute(Round storage _round, Party _side, address payable _contributor, uint _amount, uint _totalRequired) internal returns (uint) { uint contribution; uint remainingETH; (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint(_side)])); _round.contributions[_contributor][uint(_side)] += contribution; _round.paidFees[uint(_side)] += contribution; _round.feeRewards += contribution; _contributor.send(remainingETH); return contribution; }
9,000,240
/** *Submitted for verification at Etherscan.io on 2020-04-26 */ /** *Submitted for verification at Etherscan.io on 2019-08-27 */ pragma solidity ^0.5.11; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c ; //inject UNINIT LOCAL/STATE VAR require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c ; //inject UNINIT LOCAL/STATE VAR return c; } } contract AccountFrozenBalances { using SafeMath for uint256; mapping (address => uint256) private frozen_balances; function _frozen_add(address _account, uint256 _amount) internal returns (bool) { frozen_balances[_account] = frozen_balances[_account].add(_amount); return true; } function _frozen_sub(address _account, uint256 _amount) internal returns (bool) { frozen_balances[_account] = frozen_balances[_account].sub(_amount); return true; } function _frozen_balanceOf(address _account) internal view returns (uint) { return frozen_balances[_account]; } } contract Ownable { address private _owner; address public pendingOwner; modifier onlyOwner() { require(msg.sender == _owner, "caller is not the owner"); _; } modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; } function owner() public view returns (address) { return _owner; } function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(_owner, pendingOwner); _owner = pendingOwner; pendingOwner = address(0); } } contract Whitelisted { address private _whitelistadmin; address public pendingWhiteListAdmin; mapping (address => bool) private _whitelisted; modifier onlyWhitelistAdmin() { require(msg.sender == _whitelistadmin, "caller is not admin of whitelist"); _; } modifier onlyPendingWhitelistAdmin() { require(msg.sender == pendingWhiteListAdmin); _; } event WhitelistAdminTransferred(address indexed previousAdmin, address indexed newAdmin); constructor () internal { _whitelistadmin = msg.sender; _whitelisted[msg.sender] = true; } function whitelistadmin() public view returns (address){ return _whitelistadmin; } function addWhitelisted(address account) public onlyWhitelistAdmin { _whitelisted[account] = true; } function removeWhitelisted(address account) public onlyWhitelistAdmin { _whitelisted[account] = false; } function isWhitelisted(address account) public view returns (bool) { return _whitelisted[account]; } function transferWhitelistAdmin(address newAdmin) public onlyWhitelistAdmin { pendingWhiteListAdmin = newAdmin; } function claimWhitelistAdmin() public onlyPendingWhitelistAdmin { emit WhitelistAdminTransferred(_whitelistadmin, pendingWhiteListAdmin); _whitelistadmin = pendingWhiteListAdmin; pendingWhiteListAdmin = address(0); } } contract Burnable { bool private _burnallow; address private _burner; address public pendingBurner; modifier whenBurn() { require(_burnallow, "burnable: can't burn"); _; } modifier onlyBurner() { require(msg.sender == _burner, "caller is not a burner"); _; } modifier onlyPendingBurner() { require(msg.sender == pendingBurner); _; } event BurnerTransferred(address indexed previousBurner, address indexed newBurner); constructor () internal { _burnallow = true; _burner = msg.sender; } function burnallow() public view returns (bool) { return _burnallow; } function burner() public view returns (address) { return _burner; } function burnTrigger() public onlyBurner { _burnallow = !_burnallow; } function transferWhitelistAdmin(address newBurner) public onlyBurner { pendingBurner = newBurner; } function claimBurner() public onlyPendingBurner { emit BurnerTransferred(_burner, pendingBurner); _burner = pendingBurner; pendingBurner = address(0); } } contract Meltable { mapping (address => bool) private _melters; address private _melteradmin; address public pendingMelterAdmin; modifier onlyMelterAdmin() { require (msg.sender == _melteradmin, "caller not a melter admin"); _; } modifier onlyMelter() { require (_melters[msg.sender] == true, "can't perform melt"); _; } modifier onlyPendingMelterAdmin() { require(msg.sender == pendingMelterAdmin); _; } event MelterTransferred(address indexed previousMelter, address indexed newMelter); constructor () internal { _melteradmin = msg.sender; _melters[msg.sender] = true; } function melteradmin() public view returns (address) { return _melteradmin; } function addToMelters(address account) public onlyMelterAdmin { _melters[account] = true; } function removeFromMelters(address account) public onlyMelterAdmin { _melters[account] = false; } function transferMelterAdmin(address newMelter) public onlyMelterAdmin { pendingMelterAdmin = newMelter; } function claimMelterAdmin() public onlyPendingMelterAdmin { emit MelterTransferred(_melteradmin, pendingMelterAdmin); _melteradmin = pendingMelterAdmin; pendingMelterAdmin = address(0); } } contract Mintable { mapping (address => bool) private _minters; address private _minteradmin; address public pendingMinterAdmin; modifier onlyMinterAdmin() { require (msg.sender == _minteradmin, "caller not a minter admin"); _; } modifier onlyMinter() { require (_minters[msg.sender] == true, "can't perform mint"); _; } modifier onlyPendingMinterAdmin() { require(msg.sender == pendingMinterAdmin); _; } event MinterTransferred(address indexed previousMinter, address indexed newMinter); constructor () internal { _minteradmin = msg.sender; _minters[msg.sender] = true; } function minteradmin() public view returns (address) { return _minteradmin; } function addToMinters(address account) public onlyMinterAdmin { _minters[account] = true; } function removeFromMinters(address account) public onlyMinterAdmin { _minters[account] = false; } function transferMinterAdmin(address newMinter) public onlyMinterAdmin { pendingMinterAdmin = newMinter; } function claimMinterAdmin() public onlyPendingMinterAdmin { emit MinterTransferred(_minteradmin, pendingMinterAdmin); _minteradmin = pendingMinterAdmin; pendingMinterAdmin = address(0); } } contract Pausable { bool private _paused; address private _pauser; address public pendingPauser; modifier onlyPauser() { require(msg.sender == _pauser, "caller is not a pauser"); _; } modifier onlyPendingPauser() { require(msg.sender == pendingPauser); _; } event PauserTransferred(address indexed previousPauser, address indexed newPauser); constructor () internal { _paused = false; _pauser = msg.sender; } function paused() public view returns (bool) { return _paused; } function pauser() public view returns (address) { return _pauser; } function pauseTrigger() public onlyPauser { _paused = !_paused; } function transferPauser(address newPauser) public onlyPauser { pendingPauser = newPauser; } function claimPauser() public onlyPendingPauser { emit PauserTransferred(_pauser, pendingPauser); _pauser = pendingPauser; pendingPauser = address(0); } } contract TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes memory _extraData) public; } contract GuardianToken is AccountFrozenBalances, Ownable, Whitelisted, Burnable, Pausable, Mintable, Meltable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; modifier canTransfer() { if(paused()){ require (isWhitelisted(msg.sender) == true, "can't perform an action"); } _; } event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Freeze(address indexed from, uint256 amount); event Melt(address indexed from, uint256 amount); event MintFrozen(address indexed to, uint256 amount); event FrozenTransfer(address indexed from, address indexed to, uint256 value); constructor (string memory _name, string memory _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; mint(msg.sender, 800000000000000); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account].add(_frozen_balanceOf(account)); } function transfer(address recipient, uint256 amount) public canTransfer returns (bool) { require(recipient != address(this), "can't transfer tokens to the contract address"); _transfer(msg.sender, recipient, amount); return true; } function allowance(address _owner, address spender) public view returns (uint256) { return _allowances[_owner][spender]; } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /* Approve and then communicate the approved contract in a single tx */ function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool) { TokenRecipient spender ; //inject UNINIT LOCAL/STATE VAR if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } else { return false; } } function transferFrom(address sender, address recipient, uint256 amount) public canTransfer returns (bool) { require(recipient != address(this), "can't transfer tokens to the contract address"); _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } function burn(uint256 amount) public whenBurn { _burn(msg.sender, amount); } function burnFrom(address account, uint256 amount) public whenBurn { _burnFrom(account, amount); } function destroy(address account, uint256 amount) public onlyOwner { _burn(account, amount); } function destroyFrozen(address account, uint256 amount) public onlyOwner { _burnFrozen(account, amount); } function mintBatchToken(address[] calldata accounts, uint256[] calldata amounts) external onlyMinter returns (bool) { require(accounts.length > 0, "mintBatchToken: transfer should be to at least one address"); require(accounts.length == amounts.length, "mintBatchToken: recipients.length != amounts.length"); for (uint256 i ; i < accounts.length; i++) { //inject UNINIT LOCAL/STATE VAR _mint(accounts[i], amounts[i]); } return true; } function transferFrozenToken(address from, address to, uint256 amount) public onlyOwner returns (bool) { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _frozen_sub(from, amount); _frozen_add(to, amount); emit FrozenTransfer(from, to, amount); emit Transfer(from, to, amount); return true; } function freezeTokens(address account, uint256 amount) public onlyOwner returns (bool) { _freeze(account, amount); emit Transfer(account, address(this), amount); return true; } function meltTokens(address account, uint256 amount) public onlyMelter returns (bool) { _melt(account, amount); emit Transfer(address(this), account, amount); return true; } function mintFrozenTokens(address account, uint256 amount) public onlyMinter returns (bool) { _mintfrozen(account, amount); return true; } function mintBatchFrozenTokens(address[] calldata accounts, uint256[] calldata amounts) external onlyMinter returns (bool) { require(accounts.length > 0, "mintBatchFrozenTokens: transfer should be to at least one address"); require(accounts.length == amounts.length, "mintBatchFrozenTokens: recipients.length != amounts.length"); for (uint256 i ; i < accounts.length; i++) { //inject UNINIT LOCAL/STATE VAR _mintfrozen(accounts[i], amounts[i]); } return true; } function meltBatchTokens(address[] calldata accounts, uint256[] calldata amounts) external onlyMelter returns (bool) { require(accounts.length > 0, "mintBatchFrozenTokens: transfer should be to at least one address"); require(accounts.length == amounts.length, "mintBatchFrozenTokens: recipients.length != amounts.length"); for (uint256 i ; i < accounts.length; i++) { //inject UNINIT LOCAL/STATE VAR _melt(accounts[i], amounts[i]); emit Transfer(address(this), accounts[i], amounts[i]); } return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); require(account != address(this), "ERC20: mint to the contract address"); require(amount > 0, "ERC20: mint amount should be > 0"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(this), account, amount); } function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(this), value); } function _approve(address _owner, address spender, uint256 value) internal { require(_owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[_owner][spender] = value; emit Approval(_owner, spender, value); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } function _freeze(address account, uint256 amount) internal { require(account != address(0), "ERC20: freeze from the zero address"); require(amount > 0, "ERC20: freeze from the address: amount should be > 0"); _balances[account] = _balances[account].sub(amount); _frozen_add(account, amount); emit Freeze(account, amount); } function _mintfrozen(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint frozen to the zero address"); require(account != address(this), "ERC20: mint frozen to the contract address"); require(amount > 0, "ERC20: mint frozen amount should be > 0"); _totalSupply = _totalSupply.add(amount); emit Transfer(address(this), account, amount); _frozen_add(account, amount); emit MintFrozen(account, amount); } function _melt(address account, uint256 amount) internal { require(account != address(0), "ERC20: melt from the zero address"); require(amount > 0, "ERC20: melt from the address: value should be > 0"); require(_frozen_balanceOf(account) >= amount, "ERC20: melt from the address: balance < amount"); _frozen_sub(account, amount); _balances[account] = _balances[account].add(amount); emit Melt(account, amount); } function _burnFrozen(address account, uint256 amount) internal { require(account != address(0), "ERC20: frozen burn from the zero address"); _totalSupply = _totalSupply.sub(amount); _frozen_sub(account, amount); emit Transfer(account, address(this), amount); } }
Approve and then communicate the approved contract in a single tx /
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool) { if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; return false; } }
12,591,042
./full_match/4/0xED52F32Ca1f62414A3E85266b3E087C4744F6a40/sources/Donor.sol
parts[1] = 'Hello';parts[2] = '</text><text x="10" y="40" class="base">';parts[3] = 'World!';
function tokenURI(uint256 tokenId) override public view returns (string memory) { string[5] memory parts; parts[1] = getContributor(tokenId)[0]; parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getContributor(tokenId)[1]; parts[4] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4])); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; }
745,942
// SPDX-License-Identifier: UNLICENSED // It's trivially easy to exploit a weak PRNG based NFT. // Just bundle this with a flashbots bundle where the mint occurs. // // It's also trivially easy to detect/prevent with a took like slither: // https://github.com/crytic/slither/wiki/Detector-Documentation#weak-PRNG pragma solidity ^0.8.0; import "./WolfGame/Woolf.sol"; contract CatchTheWolf { address internal constant WOOLF_ADDRESS = 0xEB834ae72B30866af20a6ce5440Fa598BfAd3a42; Woolf private constant WGAME = Woolf(WOOLF_ADDRESS); constructor() payable { } receive() external payable { } fallback() external payable { } // A call we can revert on function roll_alpha() public { view_alpha(); } // A view we can test with function view_alpha() public view { // We need to do it this way to account for theft and mixed ids. uint256 seed = WGAME.totalSupply() + 1; uint256 prn = random(seed); // We want to roll a wolf bool isSheep = (prn & 0xFFFF) % 10 != 0; require(!isSheep, 'Sheep'); // Let's check that we'll own it. bool isOurs = ((prn >> 245) % 10) != 0; require(isOurs, "Stolen"); } // The weak prng which started it all function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ))); } }
The weak prng which started it all
function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ))); }
6,480,816
// SPDX-License-Identifier: MIT pragma solidity ^0.5.17; interface IERC20 { function TOTALSUPPLY676() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF365(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER984(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE421(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE350(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM233(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER7(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL756(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD231(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB723(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB723(a, b, "SafeMath: subtraction overflow"); } function SUB723(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL124(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV477(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV477(a, b, "SafeMath: division by zero"); } function DIV477(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD902(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD902(a, b, "SafeMath: modulo by zero"); } function MOD902(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT563(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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); } function TOPAYABLE474(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE638(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER541(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.TRANSFER984.selector, to, value)); } function SAFETRANSFERFROM607(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.TRANSFERFROM233.selector, from, to, value)); } function SAFEAPPROVE839(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE421(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.APPROVE350.selector, spender, value)); } function SAFEINCREASEALLOWANCE550(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE421(address(this), spender).ADD231(value); CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.APPROVE350.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE384(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE421(address(this), spender).SUB723(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.APPROVE350.selector, spender, newAllowance)); } function CALLOPTIONALRETURN431(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT563(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // interface IController { function WITHDRAW26(address, uint256) external; //inject NONSTANDARD NAMING function BALANCEOF365(address) external view returns (uint256); //inject NONSTANDARD NAMING function EARN979(address, uint256) external; //inject NONSTANDARD NAMING function WANT15(address) external view returns (address); //inject NONSTANDARD NAMING function REWARDS956() external view returns (address); //inject NONSTANDARD NAMING function VAULTS197(address) external view returns (address); //inject NONSTANDARD NAMING function STRATEGIES736(address) external view returns (address); //inject NONSTANDARD NAMING } // interface Gauge { function DEPOSIT301(uint256) external; //inject NONSTANDARD NAMING function BALANCEOF365(address) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAW26(uint256) external; //inject NONSTANDARD NAMING } // interface Mintr { function MINT474(address) external; //inject NONSTANDARD NAMING } // interface Uni { function SWAPEXACTTOKENSFORTOKENS884( //inject NONSTANDARD NAMING uint256, uint256, address[] calldata, address, uint256 ) external; } // interface ICurveFi { function GET_VIRTUAL_PRICE966() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY5( //inject NONSTANDARD NAMING // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function ADD_LIQUIDITY5( //inject NONSTANDARD NAMING // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function REMOVE_LIQUIDITY_IMBALANCE212(uint256[4] calldata amounts, uint256 max_burn_amount) external; //inject NONSTANDARD NAMING function REMOVE_LIQUIDITY359(uint256 _amount, uint256[4] calldata amounts) external; //inject NONSTANDARD NAMING function EXCHANGE368( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; } interface Zap { function REMOVE_LIQUIDITY_ONE_COIN241( //inject NONSTANDARD NAMING uint256, int128, uint256 ) external; } // // NOTE: Basically an alias for Vaults interface yERC20 { function DEPOSIT301(uint256 _amount) external; //inject NONSTANDARD NAMING function WITHDRAW26(uint256 _amount) external; //inject NONSTANDARD NAMING function GETPRICEPERFULLSHARE41() external view returns (uint256); //inject NONSTANDARD NAMING } // interface VoterProxy { function WITHDRAW26( //inject NONSTANDARD NAMING address _gauge, address _token, uint256 _amount ) external returns (uint256); function BALANCEOF365(address _gauge) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAWALL38(address _gauge, address _token) external returns (uint256); //inject NONSTANDARD NAMING function DEPOSIT301(address _gauge, address _token) external; //inject NONSTANDARD NAMING function HARVEST174(address _gauge) external; //inject NONSTANDARD NAMING function LOCK81() external; //inject NONSTANDARD NAMING } contract StrategyCurve3CrvVoterProxy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant want150 = address(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490); //inject NONSTANDARD NAMING address public constant crv64 = address(0xD533a949740bb3306d119CC777fa900bA034cd52); //inject NONSTANDARD NAMING address public constant uni956 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING address public constant weth657 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // used for crv <> weth <> dai route //inject NONSTANDARD NAMING address public constant dai412 = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING address public constant curve384 = address(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); //inject NONSTANDARD NAMING address public constant gauge100 = address(0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A); //inject NONSTANDARD NAMING address public constant voter170 = address(0xF147b8125d2ef93FB6965Db97D6746952a133934); //inject NONSTANDARD NAMING uint256 public keepCRV = 1000; uint256 public performanceFee = 450; uint256 public strategistReward = 50; uint256 public withdrawalFee = 50; uint256 public constant fee_denominator706 = 10000; //inject NONSTANDARD NAMING address public proxy; address public governance; address public controller; address public strategist; uint256 public earned; // lifetime strategy earnings denominated in `want` token event HARVESTED63(uint wantEarned, uint lifetimeEarned); //inject NONSTANDARD NAMING constructor(address _controller) public { governance = msg.sender; strategist = msg.sender; controller = _controller; } function GETNAME974() external pure returns (string memory) { //inject NONSTANDARD NAMING return "StrategyCurve3CrvVoterProxy"; } function SETSTRATEGIST311(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance || msg.sender == strategist, "!authorized"); strategist = _strategist; } function SETKEEPCRV999(uint256 _keepCRV) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } function SETWITHDRAWALFEE117(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); withdrawalFee = _withdrawalFee; } function SETPERFORMANCEFEE881(uint256 _performanceFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function SETSTRATEGISTREWARD913(uint _strategistReward) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategistReward = _strategistReward; } function SETPROXY556(address _proxy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); proxy = _proxy; } function DEPOSIT301() public { //inject NONSTANDARD NAMING uint256 _want = IERC20(want150).BALANCEOF365(address(this)); if (_want > 0) { IERC20(want150).SAFETRANSFER541(proxy, _want); VoterProxy(proxy).DEPOSIT301(gauge100, want150); } } // Controller only function for creating additional rewards from dust function WITHDRAW26(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); require(want150 != address(_asset), "want"); require(crv64 != address(_asset), "crv"); require(dai412 != address(_asset), "dai"); balance = _asset.BALANCEOF365(address(this)); _asset.SAFETRANSFER541(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function WITHDRAW26(uint256 _amount) external { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want150).BALANCEOF365(address(this)); if (_balance < _amount) { _amount = _WITHDRAWSOME169(_amount.SUB723(_balance)); _amount = _amount.ADD231(_balance); } uint256 _fee = _amount.MUL124(withdrawalFee).DIV477(fee_denominator706); IERC20(want150).SAFETRANSFER541(IController(controller).REWARDS956(), _fee); address _vault = IController(controller).VAULTS197(address(want150)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want150).SAFETRANSFER541(_vault, _amount.SUB723(_fee)); } function _WITHDRAWSOME169(uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING return VoterProxy(proxy).WITHDRAW26(gauge100, want150, _amount); } // Withdraw all funds, normally used when migrating strategies function WITHDRAWALL38() external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); _WITHDRAWALL587(); balance = IERC20(want150).BALANCEOF365(address(this)); address _vault = IController(controller).VAULTS197(address(want150)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want150).SAFETRANSFER541(_vault, balance); } function _WITHDRAWALL587() internal { //inject NONSTANDARD NAMING VoterProxy(proxy).WITHDRAWALL38(gauge100, want150); } function HARVEST174() public { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!authorized"); VoterProxy(proxy).HARVEST174(gauge100); uint256 _crv = IERC20(crv64).BALANCEOF365(address(this)); if (_crv > 0) { uint256 _keepCRV = _crv.MUL124(keepCRV).DIV477(fee_denominator706); IERC20(crv64).SAFETRANSFER541(voter170, _keepCRV); _crv = _crv.SUB723(_keepCRV); IERC20(crv64).SAFEAPPROVE839(uni956, 0); IERC20(crv64).SAFEAPPROVE839(uni956, _crv); address[] memory path = new address[](3); path[0] = crv64; path[1] = weth657; path[2] = dai412; Uni(uni956).SWAPEXACTTOKENSFORTOKENS884(_crv, uint256(0), path, address(this), now.ADD231(1800)); } uint256 _dai = IERC20(dai412).BALANCEOF365(address(this)); if (_dai > 0) { IERC20(dai412).SAFEAPPROVE839(curve384, 0); IERC20(dai412).SAFEAPPROVE839(curve384, _dai); ICurveFi(curve384).ADD_LIQUIDITY5([_dai, 0, 0], 0); } uint256 _want = IERC20(want150).BALANCEOF365(address(this)); if (_want > 0) { uint256 _fee = _want.MUL124(performanceFee).DIV477(fee_denominator706); uint256 _reward = _want.MUL124(strategistReward).DIV477(fee_denominator706); IERC20(want150).SAFETRANSFER541(IController(controller).REWARDS956(), _fee); IERC20(want150).SAFETRANSFER541(strategist, _reward); DEPOSIT301(); } VoterProxy(proxy).LOCK81(); earned = earned.ADD231(_want); emit HARVESTED63(_want, earned); } function BALANCEOFWANT698() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(want150).BALANCEOF365(address(this)); } function BALANCEOFPOOL677() public view returns (uint256) { //inject NONSTANDARD NAMING return VoterProxy(proxy).BALANCEOF365(gauge100); } function BALANCEOF365() public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEOFWANT698().ADD231(BALANCEOFPOOL677()); } function SETGOVERNANCE126(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETCONTROLLER597(address _controller) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); controller = _controller; } }
inject NONSTANDARD NAMING
function WANT15(address) external view returns (address);
14,088,931
./full_match/56/0xE50552410cF62BCEd605C9894C7E532D9dC35660/sources/project_/contracts/current/Libraries/Algorithm.sol
Days for selling taking into account bnb entering/leaving the TLV last daysWe storage the snapshots BNB diff to storage how much BNB was withdraw/invest on the miner each datBNB investing diff along the days vs withdrawsWe take the ratio diff, and get the amount of days to add/substract to daysSellWe adjust daysSell taking into acount the limits
function daysForSelling(uint256 timestamp) public view returns (uint256) { uint256 posRatio = 0; uint256 negRatio = 0; uint256 globalDiff = 0; uint256 [7] memory _withdrawals = lastDaysWithdrawals(timestamp); uint256 [7] memory _investments = lastDaysInvestments(timestamp); (posRatio, negRatio) = getRatiosFromInvWitDiff(_investments, _withdrawals); if(negRatio > posRatio){ globalDiff = (negRatio.sub(posRatio)).div(100); } else{ globalDiff = (posRatio.sub(negRatio)).div(100); } if(negRatio > posRatio){ daysSell = daysSell.add(globalDiff); if(daysSell > maxDaysSell){ daysSell = maxDaysSell; } if(globalDiff < daysSell && daysSell.sub(globalDiff) > minDaysSell){ daysSell = daysSell.sub(globalDiff); } else{ daysSell = minDaysSell; } } return daysSell; }
3,243,306
./partial_match/1/0xe2479a364B652efF8918a8ab6042eb3f98A585C9/sources/Love_Swap_V1.sol
uni:USDT->ETH,cofix:ETH->USDT,包含cofi价值
function doitForCofixGetCofi(uint256 ethAmount, uint256 cofiPrice) public payable { uint256 ethBefore = address(this).balance; uint256 tokenBefore = IERC20(USDTAddress).balanceOf(address(this)); uint256 cofiBefore = IERC20(cofiAddress).balanceOf(address(this)); address[] memory data = new address[](2); data[0] = WETHAddress; data[1] = USDTAddress; UniswapV2Router(uniRouter).swapExactETHForTokens.value(ethAmount)(0,data,address(this),block.timestamp + 3600); uint256 tokenMiddle = IERC20(USDTAddress).balanceOf(address(this)).sub(tokenBefore); CoFiXRouter(cofixRouter).swapExactTokensForETH.value(nestPrice)(USDTAddress,tokenMiddle,1,address(this), address(this), block.timestamp + 3600); uint256 cofiCost = ethBefore.sub(address(this).balance); require(IERC20(cofiAddress).balanceOf(address(this)).sub(cofiBefore).mul(cofiPrice).div(1 ether) > cofiCost, "cofi not enough"); require(IERC20(USDTAddress).balanceOf(address(this)) >= tokenBefore, "token not enough"); }
3,601,547
//SPDX-License-Identifier: MIT // ___ ___ ______ __ // /__/\ /__/\ /_____/\ /_/\ // \::\ \\ \ \ \:::_ \ \ \:\ \ // \::\/_\ .\ \ \:\ \ \ \ \:\ \ // \:: ___::\ \ \:\ \ \ \ \:\ \____ // \: \ \\::\ \ \:\_\ \ \ \:\/___/\ // \__\/ \::\/ \_____\/ \_____\/ /// @title Ribbit Daycare /// @author Hol /// @notice A wrapper for Ribbits with ownership. pragma solidity ^0.8.4; import "./Interfaces.sol"; contract RibbitDaycare is IERC721Receiver { SURF surf; Ribbits ribbits; wRBT wrbt; // Price in SURF per day uint256 public daycareFee; // Hard limit to number of stakers uint256 public constant maxStakingSlots = 500; // Current Stakes uint256 public currentStakes; uint256 public surfRewards; uint256 surfDivChange; // wRBT Staker => Amount mapping(address => uint256) public stakerBalances; // Snapshots to calculate the reward mapping(address => uint256) rewardSnapshots; // Index => RibbitID uint256[] public ribbitIndex; // Index => Staker address[] public stakerIndex; // RibbitID => Owner mapping(uint256 => address) public ribbitOwners; // RibbitID => Number of Days mapping(uint256 => uint256) public ribbitDays; // RibbitID => Depositted Timestamp mapping(uint256 => uint256) public depositDates; // address => SURF Balance mapping(address => uint256) public surfBalances; constructor( address _surf, address _ribbits, address _wrbt, uint256 _daycareFee ) { surf = SURF(_surf); ribbits = Ribbits(_ribbits); wrbt = wRBT(_wrbt); daycareFee = _daycareFee; ribbits.setApprovalForAll(_wrbt, true); } /// @dev Gets the ID's of ribbits currently deposited by someone. /// @param owner The address of the owner. /// @return ribbitList List of ribbits owned by the address. function GetDepositedRibbits(address owner) external view returns (uint256[] memory ribbitList) { uint256 counter = 0; for (uint256 index = 0; index < ribbitIndex.length; index++) { if (ribbitOwners[ribbitIndex[index]] == owner) { counter++; } } ribbitList = new uint256[](counter); counter = 0; for (uint256 index = 0; index < ribbitIndex.length; index++) { if (ribbitOwners[ribbitIndex[index]] == owner) { ribbitList[counter] = ribbitIndex[index]; counter++; } } return ribbitList; } /// @dev Stakes wRBT's in the contract. /// @param amount The amount of wRBT staked, whole number. /// Sticking to whole numbers for simplicity, as staking 0.5 wRBT /// that is currently not in contract is impossible to withdraw /// for half a Ribbit! function stakewRBT(uint256 amount) public { require(amount % (1 * 10**18) == 0 && amount > 0, "Must be whole wRBT"); stakerBalances[msg.sender] += amount; withdrawSURF(); rewardSnapshots[msg.sender] = surfRewards; currentStakes += amount; wrbt.transferFrom(msg.sender, address(this), amount); } /// @dev Unstakes wRBT's in the contract if there is supply held. function unstakewRBT(uint256 amount) public { require( amount > 0 && stakerBalances[msg.sender] >= amount, "Not enough staked" ); require(wrbtAvailable() >= amount, "Not enough wRBT in contract"); require(amount % (1 * 10**18) == 0 && amount > 0, "Must be whole wRBT"); withdrawSURF(); stakerBalances[msg.sender] -= amount; currentStakes -= amount; wrbt.transfer(msg.sender, amount); } /// @dev Withdraws the SURF rewards of the sender and changes snapshot function withdrawSURF() public { uint256 surfBalance = surf.balanceOf(address(this)); uint256 unclaimedSurf = stakerBalances[msg.sender] * (surfRewards - rewardSnapshots[msg.sender]); if (surfBalance > 0 && unclaimedSurf > 0) { rewardSnapshots[msg.sender] = surfRewards; surf.transfer(msg.sender, unclaimedSurf); } } /// @dev Deposits a ribbit in exchange of a wRBT that is currently staked in the contract. /// @param _ribbitIds Array with the id's of the ribbits. /// @param _days Amount of days to deposit for, paid in SURF with bulk discount. function daycareDeposit(uint256[] memory _ribbitIds, uint256 _days) public { require(_days > 0, "Days can't be zero"); uint256 ribbitNumber = _ribbitIds.length; uint256 surfAmount = _days * daycareFee; require( wrbtAvailable() / (1 * 10**18) >= ribbitNumber, "Insufficient wRBT staked in contract" ); // Add time and deposit date to each ribbit for (uint256 index = 0; index < ribbitNumber; index++) { uint256 ribId = _ribbitIds[index]; ribbitDays[ribId] = _days * 1 days; depositDates[ribId] = block.timestamp; ribbitOwners[ribId] = msg.sender; if (!hasRibbitIndex(ribId)) { ribbitIndex.push(ribId); } } // Transfer each ribbit for (uint256 index = 0; index < ribbitNumber; index++) { ribbits.safeTransferFrom( msg.sender, address(this), _ribbitIds[index] ); } distributeSURF(surfAmount); surf.transferFrom(msg.sender, address(this), surfAmount); wrbt.transfer(msg.sender, ribbitNumber * 10**18); } /// @dev Wraps all ribbits owned by the contract that have no time left. function wrapAbandonedRibbits() public { //TODO: Bulk wrap all the ribbits with no time left, remove from lists, etc. uint256[] memory abandonedRibbits = getAbandonedRibbits(); require(abandonedRibbits.length > 0, "No abandonded ribbits"); for (uint256 index = 0; index < abandonedRibbits.length; index++) { delete ribbitOwners[abandonedRibbits[index]]; delete depositDates[abandonedRibbits[index]]; delete ribbitDays[abandonedRibbits[index]]; } wrbt.wrap(abandonedRibbits); } /// @dev Withdraws ribbits by their owner in exchange of a wRBT /// @param _ribbitIds Array with the ids of all the Ribbits function withdrawRibbits(uint256[] memory _ribbitIds) public { uint256 amount = _ribbitIds.length; for (uint256 index = 0; index < amount; index++) { uint256 _ribbitId = _ribbitIds[index]; require( ribbits.ownerOf(_ribbitId) == address(this), "Ribbit not in contract" ); require(ribbitOwners[_ribbitId] == msg.sender, "Not ribbit owner"); delete ribbitOwners[_ribbitId]; delete depositDates[_ribbitId]; delete ribbitDays[_ribbitId]; ribbits.safeTransferFrom(address(this), msg.sender, _ribbitId); } wrbt.transferFrom(msg.sender, address(this), amount * 10**18); } /// @dev Returns an array with all the abandoned ribbits. function getAbandonedRibbits() public view returns (uint256[] memory abandonedRibbits) { uint256 ribbitId; uint256 count; for (uint256 index = 0; index < ribbitIndex.length; index++) { ribbitId = ribbitIndex[index]; if (isAbandoned(ribbitId)) { count++; } } abandonedRibbits = new uint256[](count); count = 0; for (uint256 index = 0; index < ribbitIndex.length; index++) { ribbitId = ribbitIndex[index]; if (isAbandoned(ribbitId)) { abandonedRibbits[count] = ribbitId; count++; } } return abandonedRibbits; } /// @dev Calculates whether a deposited ribbit is out of time. /// @param _ribbitId The id of the ribbit. function isAbandoned(uint256 _ribbitId) public view returns (bool) { return depositDates[_ribbitId] + ribbitDays[_ribbitId] < block.timestamp && ribbits.ownerOf(_ribbitId) == address(this); } /// @dev Adds day credits to the ribbit specified, must be already deposited /// @param _ribbitId The ID of the ribbit. /// @param amount The number of days to add to the ribbit. function addDays(uint256 _ribbitId, uint256 amount) public { require( ribbits.ownerOf(_ribbitId) == address(this), "Ribbit not in daycare" ); ribbitDays[_ribbitId] += amount * 1 days; uint256 surfAmount = amount * daycareFee; distributeSURF(surfAmount); surf.transferFrom(msg.sender, address(this), surfAmount); } /// @dev Adds the calculated surf reward dividend for the current snapshot /// @param amount The amount of SURF to be distributed function distributeSURF(uint256 amount) internal { require(amount > 0 && currentStakes > 0); amount = amount + surfDivChange - (amount * surf.transferFee()) / 1000; surfRewards += amount / currentStakes; surfDivChange = amount % currentStakes; } /// @dev Returns the balance of wRBT held by the contract, rounded to a whole number function wrbtAvailable() public view returns (uint256) { return wrbt.balanceOf(address(this)); } /// @dev Checks whether the ribbit is in the index function hasRibbitIndex(uint256 _ribbitId) internal view returns (bool) { for (uint256 index = 0; index < ribbitIndex.length; index++) { if (ribbitIndex[index] == _ribbitId) return true; } return false; } /// @dev Needed to deposit ribbits? function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { if (this.onERC721Received.selector != 0x150b7a02) { return 0x150b7a02; } return this.onERC721Received.selector; } }
Adds the calculated surf reward dividend for the current snapshot amount The amount of SURF to be distributed
function distributeSURF(uint256 amount) internal { require(amount > 0 && currentStakes > 0); amount = amount + surfDivChange - (amount * surf.transferFee()) / 1000; surfRewards += amount / currentStakes; surfDivChange = amount % currentStakes; }
13,022,420
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title BankStorage * This contract provides the data structures, variables, and getters for Bank */ contract BankStorage { /*Variables*/ string name; // role identifier for keeper that can make liquidations bytes32 public constant KEEPER_ROLE = keccak256("KEEPER_ROLE"); // role identifier for price updater bytes32 public constant REPORTER_ROLE = keccak256("REPORTER_ROLE"); struct Reserve { uint256 collateralBalance; uint256 debtBalance; uint256 interestRate; uint256 originationFee; uint256 collateralizationRatio; uint256 liquidationPenalty; address oracleContract; uint256 period; } struct Token { address tokenAddress; uint256 price; uint256 priceGranularity; uint256 tellorRequestId; uint256 reserveBalance; uint256 lastUpdatedAt; } struct Vault { uint256 collateralAmount; uint256 debtAmount; uint256 createdAt; } mapping(address => Vault) public vaults; Token debt; Token collateral; Reserve reserve; /** * @dev Getter function for the bank name * @return bank name */ function getName() public view returns (string memory) { return name; } /** * @dev Getter function for the current interest rate * @return interest rate */ function getInterestRate() public view returns (uint256) { return reserve.interestRate; } /** * @dev Getter function for the origination fee * @return origination fee */ function getOriginationFee() public view returns (uint256) { return reserve.originationFee; } /** * @dev Getter function for the current collateralization ratio * @return collateralization ratio */ function getCollateralizationRatio() public view returns (uint256) { return reserve.collateralizationRatio; } /** * @dev Getter function for the liquidation penalty * @return liquidation penalty */ function getLiquidationPenalty() public view returns (uint256) { return reserve.liquidationPenalty; } /** * @dev Getter function for debt token address * @return debt token price */ function getDebtTokenAddress() public view returns (address) { return debt.tokenAddress; } /** * @dev Getter function for the debt token(reserve) price * @return debt token price */ function getDebtTokenPrice() public view returns (uint256) { return debt.price; } /** * @dev Getter function for the debt token price granularity * @return debt token price granularity */ function getDebtTokenPriceGranularity() public view returns (uint256) { return debt.priceGranularity; } /** * @dev Getter function for the debt token last update time * @return debt token last update time */ function getDebtTokenLastUpdatedAt() public view returns (uint256) { return debt.lastUpdatedAt; } /** * @dev Getter function for debt token address * @return debt token price */ function getCollateralTokenAddress() public view returns (address) { return collateral.tokenAddress; } /** * @dev Getter function for the collateral token price * @return collateral token price */ function getCollateralTokenPrice() public view returns (uint256) { return collateral.price; } /** * @dev Getter function for the collateral token price granularity * @return collateral token price granularity */ function getCollateralTokenPriceGranularity() public view returns (uint256) { return collateral.priceGranularity; } /** * @dev Getter function for the collateral token last update time * @return collateral token last update time */ function getCollateralTokenLastUpdatedAt() public view returns (uint256) { return collateral.lastUpdatedAt; } /** * @dev Getter function for the debt token(reserve) balance * @return debt reserve balance */ function getReserveBalance() public view returns (uint256) { return reserve.debtBalance; } /** * @dev Getter function for the debt reserve collateral balance * @return collateral reserve balance */ function getReserveCollateralBalance() public view returns (uint256) { return reserve.collateralBalance; } /** * @dev Getter function for the user's vault collateral amount * @return collateral amount */ function getVaultCollateralAmount() public view returns (uint256) { return vaults[msg.sender].collateralAmount; } /** * @dev Getter function for the user's vault debt amount * @return debt amount */ function getVaultDebtAmount() public view returns (uint256) { return vaults[msg.sender].debtAmount; } /** * @dev Getter function for the user's vault debt amount * uses a simple interest formula (i.e. not compound interest) * @return principal debt amount */ function getVaultRepayAmount() public view returns (uint256 principal) { principal = vaults[msg.sender].debtAmount; uint256 periodsPerYear = 365 days / reserve.period; uint256 periodsElapsed = (block.timestamp / reserve.period) - (vaults[msg.sender].createdAt / reserve.period); principal += ((principal * reserve.interestRate) / 10000 / periodsPerYear) * periodsElapsed; } /** * @dev Getter function for the collateralization ratio * @return collateralization ratio */ function getVaultCollateralizationRatio(address vaultOwner) public view returns (uint256) { if (vaults[vaultOwner].debtAmount == 0) { return 0; } else { return (((vaults[vaultOwner].collateralAmount * collateral.price) / collateral.priceGranularity) * 10000) / ((vaults[vaultOwner].debtAmount * debt.price) / debt.priceGranularity); } } }
Getter function for the user's vault debt amount return debt amount/
function getVaultDebtAmount() public view returns (uint256) { return vaults[msg.sender].debtAmount; }
12,910,264
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; contract TaskBlacklist is Ownable { /// @notice The blacklist of the tasks. mapping(bytes32 => bool) private _blacklistedTasks; event TaskBlacklistAdded(bytes32 taskId); event TaskBlacklistRemoved(bytes32 taskId); modifier onlyValidTask(bytes32 _taskId) { require(isValidTask(_taskId), "Invalid task"); _; } /// @notice Ban the task from being able to be executed. /// @param _taskId The task to be banned. function banTask(bytes32 _taskId) external onlyOwner { _blacklistedTasks[_taskId] = true; emit TaskBlacklistAdded(_taskId); } /// @notice Unban the task. /// @param _taskId The task to be unbanned. function unbanTask(bytes32 _taskId) external onlyOwner { require(!isValidTask(_taskId), "Not banned"); _blacklistedTasks[_taskId] = false; emit TaskBlacklistRemoved(_taskId); } /// @notice Return if the task is valid. /// @param _taskId The task to be queried. function isValidTask(bytes32 _taskId) public view returns (bool) { return (!_blacklistedTasks[_taskId]); } }
Unban the task. _taskId The task to be unbanned.
function unbanTask(bytes32 _taskId) external onlyOwner { require(!isValidTask(_taskId), "Not banned"); _blacklistedTasks[_taskId] = false; emit TaskBlacklistRemoved(_taskId); }
12,843,597
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Report Framework * @notice Smart Contract developed for the Harmony One Round 2 Hackathon on Gitcoin * @dev On-Chain reporting of a single metric and its count defined by a key and a category. * It will store each in a bucket denoted by the {Report}-{getReportingPeriodFor} function, * which defines a bucket given a timestamp. The report is configured for weekly reporting, * with a week starting on Sunday. Override the {getReportingPeriodFor} to derive your own reporting period. * * Note Use the provided API to update the global report or the latest reports. When updating the latest * reports, the global report is also updated. * Designed as real-time reporting. A global report keeps track of overall accumulated values. * * Note no overflow has been added ... something to be mindful of * * @author victaphu */ contract Report is Ownable { // a report period represents a single report period start/end date // a sum/count for each report period is provided when updating // reports hold all the keyed reports for a given date range struct ReportPeriod { uint256 startRange; uint256 endRange; uint256 sum; uint256 count; bytes[] keys; mapping(bytes => ReportOverview) reports; } // a report overview represents the next level and represents one level // further of details. the focus of the report is presented as a key struct ReportOverview { uint256 sum; uint256 count; bytes[] categories; mapping(bytes => ReportItem) reportItems; } // reports can be further divided into report items which represent the // lowest level of reporting. struct ReportItem { uint256 sum; uint256 count; } mapping(address => bool) private _access; uint256 constant DAY_IN_SECONDS = 86400; // this represents a global overview of reports ReportPeriod private _overallReport; mapping(uint256 => ReportPeriod) private reports; /** * @dev return the latest report object using the latest timestamp to find the * report from reports mapping. * * @return period latest report using timestamp to derive the timeslot */ function getLatestReportObject() internal view returns (ReportPeriod storage period) { period = reports[getLatestReportingPeriod()]; } /** * @dev given a unix timestamp (in seconds) return the current weekday * note week 0 is sunday, week 6 is saturday * * @param timestamp unix timestamp in seconds (e.g. block.timestamp) * @return weekday the day of week between 0 and 6 (inclusive) */ function getWeekday(uint256 timestamp) public pure returns (uint8 weekday) { weekday = uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } /** * @dev this function will take a timestamp and normalise it to a value. * By default, reports are normalised to closest start of the week, so this * function will help generate weekly reports * * @param timestamp is the UNIX timestamp (in seconds) e.g. the block.timestamp */ function getReportPeriodFor(uint256 timestamp) public view virtual returns (uint256 reportPeriod) { uint256 currentDOW = getWeekday(timestamp); timestamp = (timestamp - currentDOW * DAY_IN_SECONDS); timestamp = timestamp - timestamp % DAY_IN_SECONDS; reportPeriod = timestamp; } /** * @dev get the latest reporting period given the block timestamp. Return a normalised value * based on timestamp. By default we return normalised by week * * @return reportPeriod the normalised report period for the latest timestamp */ function getLatestReportingPeriod() public view returns (uint256 reportPeriod) { return getReportPeriodFor(block.timestamp); } /** * @dev grant access to selected reporter. only the owner of the report object may assign reporters * * @param reporter the address of user/contract that may update this report */ function grantAccess(address reporter) public onlyOwner { _access[reporter] = true; } /** * @dev revoke access for a selected reporter. only the owner of the report may revoke reporters * * @param reporter the address of the user/contract that we are revoking access */ function revokeAccess(address reporter) public onlyOwner { _access[reporter] = false; } modifier accessible() { require( _access[msg.sender] || owner() == msg.sender, "Cannot access reporting function" ); _; } /** * @dev update a report given the period and the value. If the period is 0, then * the global report is updated. The sum is increased by the supplied value and the * count is incremented by 1 * * @param period is the normalised period that we want to update. * @param value is the value to be added */ function updateReport(uint256 period, uint256 value) private { ReportPeriod storage latest; if (period == 0) { latest = _overallReport; } else { latest = getLatestReportObject(); } latest.count += 1; latest.sum += value; } /** * @dev update a report given the period, key and the value. If the period is 0, then * the global report is updated. The sum is increased by the supplied value and the * count is incremented by 1. The key represents one additional dimension of data recorded * * @param period the normalised period that we want to update. * @param key the key dimension for this report * @param value the value to be added */ function updateReport( uint256 period, bytes memory key, uint256 value ) private { updateReport(period, value); ReportPeriod storage latest; if (period == 0) { latest = _overallReport; } else { latest = getLatestReportObject(); } ReportOverview storage overview = latest.reports[key]; if (overview.count == 0) { latest.keys.push(key); } overview.count += 1; overview.sum += value; } /** * @dev update a report given the period, key and category and the value. If the period is 0, then * the global report is updated. The sum is increased by the supplied value and the * count is incremented by 1. The key and category can be used to capture more fine-grain data * note data is rolled up to the parent * * @param period the normalised period that we want to update. * @param key the key dimension for this report * @param category the category dimension for this report * @param value the value to be added */ function updateReport( uint256 period, bytes memory key, bytes memory category, uint256 value ) private { updateReport(period, key, value); ReportPeriod storage latest; if (period == 0) { latest = _overallReport; } else { latest = getLatestReportObject(); } ReportOverview storage overview = latest.reports[key]; ReportItem storage item = overview.reportItems[category]; if (item.count == 0) { overview.categories.push(category); overview.reportItems[category] = item; } item.count += 1; item.sum += value; } /** * @dev update the latest report, and update the global report for the running total * * @param value the value to be added */ function updateLatestReport(uint256 value) external accessible { uint256 period = getLatestReportingPeriod(); updateReport(period, value); updateReport(0, value); // update global report } /** * @dev update the latest report, and update the global report for the running total * * @param key the key dimension for this report * @param value the value to be added */ function updateLatestReport(bytes memory key, uint256 value) external accessible { uint256 period = getLatestReportingPeriod(); updateReport(period, key, value); updateReport(0, key, value); // update global report } /** * @dev update the latest report, and update the global report for the running total * * @param key the key dimension for this report * @param category the category dimension for this report * @param value the value to be added */ function updateLatestReport( bytes memory key, bytes memory category, uint256 value ) external accessible { uint256 period = getLatestReportingPeriod(); updateReport(period, key, category, value); updateReport(0, key, category, value); // update global report } /** * @dev update the global report, this should be used if there is no intention to * have the report tool manage the running totals * * @param value the value to be added */ function updateGlobalReport(uint256 value) external accessible { updateReport(0, value); } /** * @dev update the global report, this should be used if there is no intention to * have the report tool manage the running totals * * @param key the key dimension for this report * @param value the value to be added */ function updateGlobalReport(bytes memory key, uint256 value) external accessible { updateReport(0, key, value); } /** * @dev update the global report, this should be used if there is no intention to * have the report tool manage the running totals * * @param key the key dimension for this report * @param category the category dimension for this report * @param value the value to be added */ function updateGlobalReport( bytes memory key, bytes memory category, uint256 value ) external accessible { updateReport(0, key, category, value); } /** * @dev get the report for a given period. supply 0 for the argument to get the global report * note returns data for the next level, use the keys to query further * * @param period the period for which we want to retrieve the data * @return sum current accumulated sum * @return count current total count for the overall report * @return sums all the sums that have been accumulated so far * @return counts all the counts that have been accumulated so far * @return keys a list of key dimensions. sums, counts and keys have same length and indexed accordingly */ function getReportForPeriod(uint256 period) public view returns ( uint256 sum, uint256 count, uint256[] memory sums, uint256[] memory counts, bytes[] memory keys ) { ReportPeriod storage report; if (period == 0) { report = _overallReport; } else { report = reports[period]; } sum = report.sum; count = report.count; keys = report.keys; uint256[] memory sumStorage = new uint256[](keys.length); uint256[] memory countStorage = new uint256[](keys.length); for (uint256 i = 0; i < keys.length; i++) { sumStorage[i] = report.reports[keys[i]].sum; countStorage[i] = report.reports[keys[i]].count; } sums = sumStorage; counts = countStorage; } /** * @dev get the report for a given period and key dimension. supply 0 for the argument to get the global report * note returns data for the next level, use the keys to query further * * @param period the period for which we want to retrieve the data * @param key the key dimension which we want to report on * @return sum current accumulated sum * @return count current total count for the overall report * @return sums all the sums that have been accumulated so far * @return counts all the counts that have been accumulated so far * @return keys a list of key dimensions. sums, counts and keys have same length and indexed accordingly */ function getReportForPeriod(uint256 period, bytes memory key) public view returns ( uint256 sum, uint256 count, uint256[] memory sums, uint256[] memory counts, bytes[] memory keys ) { ReportPeriod storage report; if (period == 0) { report = _overallReport; } else { report = reports[period]; } ReportOverview storage reportOverview = report.reports[key]; sum = reportOverview.sum; count = reportOverview.count; keys = reportOverview.categories; uint256[] memory sumStorage = new uint256[](keys.length); uint256[] memory countStorage = new uint256[](keys.length); for (uint256 i = 0; i < keys.length; i++) { sumStorage[i] = reportOverview.reportItems[keys[i]].sum; countStorage[i] = reportOverview.reportItems[keys[i]].count; } sums = sumStorage; counts = countStorage; } /** * @dev get the report for a given period and key dimension. supply 0 for the argument to get the global report * note returns data for the next level, use the keys to query further * * @param period the period for which we want to retrieve the data * @param key the key dimension which we want to report on * @param category the category dimension which we want to report on * @return sum current accumulated sum * @return count current total count for the overall report */ function getReportForPeriod( uint256 period, bytes memory key, bytes memory category ) public view returns (uint256 sum, uint256 count) { ReportPeriod storage report; if (period == 0) { report = _overallReport; } else { report = reports[period]; } ReportItem storage item = report.reports[key].reportItems[category]; sum = item.sum; count = item.count; } /** * @dev get the latest report at the highest level. includes key dimension breakdown * note returns data for the next level, use the keys to query further * * @return sum current accumulated sum * @return count current total count for the overall report * @return sums all the sums that have been accumulated so far * @return counts all the counts that have been accumulated so far * @return keys a list of key dimensions. sums, counts and keys have same length and indexed accordingly */ function getLatestReport() public view returns ( uint256 sum, uint256 count, uint256[] memory sums, uint256[] memory counts, bytes[] memory keys ) { return getReportForPeriod(getLatestReportingPeriod()); } /** * @dev get the latest report for a key dimension * note returns data for the next level, use the categories to query further * * @param key the key dimension which we want to report on * @return sum current accumulated sum * @return count current total count for the overall report * @return sums all the sums that have been accumulated so far * @return counts all the counts that have been accumulated so far * @return keys a list of key dimensions. sums, counts and keys have same length and indexed accordingly */ function getLatestReport(bytes memory key) public view returns ( uint256 sum, uint256 count, uint256[] memory sums, uint256[] memory counts, bytes[] memory keys ) { return getReportForPeriod(getLatestReportingPeriod(), key); } /** * @dev get the latest report for a key and category dimension * * @param key the key dimension which we want to report on * @return sum current accumulated sum * @return count current total count for the overall report */ function getLatestReport(bytes memory key, bytes memory category) public view returns (uint256 sum, uint256 count) { return getReportForPeriod(getLatestReportingPeriod(), key, category); } }
return the latest report object using the latest timestamp to find the report from reports mapping. return period latest report using timestamp to derive the timeslot/
function getLatestReportObject() internal view returns (ReportPeriod storage period) { period = reports[getLatestReportingPeriod()]; }
12,965,561
// SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "./base/ModuleManager.sol"; import "./base/OwnerManager.sol"; import "./base/FallbackManager.sol"; import "./base/GuardManager.sol"; import "./common/EtherPaymentFallback.sol"; import "./common/Singleton.sol"; import "./common/SignatureDecoder.sol"; import "./common/SecuredTokenTransfer.sol"; import "./common/StorageAccessible.sol"; import "./interfaces/ISignatureValidator.sol"; import "./external/GnosisSafeMath.sol"; /// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract GnosisSafe is EtherPaymentFallback, Singleton, ModuleManager, OwnerManager, SignatureDecoder, SecuredTokenTransfer, ISignatureValidatorConstants, FallbackManager, StorageAccessible, GuardManager { using GnosisSafeMath for uint256; string public constant VERSION = "1.3.0"; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)" // ); bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8; event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler); event ApproveHash(bytes32 indexed approvedHash, address indexed owner); event SignMsg(bytes32 indexed msgHash); event ExecutionFailure(bytes32 txHash, uint256 payment); event ExecutionSuccess(bytes32 txHash, uint256 payment); uint256 public nonce; bytes32 private _deprecatedDomainSeparator; // Mapping to keep track of all message hashes that have been approved by ALL REQUIRED owners mapping(bytes32 => uint256) public signedMessages; // Mapping to keep track of all hashes (message or transaction) that have been approved by ANY owners mapping(address => mapping(bytes32 => uint256)) public approvedHashes; // This constructor ensures that this contract can only be used as a master copy for Proxy contracts constructor() { // By setting the threshold it is not possible to call setup anymore, // so we create a Safe with 0 owners and threshold 1. // This is an unusable Safe, perfect for the singleton threshold = 1; } /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. /// @param to Contract address for optional delegate call. /// @param data Data payload for optional delegate call. /// @param fallbackHandler Handler for fallback calls to this contract /// @param paymentToken Token that should be used for the payment (0 is ETH) /// @param payment Value that should be paid /// @param paymentReceiver Address that should receive the payment (or 0 if tx.origin) function setup( address[] calldata _owners, uint256 _threshold, address to, bytes calldata data, address fallbackHandler, address paymentToken, uint256 payment, address payable paymentReceiver ) external { // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice setupOwners(_owners, _threshold); if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler); // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules setupModules(to, data); if (payment > 0) { // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself) // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment handlePayment(payment, 0, 1, paymentToken, paymentReceiver); } emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler); } /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction. /// Note: The fees are always transferred, even if the user transaction fails. /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @param safeTxGas Gas that should be used for the Safe transaction. /// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) /// @param gasPrice Gas price that should be used for the payment calculation. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) function execTransaction( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures ) public payable virtual returns (bool success) { bytes32 txHash; // Use scope here to limit variable lifetime and prevent `stack too deep` errors { bytes memory txHashData = encodeTransactionData( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info nonce ); // Increase nonce and execute transaction. nonce++; txHash = keccak256(txHashData); checkSignatures(txHash, txHashData, signatures); } address guard = getGuard(); { if (guard != address(0)) { Guard(guard).checkTransaction( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info signatures, msg.sender ); } } // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500) // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150 require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010"); // Use scope here to limit variable lifetime and prevent `stack too deep` errors { uint256 gasUsed = gasleft(); // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas) // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas); gasUsed = gasUsed.sub(gasleft()); // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert require(success || safeTxGas != 0 || gasPrice != 0, "GS013"); // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls uint256 payment = 0; if (gasPrice > 0) { payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver); } if (success) emit ExecutionSuccess(txHash, payment); else emit ExecutionFailure(txHash, payment); } { if (guard != address(0)) { Guard(guard).checkAfterExecution(txHash, success); } } } function handlePayment( uint256 gasUsed, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver ) private returns (uint256 payment) { // solhint-disable-next-line avoid-tx-origin address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver; if (gasToken == address(0)) { // For ETH we will only adjust the gas price to not be higher than the actual used gas price payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice); require(receiver.send(payment), "GS011"); } else { payment = gasUsed.add(baseGas).mul(gasPrice); require(transferToken(gasToken, receiver, payment), "GS012"); } } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param dataHash Hash of the data (could be either a message hash or transaction hash) * @param data That should be signed (this is passed to an external validator contract) * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash. */ function checkSignatures( bytes32 dataHash, bytes memory data, bytes memory signatures ) public view { // Load threshold to avoid multiple storage loads uint256 _threshold = threshold; // Check that a threshold is set require(_threshold > 0, "GS001"); checkNSignatures(dataHash, data, signatures, _threshold); } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param dataHash Hash of the data (could be either a message hash or transaction hash) * @param data That should be signed (this is passed to an external validator contract) * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash. * @param requiredSignatures Amount of required valid signatures. */ function checkNSignatures( bytes32 dataHash, bytes memory data, bytes memory signatures, uint256 requiredSignatures ) public view { // Check that the provided signature data is not too short require(signatures.length >= requiredSignatures.mul(65), "GS020"); // There cannot be an owner with address 0. address lastOwner = address(0); address currentOwner; uint8 v; bytes32 r; bytes32 s; uint256 i; for (i = 0; i < requiredSignatures; i++) { (v, r, s) = signatureSplit(signatures, i); if (v == 0) { // If v is 0 then it is a contract signature // When handling contract signatures the address of the contract is encoded into r currentOwner = address(uint160(uint256(r))); // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes // This check is not completely accurate, since it is possible that more signatures than the threshold are send. // Here we only check that the pointer is not pointing inside the part that is being processed require(uint256(s) >= requiredSignatures.mul(65), "GS021"); // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes) require(uint256(s).add(32) <= signatures.length, "GS022"); // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length uint256 contractSignatureLen; // solhint-disable-next-line no-inline-assembly assembly { contractSignatureLen := mload(add(add(signatures, s), 0x20)) } require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023"); // Check signature bytes memory contractSignature; // solhint-disable-next-line no-inline-assembly assembly { // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s contractSignature := add(add(signatures, s), 0x20) } require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024"); } else if (v == 1) { // If v is 1 then it is an approved hash // When handling approved hashes the address of the approver is encoded into r currentOwner = address(uint160(uint256(r))); // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025"); } else if (v > 30) { // If v > 30 then default va (27,28) has been adjusted for eth_sign flow // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover currentOwner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash)), v - 4, r, s); } else { // Default is the ecrecover flow with the provided data hash // Use ecrecover with the messageHash for EOA signatures currentOwner = ecrecover(dataHash, v, r, s); } require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026"); lastOwner = currentOwner; } } /// @dev Allows to estimate a Safe transaction. /// This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data. /// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction` /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs). /// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version. function requiredTxGas( address to, uint256 value, bytes calldata data, Enum.Operation operation ) external returns (uint256) { uint256 startGas = gasleft(); // We don't provide an error message here, as we use it to return the estimate require(execute(to, value, data, operation, gasleft())); uint256 requiredGas = startGas - gasleft(); // Convert response to string and return via error message revert(string(abi.encodePacked(requiredGas))); } /** * @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature. * @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract. */ function approveHash(bytes32 hashToApprove) external { require(owners[msg.sender] != address(0), "GS030"); approvedHashes[msg.sender][hashToApprove] = 1; emit ApproveHash(hashToApprove, msg.sender); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solhint-disable-next-line no-inline-assembly assembly { id := chainid() } return id; } function domainSeparator() public view returns (bytes32) { return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this)); } /// @dev Returns the bytes that are hashed to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Gas that should be used for the safe transaction. /// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param _nonce Transaction nonce. /// @return Transaction hash bytes. function encodeTransactionData( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes memory) { bytes32 safeTxHash = keccak256( abi.encode( SAFE_TX_TYPEHASH, to, value, keccak256(data), operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce ) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash); } /// @dev Returns hash to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Fas that should be used for the safe transaction. /// @param baseGas Gas costs for data used to trigger the safe transaction. /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param _nonce Transaction nonce. /// @return Transaction hash. function getTransactionHash( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes32) { return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce)); } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/Enum.sol"; /// @title Executor - A contract that can execute transactions /// @author Richard Meissner - <[email protected]> contract Executor { function execute( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txGas ) internal returns (bool success) { if (operation == Enum.Operation.DelegateCall) { // solhint-disable-next-line no-inline-assembly assembly { success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0) } } else { // solhint-disable-next-line no-inline-assembly assembly { success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0) } } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/SelfAuthorized.sol"; /// @title Fallback Manager - A contract that manages fallback calls made to this contract /// @author Richard Meissner - <[email protected]> contract FallbackManager is SelfAuthorized { event ChangedFallbackHandler(address handler); // keccak256("fallback_manager.handler.address") bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5; function internalSetFallbackHandler(address handler) internal { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, handler) } } /// @dev Allows to add a contract to handle fallback calls. /// Only fallback calls without value and with data will be forwarded. /// This can only be done via a Safe transaction. /// @param handler contract to handle fallback calls. function setFallbackHandler(address handler) public authorized { internalSetFallbackHandler(handler); emit ChangedFallbackHandler(handler); } // solhint-disable-next-line payable-fallback,no-complex-fallback fallback() external { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { let handler := sload(slot) if iszero(handler) { return(0, 0) } calldatacopy(0, 0, calldatasize()) // The msg.sender address is shifted to the left by 12 bytes to remove the padding // Then the address without padding is stored right after the calldata mstore(calldatasize(), shl(96, caller())) // Add 20 bytes for the address appended add the end let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0) returndatacopy(0, 0, returndatasize()) if iszero(success) { revert(0, returndatasize()) } return(0, returndatasize()) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/Enum.sol"; import "../common/SelfAuthorized.sol"; import "../interfaces/IERC165.sol"; interface Guard is IERC165 { function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external; function checkAfterExecution(bytes32 txHash, bool success) external; } abstract contract BaseGuard is Guard { function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) { return interfaceId == type(Guard).interfaceId || // 0xe6d7a83a interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7 } } /// @title Fallback Manager - A contract that manages fallback calls made to this contract /// @author Richard Meissner - <[email protected]> contract GuardManager is SelfAuthorized { event ChangedGuard(address guard); // keccak256("guard_manager.guard.address") bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8; /// @dev Set a guard that checks transactions before execution /// @param guard The address of the guard to be used or the 0 address to disable the guard function setGuard(address guard) external authorized { if (guard != address(0)) { require(Guard(guard).supportsInterface(type(Guard).interfaceId), "GS300"); } bytes32 slot = GUARD_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, guard) } emit ChangedGuard(guard); } function getGuard() internal view returns (address guard) { bytes32 slot = GUARD_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { guard := sload(slot) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/Enum.sol"; import "../common/SelfAuthorized.sol"; import "./Executor.sol"; /// @title Module Manager - A contract that manages modules that can execute transactions via this contract /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract ModuleManager is SelfAuthorized, Executor { event EnabledModule(address module); event DisabledModule(address module); event ExecutionFromModuleSuccess(address indexed module); event ExecutionFromModuleFailure(address indexed module); address internal constant SENTINEL_MODULES = address(0x1); mapping(address => address) internal modules; function setupModules(address to, bytes memory data) internal { require(modules[SENTINEL_MODULES] == address(0), "GS100"); modules[SENTINEL_MODULES] = SENTINEL_MODULES; if (to != address(0)) // Setup has to complete successfully or transaction fails. require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000"); } /// @dev Allows to add a module to the whitelist. /// This can only be done via a Safe transaction. /// @notice Enables the module `module` for the Safe. /// @param module Module to be whitelisted. function enableModule(address module) public authorized { // Module address cannot be null or sentinel. require(module != address(0) && module != SENTINEL_MODULES, "GS101"); // Module cannot be added twice. require(modules[module] == address(0), "GS102"); modules[module] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = module; emit EnabledModule(module); } /// @dev Allows to remove a module from the whitelist. /// This can only be done via a Safe transaction. /// @notice Disables the module `module` for the Safe. /// @param prevModule Module that pointed to the module to be removed in the linked list /// @param module Module to be removed. function disableModule(address prevModule, address module) public authorized { // Validate module address and check that it corresponds to module index. require(module != address(0) && module != SENTINEL_MODULES, "GS101"); require(modules[prevModule] == module, "GS103"); modules[prevModule] = modules[module]; modules[module] = address(0); emit DisabledModule(module); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule( address to, uint256 value, bytes memory data, Enum.Operation operation ) public virtual returns (bool success) { // Only whitelisted modules are allowed. require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104"); // Execute transaction without further confirmations. success = execute(to, value, data, operation, gasleft()); if (success) emit ExecutionFromModuleSuccess(msg.sender); else emit ExecutionFromModuleFailure(msg.sender); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModuleReturnData( address to, uint256 value, bytes memory data, Enum.Operation operation ) public returns (bool success, bytes memory returnData) { success = execTransactionFromModule(to, value, data, operation); // solhint-disable-next-line no-inline-assembly assembly { // Load free memory location let ptr := mload(0x40) // We allocate memory for the return data by setting the free memory location to // current free memory location + data size + 32 bytes for data size value mstore(0x40, add(ptr, add(returndatasize(), 0x20))) // Store the size mstore(ptr, returndatasize()) // Store the data returndatacopy(add(ptr, 0x20), 0, returndatasize()) // Point the return data to the correct memory location returnData := ptr } } /// @dev Returns if an module is enabled /// @return True if the module is enabled function isModuleEnabled(address module) public view returns (bool) { return SENTINEL_MODULES != module && modules[module] != address(0); } /// @dev Returns array of modules. /// @param start Start of the page. /// @param pageSize Maximum number of modules that should be returned. /// @return array Array of modules. /// @return next Start of the next page. function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) { // Init array with max page size array = new address[](pageSize); // Populate return array uint256 moduleCount = 0; address currentModule = modules[start]; while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) { array[moduleCount] = currentModule; currentModule = modules[currentModule]; moduleCount++; } next = currentModule; // Set correct size of returned array // solhint-disable-next-line no-inline-assembly assembly { mstore(array, moduleCount) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/SelfAuthorized.sol"; /// @title OwnerManager - Manages a set of owners and a threshold to perform actions. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract OwnerManager is SelfAuthorized { event AddedOwner(address owner); event RemovedOwner(address owner); event ChangedThreshold(uint256 threshold); address internal constant SENTINEL_OWNERS = address(0x1); mapping(address => address) internal owners; uint256 internal ownerCount; uint256 internal threshold; /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. function setupOwners(address[] memory _owners, uint256 _threshold) internal { // Threshold can only be 0 at initialization. // Check ensures that setup function can only be called once. require(threshold == 0, "GS200"); // Validate that threshold is smaller than number of added owners. require(_threshold <= _owners.length, "GS201"); // There has to be at least one Safe owner. require(_threshold >= 1, "GS202"); // Initializing Safe owners. address currentOwner = SENTINEL_OWNERS; for (uint256 i = 0; i < _owners.length; i++) { // Owner address cannot be null. address owner = _owners[i]; require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203"); // No duplicate owners allowed. require(owners[owner] == address(0), "GS204"); owners[currentOwner] = owner; currentOwner = owner; } owners[currentOwner] = SENTINEL_OWNERS; ownerCount = _owners.length; threshold = _threshold; } /// @dev Allows to add a new owner to the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`. /// @param owner New owner address. /// @param _threshold New threshold. function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized { // Owner address cannot be null, the sentinel or the Safe itself. require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203"); // No duplicate owners allowed. require(owners[owner] == address(0), "GS204"); owners[owner] = owners[SENTINEL_OWNERS]; owners[SENTINEL_OWNERS] = owner; ownerCount++; emit AddedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to remove an owner from the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`. /// @param prevOwner Owner that pointed to the owner to be removed in the linked list /// @param owner Owner address to be removed. /// @param _threshold New threshold. function removeOwner( address prevOwner, address owner, uint256 _threshold ) public authorized { // Only allow to remove an owner, if threshold can still be reached. require(ownerCount - 1 >= _threshold, "GS201"); // Validate owner address and check that it corresponds to owner index. require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203"); require(owners[prevOwner] == owner, "GS205"); owners[prevOwner] = owners[owner]; owners[owner] = address(0); ownerCount--; emit RemovedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to swap/replace an owner from the Safe with another address. /// This can only be done via a Safe transaction. /// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`. /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list /// @param oldOwner Owner address to be replaced. /// @param newOwner New owner address. function swapOwner( address prevOwner, address oldOwner, address newOwner ) public authorized { // Owner address cannot be null, the sentinel or the Safe itself. require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203"); // No duplicate owners allowed. require(owners[newOwner] == address(0), "GS204"); // Validate oldOwner address and check that it corresponds to owner index. require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203"); require(owners[prevOwner] == oldOwner, "GS205"); owners[newOwner] = owners[oldOwner]; owners[prevOwner] = newOwner; owners[oldOwner] = address(0); emit RemovedOwner(oldOwner); emit AddedOwner(newOwner); } /// @dev Allows to update the number of required confirmations by Safe owners. /// This can only be done via a Safe transaction. /// @notice Changes the threshold of the Safe to `_threshold`. /// @param _threshold New threshold. function changeThreshold(uint256 _threshold) public authorized { // Validate that threshold is smaller than number of owners. require(_threshold <= ownerCount, "GS201"); // There has to be at least one Safe owner. require(_threshold >= 1, "GS202"); threshold = _threshold; emit ChangedThreshold(threshold); } function getThreshold() public view returns (uint256) { return threshold; } function isOwner(address owner) public view returns (bool) { return owner != SENTINEL_OWNERS && owners[owner] != address(0); } /// @dev Returns array of owners. /// @return Array of Safe owners. function getOwners() public view returns (address[] memory) { address[] memory array = new address[](ownerCount); // populate return array uint256 index = 0; address currentOwner = owners[SENTINEL_OWNERS]; while (currentOwner != SENTINEL_OWNERS) { array[index] = currentOwner; currentOwner = owners[currentOwner]; index++; } return array; } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Enum - Collection of enums /// @author Richard Meissner - <[email protected]> contract Enum { enum Operation {Call, DelegateCall} } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments /// @author Richard Meissner - <[email protected]> contract EtherPaymentFallback { event SafeReceived(address indexed sender, uint256 value); /// @dev Fallback function accepts Ether transactions. receive() external payable { emit SafeReceived(msg.sender, msg.value); } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title SecuredTokenTransfer - Secure token transfer /// @author Richard Meissner - <[email protected]> contract SecuredTokenTransfer { /// @dev Transfers a token and returns if it was a success /// @param token Token that should be transferred /// @param receiver Receiver to whom the token should be transferred /// @param amount The amount of tokens that should be transferred function transferToken( address token, address receiver, uint256 amount ) internal returns (bool transferred) { // 0xa9059cbb - keccack("transfer(address,uint256)") bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount); // solhint-disable-next-line no-inline-assembly assembly { // We write the return value to scratch space. // See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20) switch returndatasize() case 0 { transferred := success } case 0x20 { transferred := iszero(or(iszero(success), iszero(mload(0)))) } default { transferred := 0 } } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title SelfAuthorized - authorizes current contract to perform actions /// @author Richard Meissner - <[email protected]> contract SelfAuthorized { function requireSelfCall() private view { require(msg.sender == address(this), "GS031"); } modifier authorized() { // This is a function call as it minimized the bytecode size requireSelfCall(); _; } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title SignatureDecoder - Decodes signatures that a encoded as bytes /// @author Richard Meissner - <[email protected]> contract SignatureDecoder { /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`. /// @notice Make sure to perform a bounds check for @param pos, to avoid out of bounds access on @param signatures /// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access /// @param signatures concatenated rsv signatures function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns ( uint8 v, bytes32 r, bytes32 s ) { // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. // solhint-disable-next-line no-inline-assembly assembly { let signaturePos := mul(0x41, pos) r := mload(add(signatures, add(signaturePos, 0x20))) s := mload(add(signatures, add(signaturePos, 0x40))) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Singleton - Base for singleton contracts (should always be first super contract) /// This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`) /// @author Richard Meissner - <[email protected]> contract Singleton { // singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract. // It should also always be ensured that the address is stored alone (uses a full word) address private singleton; } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title StorageAccessible - generic base contract that allows callers to access all internal storage. /// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol contract StorageAccessible { /** * @dev Reads `length` bytes of storage in the currents contract * @param offset - the offset in the current contract's storage in words to start reading from * @param length - the number of words (32 bytes) of data to read * @return the bytes that were read. */ function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) { bytes memory result = new bytes(length * 32); for (uint256 index = 0; index < length; index++) { // solhint-disable-next-line no-inline-assembly assembly { let word := sload(add(offset, index)) mstore(add(add(result, 0x20), mul(index, 0x20)), word) } } return result; } /** * @dev Performs a delegatecall on a targetContract in the context of self. * Internally reverts execution to avoid side effects (making it static). * * This method reverts with data equal to `abi.encode(bool(success), bytes(response))`. * Specifically, the `returndata` after a call to this method will be: * `success:bool || response.length:uint256 || response:bytes`. * * @param targetContract Address of the contract containing the code to execute. * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments). */ function simulateAndRevert(address targetContract, bytes memory calldataPayload) external { // solhint-disable-next-line no-inline-assembly assembly { let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0) mstore(0x00, success) mstore(0x20, returndatasize()) returndatacopy(0x40, 0, returndatasize()) revert(0, add(returndatasize(), 0x40)) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /** * @title GnosisSafeMath * @dev Math operations with safety checks that revert on error * Renamed from SafeMath to GnosisSafeMath to avoid conflicts * TODO: remove once open zeppelin update to solc 0.5.0 */ library GnosisSafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @notice More details at https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol 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: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; contract ISignatureValidatorConstants { // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b; } abstract contract ISignatureValidator is ISignatureValidatorConstants { /** * @dev Should return whether the signature provided is valid for the provided data * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * * MUST return the bytes4 magic value 0x20c13b0b when function passes. * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4); }
Reads `length` bytes of storage in the currents contract offset - the offset in the current contract's storage in words to start reading from length - the number of words (32 bytes) of data to read return the bytes that were read./ solhint-disable-next-line no-inline-assembly
function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) { bytes memory result = new bytes(length * 32); for (uint256 index = 0; index < length; index++) { assembly { let word := sload(add(offset, index)) mstore(add(add(result, 0x20), mul(index, 0x20)), word) } } return result; }
431,340
/** *Submitted for verification at Etherscan.io on 2021-11-21 */ // File: contracts/common/Initializable.sol pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts/common/EIP712Base.sol pragma solidity ^0.8.0; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts/common/ContextMixin.sol pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File: @openzeppelin/contracts/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 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; } } } // File: contracts/common/NativeMetaTransaction.sol pragma solidity ^0.8.0; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // 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/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/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); } } // 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/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol 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/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/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: contracts/ERC721Tradable.sol pragma solidity ^0.8.0; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } } // File: contracts/BitKoi.sol pragma solidity ^0.8.0; /** * @title BitKoi * BitKoi - a blockchain game at scale */ /// @title mix up two fish and find out which traits they should have, which includes the logic to enforce a "promo gene" in future gen0 releases abstract contract BitKoiTraitInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isBitKoiTraits() virtual public pure returns (bool); ///mix up the "genes" of the fish to see which genes our new fish will have function smooshFish(uint256 genes1, uint256 genes2, uint8 promoGene, uint256 targetBlock) virtual public returns (uint256); } /// @title A facet of BitKoiCore that manages special access privileges. /// Based on work from Cryptokitties and Axiom Zen (https://www.axiomzen.co) contract BitKoiAccessControl { // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. bool public paused = false; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCFO() { require(msg.sender == cfoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address payable _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @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 allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() virtual public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Base contract for KoiPond abstract contract BitKoiBase is BitKoiAccessControl, ERC721Tradable { /*** EVENTS ***/ /// @dev The Spawn event is fired whenever a new fish comes into existence. This obviously /// includes any time a fish is created through the spawnFish method, but it is also called /// when a new gen0 fish is created. event Spawn(uint256 fishId, uint64 timestamp); /*** DATA TYPES ***/ struct BitKoi { //a promotional gene that, when active, will enable this bitKoi to hatch with a specific trait //this is ONLY assigned for gen0 promo events uint8 promoGene; // The timestamp from the block when this fish came into existence. uint64 spawnTime; // The timestamp from the block when this fish was hatched. This also masks the traits for 'unhatched' BitKoi uint64 hatchTime; // The minimum timestamp after which this fish can engage in spawning // activities again. uint64 cooldownEndBlock; // The ID of the parents of this fish, set to 0 for gen0 fish. // With uint32 there's a limit of 4 billion fish uint32 parent1Id; uint32 parent2Id; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this fish. This starts at zero // for gen0 fish, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action. uint16 cooldownIndex; // The "generation number" of this fish. Fish minted by the KP contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other fish is the larger of the two generation // numbers of their parents, plus one. uint16 generation; // The fish's genetic code - this will never change for any fish. uint256 genes; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "cooldown" Designed such that the cooldown roughly /// doubles each time a fish is bred, encouraging owners not to just keep breeding the same fish over /// and over again. Caps out at one week (a fish can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the KoiFish struct for all KoiFish in existence. The ID /// of each fish is actually an index into this array. Fish 0 has an invalid genetic /// code and can't be used to produce offspring. BitKoi[] bitKoi; // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } abstract contract BitKoiOwnership is BitKoiBase { /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns( address _claimant, uint256 _tokenId ) internal view returns (bool) { return (ownerOf(_tokenId) == _claimant); } /// @notice Returns a list of all BitKoi IDs assigned to an address. /// @param _owner The owner whose BitKoi we are interested in. function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; uint256 tokenIndex; for (tokenIndex = 0; tokenIndex <= tokenCount - 1; tokenIndex++) { uint256 tokenId = tokenOfOwnerByIndex(_owner, tokenIndex); result[resultIndex] = tokenId; resultIndex++; } return result; } } } abstract contract BitKoiBreeding is BitKoiOwnership { event Hatch(address owner, uint256 fishId, uint64 hatchTime); uint256 public breedFee = 0 wei; uint256 public hatchFee = 0 wei; /// @dev The address of the sibling contract that is used to implement the genetic combination algorithm. BitKoiTraitInterface public bitKoiTraits; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setBitKoiTraitAddress(address _address) external onlyCEO { BitKoiTraitInterface candidateContract = BitKoiTraitInterface(_address); // NOTE: verify that a contract is what we expect it to be and not some random other one require(candidateContract.isBitKoiTraits()); // Set the new contract address bitKoiTraits = candidateContract; } /// @dev Checks that a given fish is able to breed. Requires that the /// current cooldown is finished function _isReadyToBreed(BitKoi storage _fish) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the fish has a pending birth; there can be some period of time between the end // of the pregnacy timer and the spawn event. return _fish.cooldownEndBlock <= uint64(block.number); } /// @dev Set the cooldownEndTime for the given fish based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _koiFish A reference to the KoiFish in storage which needs its timer started. function _triggerCooldown(BitKoi storage _koiFish) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _koiFish.cooldownEndBlock = uint64((cooldowns[_koiFish.cooldownIndex]/secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_koiFish.cooldownIndex < 13) { _koiFish.cooldownIndex += 1; } } // @dev Updates the minimum payment required for calling breedWith(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setBreedFee(uint256 val) external onlyCOO { breedFee = val; } // @dev Updates the minimum payment required for calling hatchFish(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setHatchFee(uint256 val) external onlyCOO { hatchFee = val; } /// @notice Checks that a given fish is able to breed (i.e. it is not /// in the middle of a cooldown). /// @param _koiId reference the id of the fish, any user can inquire about it function isReadyToBreed(uint256 _koiId) public view returns (bool) { require(_koiId > 0); BitKoi storage fish = bitKoi[_koiId]; return _isReadyToBreed(fish); } /// @dev Internal check to see if a the parents are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _parent1 A reference to the Fish struct of the potential first parent /// @param _parent1Id The first parent's ID. /// @param _parent2 A reference to the Fish struct of the potential second parent /// @param _parent2Id The second parent's ID. function _isValidMatingPair( BitKoi storage _parent1, uint256 _parent1Id, BitKoi storage _parent2, uint256 _parent2Id ) private view returns(bool) { // A Fish can't breed with itself! if (_parent1Id == _parent2Id) { return false; } //the fish have to have genes if (_parent1.genes == 0 || _parent2.genes == 0) { return false; } //they both have to be hatched if (_parent1.hatchTime == 0 || _parent2.hatchTime == 0) { return false; } // Fish can't breed with their parents. if (_parent1.parent1Id == _parent2Id || _parent1.parent2Id == _parent2Id) { return false; } if (_parent2.parent1Id == _parent1Id || _parent2.parent2Id == _parent1Id) { return false; } // OK the tx if either fish is gen zero (no parent found). if (_parent2.parent1Id == 0 || _parent1.parent1Id == 0) { return true; } // Fish can't breed with full or half siblings. if (_parent2.parent1Id == _parent1.parent1Id || _parent2.parent1Id == _parent1.parent2Id) { return false; } if (_parent2.parent2Id == _parent1.parent1Id || _parent2.parent2Id == _parent1.parent2Id) { return false; } // gtg return true; } /// @notice Checks to see if two BitKoi can breed together, including checks for /// ownership. Doesn't check that both BitKoi are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// @param _parent1Id The ID of the proposed first parent. /// @param _parent2Id The ID of the proposed second parent. function canBreedWith(uint256 _parent1Id, uint256 _parent2Id) external view returns(bool) { require(_parent1Id > 0); require(_parent2Id > 0); BitKoi storage parent1 = bitKoi[_parent1Id]; BitKoi storage parent2 = bitKoi[_parent2Id]; return _isValidMatingPair(parent1, _parent1Id, parent2, _parent2Id); } /// @dev Internal utility function to initiate breeding (aka 'grinding nemo'). Assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _parent1Id, uint256 _parent2Id) internal returns(uint256) { // Grab a reference to the two Bitkoi we want to breed from storage. BitKoi storage parent1 = bitKoi[_parent1Id]; BitKoi storage parent2 = bitKoi[_parent2Id]; // Determine the higher generation number of the two parents and use this for the new BitKoi uint16 parentGen = parent1.generation; if (parent2.generation > parent1.generation) { parentGen = parent2.generation; } // Transfer the breed fee to the CFO contract payable(address(cfoAddress)).transfer(msg.value); // Get new genes for the bitkoi but don't send in a promo gene - that's only for gen0 eggs uint256 newGenes = bitKoiTraits.smooshFish(parent1.genes, parent2.genes, 0, parent1.cooldownEndBlock); // Use the genes we just got to create a brand new BitKoi! uint256 newFishId = _createBitKoi(_parent1Id, _parent2Id, parentGen + 1, newGenes, false, 0, msg.sender); // Trigger the cooldown for both parents. _triggerCooldown(parent1); _triggerCooldown(parent2); return newFishId; } function breedWith(uint256 _parent1Id, uint256 _parent2Id) external payable whenNotPaused { // Checks for payment. require(msg.value >= breedFee); ///check to see if the caller owns both bitkoi require(_owns(msg.sender, _parent1Id)); require(_owns(msg.sender, _parent2Id)); // Grab a reference to the bitkoi parent BitKoi storage parent1 = bitKoi[_parent1Id]; // Make sure enough time has passed since the last time this fish was bred require(_isReadyToBreed(parent1)); // Grab a reference to the second parent BitKoi storage parent2 = bitKoi[_parent2Id]; // Make sure enough time has passed since the last time this bitkoi was bred require(_isReadyToBreed(parent2)); // Test that these bitkoi are a valid mating pair. require(_isValidMatingPair( parent1, _parent1Id, parent2, _parent2Id )); // All checks passed, smoosh 'em! _breedWith(_parent1Id, _parent2Id); } /// @dev An internal method that creates a new fish and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _parent1Id The fish ID of the first parent (zero for gen0) /// @param _parent2Id The fish ID of the second parent (zero for gen0) /// @param _generation The generation number of this fish, must be computed by caller. /// @param _genes The fish's genetic code. /// @param _promoGene The promo gene for special mint events /// @param _to The inital owner of this fish, must be non-zero (except for fish ID 0) function _createBitKoi( uint256 _parent1Id, uint256 _parent2Id, uint256 _generation, uint256 _genes, bool _hatchMe, uint8 _promoGene, address _to ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createKoiFish() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_parent1Id == uint256(uint32(_parent1Id))); require(_parent2Id == uint256(uint32(_parent2Id))); require(_generation == uint256(uint16(_generation))); // New fish starts with the same cooldown as parent gen/2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } uint64 hatchTime; if (_hatchMe){ hatchTime = uint64(block.timestamp); } BitKoi memory _bitKoi = BitKoi({ genes: _genes, promoGene: uint8(_promoGene), spawnTime: uint64(block.timestamp), hatchTime: hatchTime, cooldownEndBlock: 0, parent1Id: uint32(_parent1Id), parent2Id: uint32(_parent2Id), cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newBitKoiId = bitKoi.length; bitKoi.push(_bitKoi); // It's probably never going to happen, 4 billion fish is A LOT, but // let's just be 100% sure we never let this happen. require(newBitKoiId == uint256(uint32(newBitKoiId))); // This will assign ownership, and also emit the Transfer event as required per ERC721 _safeMint(_to, newBitKoiId); // emit the spawn event emit Spawn( newBitKoiId, uint64(_bitKoi.spawnTime) ); return newBitKoiId; } function hatchBitKoi(uint256 _fishId) external payable whenNotPaused { // Check for payment. require(msg.value >= hatchFee); // Ensure the caller owns the egg they want to hatch require(_owns(msg.sender, _fishId)); BitKoi storage fishToHatch = bitKoi[_fishId]; // Check to make sure the BitKoi isn't hatched yet require(fishToHatch.hatchTime == 0); fishToHatch.hatchTime = uint64(block.timestamp); // Transfer the hatch fee to the CFO contract payable(address(cfoAddress)).transfer(msg.value); // Announce that a new bitkoi has been hatched and trigger the render of the new asset emit Hatch(msg.sender, _fishId, fishToHatch.hatchTime); } } /// @title all functions related to creating fish (and their eggs) abstract contract BitKoiMinting is BitKoiBreeding { // Limits the number of fish the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 5200; uint256 public constant GEN0_EGG_CREATION_LIMIT = 44800; // Counts the number of bitkoi the contract owner has minted. uint256 public promoCreatedCount; // Counts the number of bitkoi minted in public/private sales and releases uint256 public gen0CreatedCount; // Minting is not live to start bool public allowMinting = false; // Mint passes are not required to start bool public requireMintPass = false; // Require an address to have a token to mint uint public requiredHoldings = 0; // Set the price for minting a new BitKoi gen0 egg uint256 public gen0PromoPrice = 0 wei; // Set the cap of gen0 eggs - will increase progressively as mint events happen for releases uint256 public currentGen0Cap = 100; // The time the most current mint was started uint public mintEventStarted = block.timestamp; // The limit per wallet for this period uint public currentMintLimit = 0; mapping (address => uint) tokensAllowed; mapping (address => uint) lastMintParticipated; mapping (address => uint) tokensMintedThisPeriod; // allow direct sales of gen0 eggs function setAllowMinting(bool _val) external onlyCLevel { allowMinting = _val; } // update whether or not holders are required to mint function resetMintEventClock() external onlyCLevel { mintEventStarted = block.timestamp; } // update whether or not holders are required to mint function setHolderRequirement(uint _val) external onlyCLevel { requiredHoldings = _val; } // set current cap for sale - this can be raised later so new sales can be started w/ limits function setCurrentGen0Cap(uint256 _val) external onlyCOO { require (gen0CreatedCount + _val <= GEN0_EGG_CREATION_LIMIT); currentGen0Cap = _val; } // @dev Updates the minimum payment required for calling mintGen0Egg(). Can only /// be called by the CEO address. function setGen0PromoPrice(uint256 _val) external onlyCOO { gen0PromoPrice = _val; } // @dev Updates the max number of items an address can mint in the given period. Can only /// be called by the CEO address. function setRequireMintPasses(bool _val) external onlyCOO { requireMintPass = _val; } // Here we can limit the number of BitKoi eggs a wallet can mint in the current period function setMintLimitPerPeriod(uint _val) external onlyCOO { currentMintLimit = _val; } //set a gene that is promotional and garaunteed to be in a newly hatched egg during the promo period uint8 public currentPromoGene = 0; //enable the promo gene for future releases bool public currentPromoActive = false; function setPromoGene(uint8 _val) external onlyCLevel { currentPromoGene = _val; } function setPromoStatus(bool _status) external onlyCLevel { currentPromoActive = _status; } function whitelistMintPasses(address[] calldata _addressList, uint numberOfPasses) external onlyCOO { for (uint i = 0; i < _addressList.length; i++) { tokensAllowed[_addressList[i]] += numberOfPasses; } } function getAvailablePasses(address _address) public view returns(uint) { return tokensAllowed[_address]; } function getMintedThisPeriod(address _address) public view returns(uint){ return tokensMintedThisPeriod[_address]; } function getLastMintParticipated(address _address) public view returns(uint){ return lastMintParticipated[_address]; } function mintGen0Egg(uint numberToMint) external payable whenNotPaused { //make sure minting is active require (allowMinting); //ensure they're trying to mint at least 1 egg just so people don't waste gas require(numberToMint > 0); //make sure enough eth has been sent require (msg.value >= gen0PromoPrice * numberToMint); //make sure the new tokens will not exceed the overall cap require (gen0CreatedCount + numberToMint <= currentGen0Cap); //make sure we aren't over the limit for all gen0Eggs require (gen0CreatedCount + numberToMint <= GEN0_EGG_CREATION_LIMIT); // require the purchasesr to have at least the number of required tokens to mint require (balanceOf(msg.sender) >= requiredHoldings); //if a mint pass is required, ensure that they are whitelisted if (requireMintPass){ require(numberToMint <= tokensAllowed[msg.sender]); } //if the last mint they participated in was before this one, then clear the tokens minted for the current period if (lastMintParticipated[msg.sender] < mintEventStarted){ tokensMintedThisPeriod[msg.sender] = 0; } // check to see if they've minted in the current mint period if (currentMintLimit > 0){ require(numberToMint + tokensMintedThisPeriod[msg.sender] <= currentMintLimit); } uint8 promoGene; if (currentPromoActive){ promoGene = currentPromoGene; } //transfer the sale price less the pond cut to the CFO contract payable(address(cfoAddress)).transfer(msg.value); for (uint i = 0; i < numberToMint; i++) { // Get new genes for the bitkoi but don't send in a promo gene uint256 newGenes = bitKoiTraits.smooshFish(0, 0, promoGene, block.number); _createBitKoi(0, 0, 0, newGenes, false, promoGene, msg.sender); gen0CreatedCount++; if (requireMintPass){ tokensAllowed[msg.sender]--; } tokensMintedThisPeriod[msg.sender]++; } // update the most recently participated in mint event lastMintParticipated[msg.sender] = mintEventStarted; } /// @dev we can create promo fish, up to a limit. Only callable by COO /// @param _genes the encoded genes of the fish to be created, any value is accepted /// @param _sendTo the future owner of the created fish. Default to contract COO function createPromoFish(uint256 _genes, address _sendTo, bool _hatched, uint8 promoGene) external onlyCOO { if (_sendTo == address(0)) { _sendTo = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createBitKoi(0, 0, 0, _genes, _hatched, promoGene, _sendTo); } } contract BitKoiCore is BitKoiMinting { constructor(address _proxyRegistryAddress) ERC721Tradable("BitKoi", "BITKOI", _proxyRegistryAddress) { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // the creator of the contract is also the initial COO cfoAddress = msg.sender; //start with an initial fish _createBitKoi(0, 0, 0, type(uint256).max, true, 0, address(msg.sender)); } string baseURI = "https://www.bitkoi.co/api/nft/"; string contractMainURI = "https://www.bitkoi.co"; function baseTokenURI() public view returns (string memory) { return baseURI; } function setBaseTokenURI(string memory _newBaseURI) public onlyCLevel { baseURI = _newBaseURI; } function setContractURI(string memory _newContractURI) public onlyCLevel { contractMainURI = _newContractURI; } function tokenURI(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } function contractURI() public view returns (string memory) { return contractMainURI; } function unpause() override public onlyCEO whenPaused { require(address(bitKoiTraits) != address(0)); // Actually unpause the contract. super.unpause(); } function withdrawBalance() external onlyCFO { payable(cfoAddress).transfer(address(this).balance); } /// @notice Returns all the relevant information about a specific fish. /// @param _id The ID of the fish we're looking up function getBitKoi(uint256 _id) external view returns ( bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint64 spawnTime, uint64 hatchTime, uint256 parent1Id, uint256 parent2Id, uint256 generation, uint256 cooldownEndBlock, uint256 genes, uint8 promoGene ) { BitKoi storage fish = bitKoi[_id]; isReady = (fish.cooldownEndBlock <= block.number); uint256 bitKoiGenes; if (fish.hatchTime > 0){ bitKoiGenes = fish.genes; } cooldownIndex = uint256(fish.cooldownIndex); nextActionAt = uint256(fish.cooldownEndBlock); spawnTime = uint64(fish.spawnTime); hatchTime = uint64(fish.hatchTime); parent1Id = uint256(fish.parent1Id); parent2Id = uint256(fish.parent2Id); generation = uint256(fish.generation); cooldownEndBlock = uint256(fish.cooldownEndBlock); genes = bitKoiGenes; promoGene = uint8(fish.promoGene); } }
update whether or not holders are required to mint
function resetMintEventClock() external onlyCLevel { mintEventStarted = block.timestamp; }
2,415,386
pragma solidity ^0.4.25; contract IVoteHistory { function WhoDidThePlayerVote(IPlayer player) public returns(IPlayer); } contract IParticipatable { function GetParticipants() public returns(IPlayer[] memory); function EnableParticipant(IPlayer player) public ; function DisableParticipant(IPlayer player) public ; function DisableAllParticipants() public ; function EnableAllParticipants() public ; function IInitializable(IPlayer[] memory players) public ; function IsRegisteredParticipant(IPlayer player) public returns(bool); function CanParticipate(IPlayer player) public returns(bool); function ParticipatablePlayersCount() public returns(uint); } contract IBallot is IVoteHistory, IParticipatable { function DidVote(IPlayer player) public returns(bool); function TryVote(IPlayer byWho, IPlayer toWho) public returns(bool); function GetWinners() public returns(IPlayer[] memory); function IsSoloWinder() public returns(bool); function IsZeroWinders() public returns(bool); function IsEveryVotableOnesVoted() public returns(bool); } contract IChatable { function TryChat(IPlayer player, string memory message) public returns(bool); } contract ISpokenEvent { /// Occurs when event spoken. arguments are timestamp, player, message. event eventSpoken(uint timestamp, IPlayer player, string message); } contract IChatLog is IParticipatable, IChatable, ISpokenEvent { function GetAllMessages() public returns(ChatMessage[]); // havent realized ChatMessage function GetNewestMessage() public returns(ChatMessage ); function PrintSystemMessage(string memory message) public ; } contract IChatter is IChatLog, ITimeLimitable, IInitializableIPlayerArr { } contract IInitializable { function Initialize() public; } contract ISequentialChatter is IChatter, ITimeLimitForwardable { function GetSpeakingPlayer() public returns(IPlayer); function HaveEveryoneSpoke() public returns(bool); } // this abstact contract should be added by field to implement 'null' case contract IClock { function GetNth_day() public returns(uint); function DayPlusPlus() public; function GetRealTimeInSeconds() public returns(uint); } contract IDependencyInjection { function BallotFactory() public returns(IBallot); function ChatLogFactory() public returns(IChatLog); function ChatterFactory() public returns(IChatter); function ClockFactory() public returns(IClock); function PlayerFactoryFactory() public returns(IPlayerFactory); function PlayerManager() public returns(ITHQBY_PlayerManager); //IScene SceneFactory(string name); function SettingsFactory() public returns(ITHQBY_Settings); function SceneManagerFactory() public returns(ISceneManager); function ParticipatableFactory() public returns(IParticipatable); function RoleBidderFactory() public returns(IRoleBidder); function SequentialChatterFactory() public returns(ISequentialChatter); function TimeLimitableFactory() public returns(ITimeLimitable); function SceneDAYFactory() public returns(SceneDAY); function SceneDAY_PKFactory() public returns(SceneDAY_PK); function NIGHT_POLICE_Factory() public returns(SceneNIGHT_POLICE); function NIGHT_KILLER_Factory() public returns(SceneNIGHT_KILLER); function Initialize() public; function LateInitiizeAfterRoleBide() public; } contract IGameController { function GetLivingPlayers() public returns(IPlayer[] memory); function GetDeadPlayers() public returns(IPlayer[] memory); function RegisterNewPlayerAndReturnID(address player) public returns(uint); // object address } contract IPlayer is ISpokenEvent { function SenderAddress() public returns(address); function GetVotingWeightAsPercent() public returns(uint); function GetRole() public returns(string memory); function GetId() public returns(uint); function SetId(uint id) public ; function GetIsAlive() public returns(bool); function KillMe() public ; //function Speak(string message) public ; //bool TryVote(uint playerID) public ; function speak (string message) public; function TryVote (uint playerID) returns(bool); } contract IPlayerFactory { function Create(string memory str) public returns(IPlayer); } contract IPlayerManager is IInitializableIPlayerArr { function GetPlayer(uint id) public returns(IPlayer); function GetAllPlayers() public returns(IPlayer[] memory); function GetAllLivingPlayers() public returns(IPlayer[] memory); function GetDeadPlayers() public returns(IPlayer[] memory); } contract IInitializableIPlayerArr { function Initialize(IPlayer[] memory) public; } contract IRoleBidder is IInitializable { function Bid(uint playerID, string memory role, uint bidAmount) public ; function HasEveryoneBid() public returns(bool); function SetPlayersCount(uint playersCount) public ; function CreateRoles() public returns(IPlayer[] memory); function GetIsActive() public returns(bool); } contract IScene is ITimeLimitable, ITimeLimitForwardable { function Initialize(ISceneManagerFriendToScene sceneMng, IPlayer[] memory players) public ; function GetSceneName() public returns(string memory);//return this.GetType().ToString(); function Ballot() public returns(IBallot); function Chatter() public returns(IChatter); function Refresh() public ; } contract IPrivateScene is IScene { function ZeroVotingResultHandler() public ; function OneVotingResultHandler(IPlayer result) public ; function MoreVotingResultHandler(IPlayer[] memory result) public ; function DoesPlayerHavePrivilageToMoveForward(IPlayer player) public returns(bool); } contract ISceneManager is ITimeLimitForwardable, IInitializable { function GetCurrentScene() public returns(IScene); } contract ISceneManagerFriendToScene is ISceneManager { function MoveForwardToNewScene(IScene newScene) public ; } contract ITHQBYPlayerInterface { //starting game function Bid(string memory role, uint bidAmount) public ; //accessing function getID(uint id) public returns(uint); function getRole(string memory role) public returns(string memory); function getChatLog(ChatMessage[] memory msgs) public returns(IChatLog); //communicating function TryChat(string memory message) public returns(bool); //action method function TryVote(uint playerID) public returns(bool); } contract ITHQBY_PlayerManager is IPlayerManager { function GetLivingPolicePlayers() public returns(IPlayer[] memory); function GetLivingCitizenPlayers() public returns(IPlayer[] memory); function GetLivingKillerPlayers() public returns(IPlayer[] memory); } contract ITHQBY_Settings { function DAY() public returns(string memory); function DAY_PK() public returns(string memory); function NIGHT_KILLER() public returns(string memory); function NIGHT_POLICE() public returns(string memory); function POLICE() public returns(string memory); function CITIZEN() public returns(string memory); function KILLER() public returns(string memory); } contract ITimeLimitable is IClock { function IsOverTime() public returns(bool); function SetTimeLimit(uint secondss) public ; function IncrementTimeLimit(int secondss) public ; function SetTimerOn() public ; } contract ITimeLimitForwardable is ITimeLimitable { event moveForward(Action); // ??? and I may in the future put all event in a seperate contract function TryMoveForward(IPlayer player) public returns(bool); }
starting gameaccessingcommunicatingaction method
{ function Bid(string memory role, uint bidAmount) public ; function getID(uint id) public returns(uint); function getRole(string memory role) public returns(string memory); function getChatLog(ChatMessage[] memory msgs) public returns(IChatLog); function TryChat(string memory message) public returns(bool); function TryVote(uint playerID) public returns(bool); }
6,449,232
pragma solidity ^0.5.17; import "./ErrorDecoder.sol"; import "../token/IApproveAndCall.sol"; /** * Base contract for receiving approval from SOV token */ contract ApprovalReceiver is ErrorDecoder, IApproveAndCall { modifier onlyThisContract() { //accepts calls only from receiveApproval function require(msg.sender == address(this), "unauthorized"); _; } /** * @notice receives approval from SOV token * @param _data the data will be used for low level call */ function receiveApproval( address _sender, uint256 _amount, address _token, bytes calldata _data ) external { //accepts calls only from SOV token require(msg.sender == _getToken(), "unauthorized"); require(msg.sender == _token, "unauthorized"); //only allowed methods bool isAllowed = false; bytes4[] memory selectors = _getSelectors(); bytes4 sig = _getSig(_data); for (uint256 i = 0; i < selectors.length; i++) { if (sig == selectors[i]) { isAllowed = true; break; } } require(isAllowed, "method is not allowed"); //check sender and amount address sender; uint256 amount; (, sender, amount) = abi.decode(abi.encodePacked(bytes28(0), _data), (bytes32, address, uint256)); require(sender == _sender, "sender mismatch"); require(amount == _amount, "amount mismatch"); _call(_data); } /** * @notice returns token address, only this address can be a sender for receiveApproval * @dev should be overridden in child contracts, otherwise error will be thrown */ function _getToken() internal view returns (address) { return address(0); } /** * @notice returns list of function selectors allowed to be invoked * @dev should be overridden in child contracts, otherwise error will be thrown */ function _getSelectors() internal view returns (bytes4[] memory) { return new bytes4[](0); } function _call(bytes memory _data) internal { //makes call and reads error message (bool success, bytes memory returnData) = address(this).call(_data); if (!success) { if (returnData.length <= ERROR_MESSAGE_SHIFT) { revert("receiveApproval: Transaction execution reverted."); } else { revert(_addErrorMessage("receiveApproval: ", string(returnData))); } } } function _getSig(bytes memory _data) internal pure returns (bytes4 sig) { assembly { sig := mload(add(_data, 32)) } } }
makes call and reads error message
function _call(bytes memory _data) internal { (bool success, bytes memory returnData) = address(this).call(_data); if (!success) { if (returnData.length <= ERROR_MESSAGE_SHIFT) { revert("receiveApproval: Transaction execution reverted."); revert(_addErrorMessage("receiveApproval: ", string(returnData))); } } }
1,840,652
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { LibDiamondCut } from "./diamond/LibDiamondCut.sol"; import { DiamondFacet } from "./diamond/DiamondFacet.sol"; import { OwnershipFacet } from "./diamond/OwnershipFacet.sol"; import { LibDiamondStorage } from "./diamond/LibDiamondStorage.sol"; import { IDiamondCut } from "./diamond/IDiamondCut.sol"; import { IDiamondLoupe } from "./diamond/IDiamondLoupe.sol"; import { IERC165 } from "./diamond/IERC165.sol"; import { LibDiamondStorageDerivaDEX } from "./storage/LibDiamondStorageDerivaDEX.sol"; import { IDDX } from "./tokens/interfaces/IDDX.sol"; /** * @title DerivaDEX * @author DerivaDEX * @notice This is the diamond for DerivaDEX. All current * and future logic runs by way of this contract. * @dev This diamond implements the Diamond Standard (EIP #2535). */ contract DerivaDEX { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @notice This constructor initializes the upgrade machinery (as * per the Diamond Standard), sets the admin of the proxy * to be the deploying address (very temporary), and sets * the native DDX governance/operational token. * @param _ddxToken The native DDX token address. */ constructor(IDDX _ddxToken) public { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Temporarily set admin to the deploying address to facilitate // adding the Diamond functions dsDerivaDEX.admin = msg.sender; // Set DDX token address for token logic in facet contracts require(address(_ddxToken) != address(0), "DerivaDEX: ddx token is zero address."); dsDerivaDEX.ddxToken = _ddxToken; emit OwnershipTransferred(address(0), msg.sender); // Create DiamondFacet contract - // implements DiamondCut interface and DiamondLoupe interface DiamondFacet diamondFacet = new DiamondFacet(); // Create OwnershipFacet contract which implements ownership // functions and supportsInterface function OwnershipFacet ownershipFacet = new OwnershipFacet(); IDiamondCut.FacetCut[] memory diamondCut = new IDiamondCut.FacetCut[](2); // adding diamondCut function and diamond loupe functions diamondCut[0].facetAddress = address(diamondFacet); diamondCut[0].action = IDiamondCut.FacetCutAction.Add; diamondCut[0].functionSelectors = new bytes4[](6); diamondCut[0].functionSelectors[0] = DiamondFacet.diamondCut.selector; diamondCut[0].functionSelectors[1] = DiamondFacet.facetFunctionSelectors.selector; diamondCut[0].functionSelectors[2] = DiamondFacet.facets.selector; diamondCut[0].functionSelectors[3] = DiamondFacet.facetAddress.selector; diamondCut[0].functionSelectors[4] = DiamondFacet.facetAddresses.selector; diamondCut[0].functionSelectors[5] = DiamondFacet.supportsInterface.selector; // adding ownership functions diamondCut[1].facetAddress = address(ownershipFacet); diamondCut[1].action = IDiamondCut.FacetCutAction.Add; diamondCut[1].functionSelectors = new bytes4[](2); diamondCut[1].functionSelectors[0] = OwnershipFacet.transferOwnershipToSelf.selector; diamondCut[1].functionSelectors[1] = OwnershipFacet.getAdmin.selector; // execute internal diamondCut function to add functions LibDiamondCut.diamondCut(diamondCut, address(0), new bytes(0)); // adding ERC165 data ds.supportedInterfaces[IERC165.supportsInterface.selector] = true; ds.supportedInterfaces[IDiamondCut.diamondCut.selector] = true; bytes4 interfaceID = IDiamondLoupe.facets.selector ^ IDiamondLoupe.facetFunctionSelectors.selector ^ IDiamondLoupe.facetAddresses.selector ^ IDiamondLoupe.facetAddress.selector; ds.supportedInterfaces[interfaceID] = true; } // TODO(jalextowle): Remove this linter directive when // https://github.com/protofire/solhint/issues/248 is merged and released. /* solhint-disable ordering */ receive() external payable { revert("DerivaDEX does not directly accept ether."); } // Finds facet for function that is called and executes the // function if it is found and returns any value. fallback() external payable { LibDiamondStorage.DiamondStorage storage ds; bytes32 position = LibDiamondStorage.DIAMOND_STORAGE_POSITION; assembly { ds_slot := position } address facet = ds.selectorToFacetAndPosition[msg.sig].facetAddress; require(facet != address(0), "Function does not exist."); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(0, 0, size) switch result case 0 { revert(0, size) } default { return(0, size) } } } /* solhint-enable ordering */ } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * * Implementation of internal diamondCut function. /******************************************************************************/ import "./LibDiamondStorage.sol"; import "./IDiamondCut.sol"; library LibDiamondCut { event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); // Internal function version of diamondCut // This code is almost the same as the external diamondCut, // except it is using 'FacetCut[] memory _diamondCut' instead of // 'FacetCut[] calldata _diamondCut'. // The code is duplicated to prevent copying calldata to memory which // causes an error for a two dimensional array. function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { require(_diamondCut.length > 0, "LibDiamondCut: No facets to cut"); for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { addReplaceRemoveFacetSelectors( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addReplaceRemoveFacetSelectors( address _newFacetAddress, IDiamondCut.FacetCutAction _action, bytes4[] memory _selectors ) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); // add or replace functions if (_newFacetAddress != address(0)) { uint256 facetAddressPosition = ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition; // add new facet address if it does not exist if ( facetAddressPosition == 0 && ds.facetFunctionSelectors[_newFacetAddress].functionSelectors.length == 0 ) { ensureHasContractCode(_newFacetAddress, "LibDiamondCut: New facet has no code"); facetAddressPosition = ds.facetAddresses.length; ds.facetAddresses.push(_newFacetAddress); ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition = uint16(facetAddressPosition); } // add or replace selectors for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; // add if (_action == IDiamondCut.FacetCutAction.Add) { require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists"); addSelector(_newFacetAddress, selector); } else if (_action == IDiamondCut.FacetCutAction.Replace) { // replace require( oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function" ); removeSelector(oldFacetAddress, selector); addSelector(_newFacetAddress, selector); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } } else { require( _action == IDiamondCut.FacetCutAction.Remove, "LibDiamondCut: action not set to FacetCutAction.Remove" ); // remove selectors for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; removeSelector(ds.selectorToFacetAndPosition[selector].facetAddress, selector); } } } function addSelector(address _newFacet, bytes4 _selector) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 selectorPosition = ds.facetFunctionSelectors[_newFacet].functionSelectors.length; ds.facetFunctionSelectors[_newFacet].functionSelectors.push(_selector); ds.selectorToFacetAndPosition[_selector].facetAddress = _newFacet; ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = uint16(selectorPosition); } function removeSelector(address _oldFacetAddress, bytes4 _selector) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); require(_oldFacetAddress != address(0), "LibDiamondCut: Can't remove or replace function that doesn't exist"); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition; uint256 lastSelectorPosition = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.length - 1; bytes4 lastSelector = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[lastSelectorPosition]; // if not the same then replace _selector with lastSelector if (lastSelector != _selector) { ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[selectorPosition] = lastSelector; ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint16(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition]; uint256 facetAddressPosition = ds.facetFunctionSelectors[_oldFacetAddress].facetAddressPosition; if (_oldFacetAddress != lastFacetAddress) { ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = uint16(facetAddressPosition); } ds.facetAddresses.pop(); delete ds.facetFunctionSelectors[_oldFacetAddress]; } } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { LibDiamondCut.ensureHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function ensureHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * * Implementation of diamondCut external function and DiamondLoupe interface. /******************************************************************************/ import "./LibDiamondStorage.sol"; import "./LibDiamondCut.sol"; import "../storage/LibDiamondStorageDerivaDEX.sol"; import "./IDiamondCut.sol"; import "./IDiamondLoupe.sol"; import "./IERC165.sol"; contract DiamondFacet is IDiamondCut, IDiamondLoupe, IERC165 { // Standard diamondCut external function /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external override { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "DiamondFacet: Must own the contract"); require(_diamondCut.length > 0, "DiamondFacet: No facets to cut"); for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { LibDiamondCut.addReplaceRemoveFacetSelectors( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } emit DiamondCut(_diamondCut, _init, _calldata); LibDiamondCut.initializeDiamondCut(_init, _calldata); } // Diamond Loupe Functions //////////////////////////////////////////////////////////////////// /// These functions are expected to be called frequently by tools. // // struct Facet { // address facetAddress; // bytes4[] functionSelectors; // } // /// @notice Gets all facets and their selectors. /// @return facets_ Facet function facets() external view override returns (Facet[] memory facets_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 numFacets = ds.facetAddresses.length; facets_ = new Facet[](numFacets); for (uint256 i; i < numFacets; i++) { address facetAddress_ = ds.facetAddresses[i]; facets_[i].facetAddress = facetAddress_; facets_[i].functionSelectors = ds.facetFunctionSelectors[facetAddress_].functionSelectors; } } /// @notice Gets all the function selectors provided by a facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view override returns (bytes4[] memory facetFunctionSelectors_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetFunctionSelectors_ = ds.facetFunctionSelectors[_facet].functionSelectors; } /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view override returns (address[] memory facetAddresses_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetAddresses_ = ds.facetAddresses; } /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view override returns (address facetAddress_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetAddress_ = ds.selectorToFacetAndPosition[_functionSelector].facetAddress; } // This implements ERC-165. function supportsInterface(bytes4 _interfaceId) external view override returns (bool) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); return ds.supportedInterfaces[_interfaceId]; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { LibDiamondStorageDerivaDEX } from "../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorage } from "../diamond/LibDiamondStorage.sol"; import { IERC165 } from "./IERC165.sol"; contract OwnershipFacet { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @notice This function transfers ownership to self. This is done * so that we can ensure upgrades (using diamondCut) and * various other critical parameter changing scenarios * can only be done via governance (a facet). */ function transferOwnershipToSelf() external { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Not authorized"); dsDerivaDEX.admin = address(this); emit OwnershipTransferred(msg.sender, address(this)); } /** * @notice This gets the admin for the diamond. * @return Admin address. */ function getAdmin() external view returns (address) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); return dsDerivaDEX.admin; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ library LibDiamondStorage { struct FacetAddressAndPosition { address facetAddress; uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint16 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the facet address in the facetAddresses array // and the position of the selector in the facetSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; } bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ interface IDiamondCut { enum FacetCutAction { Add, Replace, Remove } struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ import "./IDiamondCut.sol"; // A loupe is a small magnifying glass used to look at diamonds. // These functions look at diamonds interface IDiamondLoupe { /// These functions are expected to be called frequently /// by tools. struct Facet { address facetAddress; bytes4[] functionSelectors; } /// @notice Gets all facet addresses and their four byte function selectors. /// @return facets_ Facet function facets() external view returns (Facet[] memory facets_); /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view returns (address[] memory facetAddresses_); /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceId The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDDX } from "../tokens/interfaces/IDDX.sol"; library LibDiamondStorageDerivaDEX { struct DiamondStorageDerivaDEX { string name; address admin; IDDX ddxToken; } bytes32 constant DIAMOND_STORAGE_POSITION_DERIVADEX = keccak256("diamond.standard.diamond.storage.DerivaDEX.DerivaDEX"); function diamondStorageDerivaDEX() internal pure returns (DiamondStorageDerivaDEX storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_DERIVADEX; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IDDX { function transfer(address _recipient, uint256 _amount) external returns (bool); function mint(address _recipient, uint256 _amount) external; function delegate(address _delegatee) external; function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool); function approve(address _spender, uint256 _amount) external returns (bool); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDDX } from "./interfaces/IDDX.sol"; /** * @title DDXWalletCloneable * @author DerivaDEX * @notice This is a cloneable on-chain DDX wallet that holds a trader's * stakes and issued rewards. */ contract DDXWalletCloneable { // Whether contract has already been initialized once before bool initialized; /** * @notice This function initializes the on-chain DDX wallet * for a given trader. * @param _trader Trader address. * @param _ddxToken DDX token address. * @param _derivaDEX DerivaDEX Proxy address. */ function initialize( address _trader, IDDX _ddxToken, address _derivaDEX ) external { // Prevent initializing more than once require(!initialized, "DDXWalletCloneable: already init."); initialized = true; // Automatically delegate the holdings of this contract/wallet // back to the trader. _ddxToken.delegate(_trader); // Approve the DerivaDEX Proxy contract for unlimited transfers _ddxToken.approve(_derivaDEX, uint96(-1)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { TraderDefs } from "../../libs/defs/TraderDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { DDXWalletCloneable } from "../../tokens/DDXWalletCloneable.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { IDDXWalletCloneable } from "../../tokens/interfaces/IDDXWalletCloneable.sol"; import { LibTraderInternal } from "./LibTraderInternal.sol"; /** * @title Trader * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to traders - staking DDX, withdrawing * DDX, receiving DDX rewards, etc. */ contract Trader { using SafeMath96 for uint96; using SafeMath for uint256; using SafeERC20 for IERC20; event RewardCliffSet(bool rewardCliffSet); event DDXRewardIssued(address trader, uint96 amount); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Trader: must be called by Gov."); _; } /** * @notice Limits functions to only be called post reward cliff. */ modifier postRewardCliff { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); require(dsTrader.rewardCliff, "Trader: prior to reward cliff."); _; } /** * @notice This function initializes the state with some critical * information, including the on-chain wallet cloneable * contract address. This can only be called via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. */ function initialize(IDDXWalletCloneable _ddxWalletCloneable) external onlyAdmin { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Set the on-chain DDX wallet cloneable contract address dsTrader.ddxWalletCloneable = _ddxWalletCloneable; } /** * @notice This function sets the reward cliff. * @param _rewardCliff Reward cliff. */ function setRewardCliff(bool _rewardCliff) external onlyAdmin { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Set the reward cliff (boolean value) dsTrader.rewardCliff = _rewardCliff; emit RewardCliffSet(_rewardCliff); } /** * @notice This function issues DDX rewards to a trader. It can * only be called via governance. * @param _amount DDX tokens to be rewarded. * @param _trader Trader recipient address. */ function issueDDXReward(uint96 _amount, address _trader) external onlyAdmin { // Call the internal function to issue DDX rewards. This // internal function is shareable with other facets that import // the LibTraderInternal library. LibTraderInternal.issueDDXReward(_amount, _trader); } /** * @notice This function issues DDX rewards to an external address. * It can only be called via governance. * @param _amount DDX tokens to be rewarded. * @param _recipient External recipient address. */ function issueDDXToRecipient(uint96 _amount, address _recipient) external onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.mint(_recipient, _amount); emit DDXRewardIssued(_recipient, _amount); } /** * @notice This function lets traders take DDX from their wallet * into their on-chain DDX wallet. It's important to note * that any DDX staked from the trader to this wallet * delegates the voting rights of that stake back to the * user. To be more explicit, if Alice's personal wallet is * delegating to Bob, and she now stakes a portion of her * DDX into this on-chain DDX wallet of hers, those tokens * will now count towards her voting power, not Bob's, since * her on-chain wallet is automatically delegating back to * her. * @param _amount The DDX tokens to be staked. */ function stakeDDXFromTrader(uint96 _amount) external { transferDDXToWallet(msg.sender, _amount); } /** * @notice This function lets traders send DDX from their wallet * into another trader's on-chain DDX wallet. It's * important to note that any DDX staked to this wallet * delegates the voting rights of that stake back to the * user. * @param _trader Trader address to receive DDX (inside their * wallet, which will be created if it does not already * exist). * @param _amount The DDX tokens to be staked. */ function sendDDXFromTraderToTraderWallet(address _trader, uint96 _amount) external { transferDDXToWallet(_trader, _amount); } /** * @notice This function lets traders withdraw DDX from their * on-chain DDX wallet to their personal wallet. It's * important to note that the voting rights for any DDX * withdrawn are returned back to the delegatee of the * user's personal wallet. To be more explicit, if Alice is * personal wallet is delegating to Bob, and she now * withdraws a portion of her DDX from this on-chain DDX * wallet of hers, those tokens will now count towards Bob's * voting power, not her's, since her on-chain wallet is * automatically delegating back to her, but her personal * wallet is delegating to Bob. Withdrawals can only happen * when the governance cliff is lifted. * @param _amount The DDX tokens to be withdrawn. */ function withdrawDDXToTrader(uint96 _amount) external postRewardCliff { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[msg.sender]; LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Subtract trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.sub96(_amount); // Transfer DDX from trader's on-chain wallet to the trader dsDerivaDEX.ddxToken.transferFrom(trader.ddxWalletContract, msg.sender, _amount); } /** * @notice This function gets the attributes for a given trader. * @param _trader Trader address. */ function getTrader(address _trader) external view returns (TraderDefs.Trader memory) { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); return dsTrader.traders[_trader]; } /** * @notice This function transfers DDX from the sender * to another trader's DDX wallet. * @param _trader Trader address' DDX wallet address to transfer * into. * @param _amount Amount of DDX to transfer. */ function transferDDXToWallet(address _trader, uint96 _amount) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[_trader]; // If trader does not have a DDX on-chain wallet yet, create one if (trader.ddxWalletContract == address(0)) { LibTraderInternal.createDDXWallet(_trader); } LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Add trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.add96(_amount); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.transferFrom(msg.sender, trader.ddxWalletContract, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @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; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 SafeMath96 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add96(uint96 a, uint96 b) internal pure returns (uint96) { uint96 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 sub96(uint96 a, uint96 b) internal pure returns (uint96) { return sub96(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 sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); uint96 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title TraderDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * traders. */ library TraderDefs { // Consists of trader attributes, including the DDX balance and // the onchain DDX wallet contract address struct Trader { uint96 ddxBalance; address ddxWalletContract; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { TraderDefs } from "../libs/defs/TraderDefs.sol"; import { IDDXWalletCloneable } from "../tokens/interfaces/IDDXWalletCloneable.sol"; library LibDiamondStorageTrader { struct DiamondStorageTrader { mapping(address => TraderDefs.Trader) traders; bool rewardCliff; IDDXWalletCloneable ddxWalletCloneable; } bytes32 constant DIAMOND_STORAGE_POSITION_TRADER = keccak256("diamond.standard.diamond.storage.DerivaDEX.Trader"); function diamondStorageTrader() internal pure returns (DiamondStorageTrader storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_TRADER; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { IDDX } from "./IDDX.sol"; interface IDDXWalletCloneable { function initialize( address _trader, IDDX _ddxToken, address _derivaDEX ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { LibClone } from "../../libs/LibClone.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { TraderDefs } from "../../libs/defs/TraderDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { IDDXWalletCloneable } from "../../tokens/interfaces/IDDXWalletCloneable.sol"; /** * @title TraderInternalLib * @author DerivaDEX * @notice This is a library of internal functions mainly defined in * the Trader facet, but used in other facets. */ library LibTraderInternal { using SafeMath96 for uint96; using SafeMath for uint256; using SafeERC20 for IERC20; event DDXRewardIssued(address trader, uint96 amount); /** * @notice This function creates a new DDX wallet for a trader. * @param _trader Trader address. */ function createDDXWallet(address _trader) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Leveraging the minimal proxy contract/clone factory pattern // as described here (https://eips.ethereum.org/EIPS/eip-1167) IDDXWalletCloneable ddxWallet = IDDXWalletCloneable(LibClone.createClone(address(dsTrader.ddxWalletCloneable))); LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Cloneable contracts have no constructor, so instead we use // an initialize function. This initialize delegates this // on-chain DDX wallet back to the trader and sets the allowance // for the DerivaDEX Proxy contract to be unlimited. ddxWallet.initialize(_trader, dsDerivaDEX.ddxToken, address(this)); // Store the on-chain wallet address in the trader's storage dsTrader.traders[_trader].ddxWalletContract = address(ddxWallet); } /** * @notice This function issues DDX rewards to a trader. It can be * called by any facet part of the diamond. * @param _amount DDX tokens to be rewarded. * @param _trader Trader address. */ function issueDDXReward(uint96 _amount, address _trader) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[_trader]; // If trader does not have a DDX on-chain wallet yet, create one if (trader.ddxWalletContract == address(0)) { createDDXWallet(_trader); } LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Add trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.add96(_amount); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.mint(trader.ddxWalletContract, _amount); emit DDXRewardIssued(_trader, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. 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. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly library LibClone { function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and(eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))) } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath32 } from "../../libs/SafeMath32.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { MathHelpers } from "../../libs/MathHelpers.sol"; import { InsuranceFundDefs } from "../../libs/defs/InsuranceFundDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageInsuranceFund } from "../../storage/LibDiamondStorageInsuranceFund.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { LibDiamondStoragePause } from "../../storage/LibDiamondStoragePause.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { LibTraderInternal } from "../trader/LibTraderInternal.sol"; import { IAToken } from "../interfaces/IAToken.sol"; import { IComptroller } from "../interfaces/IComptroller.sol"; import { ICToken } from "../interfaces/ICToken.sol"; import { IDIFundToken } from "../../tokens/interfaces/IDIFundToken.sol"; import { IDIFundTokenFactory } from "../../tokens/interfaces/IDIFundTokenFactory.sol"; interface IERCCustom { function decimals() external view returns (uint8); } /** * @title InsuranceFund * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to insurance mining - staking directly * into the insurance fund and receiving a DDX issuance to be * used in governance/operations. * @dev This facet at the moment only handles insurance mining. It can * and will grow to handle the remaining functions of the insurance * fund, such as receiving quote-denominated fees and liquidation * spreads, among others. The Diamond storage will only be * affected when facet functions are called via the proxy * contract, no checks are necessary. */ contract InsuranceFund { using SafeMath32 for uint32; using SafeMath96 for uint96; using SafeMath for uint96; using SafeMath for uint256; using MathHelpers for uint32; using MathHelpers for uint96; using MathHelpers for uint224; using MathHelpers for uint256; using SafeERC20 for IERC20; // Compound-related constant variables // kovan: 0x5eAe89DC1C671724A672ff0630122ee834098657 IComptroller public constant COMPTROLLER = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); // kovan: 0x61460874a7196d6a22D1eE4922473664b3E95270 IERC20 public constant COMP_TOKEN = IERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888); event InsuranceFundInitialized( uint32 interval, uint32 withdrawalFactor, uint96 mineRatePerBlock, uint96 advanceIntervalReward, uint256 miningFinalBlockNumber ); event InsuranceFundCollateralAdded( bytes32 collateralName, address underlyingToken, address collateralToken, InsuranceFundDefs.Flavor flavor ); event StakedToInsuranceFund(address staker, uint96 amount, bytes32 collateralName); event WithdrawnFromInsuranceFund(address withdrawer, uint96 amount, bytes32 collateralName); event AdvancedOtherRewards(address intervalAdvancer, uint96 advanceReward); event InsuranceMineRewardsClaimed(address claimant, uint96 minedAmount); event MineRatePerBlockSet(uint96 mineRatePerBlock); event AdvanceIntervalRewardSet(uint96 advanceIntervalReward); event WithdrawalFactorSet(uint32 withdrawalFactor); event InsuranceMiningExtended(uint256 miningFinalBlockNumber); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "IFund: must be called by Gov."); _; } /** * @notice Limits functions to only be called while insurance * mining is ongoing. */ modifier insuranceMiningOngoing { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(block.number < dsInsuranceFund.miningFinalBlockNumber, "IFund: mining ended."); _; } /** * @notice Limits functions to only be called while other * rewards checkpointing is ongoing. */ modifier otherRewardsOngoing { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require( dsInsuranceFund.otherRewardsCheckpointBlock < dsInsuranceFund.miningFinalBlockNumber, "IFund: other rewards checkpointing ended." ); _; } /** * @notice Limits functions to only be called via governance. */ modifier isNotPaused { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); require(!dsPause.isPaused, "IFund: paused."); _; } /** * @notice This function initializes the state with some critical * information. This can only be called via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @param _interval The interval length (blocks) for other rewards * claiming checkpoints (i.e. COMP and extra aTokens). * @param _withdrawalFactor Specifies the withdrawal fee if users * redeem their insurance tokens. * @param _mineRatePerBlock The DDX tokens to be mined each interval * for insurance mining. * @param _advanceIntervalReward DDX reward for participant who * advances the insurance mining interval. * @param _insuranceMiningLength Insurance mining length (blocks). */ function initialize( uint32 _interval, uint32 _withdrawalFactor, uint96 _mineRatePerBlock, uint96 _advanceIntervalReward, uint256 _insuranceMiningLength, IDIFundTokenFactory _diFundTokenFactory ) external onlyAdmin { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Set the interval for other rewards claiming checkpoints // (i.e. COMP and aTokens that accrue to the contract) // (e.g. 40320 ~ 1 week = 7 * 24 * 60 * 60 / 15 blocks) dsInsuranceFund.interval = _interval; // Keep track of the block number for other rewards checkpoint, // which is initialized to the block number the insurance fund // facet is added to the diamond dsInsuranceFund.otherRewardsCheckpointBlock = block.number; // Set the withdrawal factor, capped at 1000, implying 0% fee require(_withdrawalFactor <= 1000, "IFund: withdrawal fee too high."); // Set withdrawal ratio, which will be used with a 1e3 scaling // factor, meaning a value of 995 implies a withdrawal fee of // 0.5% since 995/1e3 => 0.995 dsInsuranceFund.withdrawalFactor = _withdrawalFactor; // Set the insurance mine rate per block. // (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens)) dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock; // Incentive to advance the other rewards interval // (e.g. 100e18 = 100 DDX) dsInsuranceFund.advanceIntervalReward = _advanceIntervalReward; // Set the final block number for insurance mining dsInsuranceFund.miningFinalBlockNumber = block.number.add(_insuranceMiningLength); // DIFundToken factory to deploy DerivaDEX Insurance Fund token // contracts pertaining to each supported collateral dsInsuranceFund.diFundTokenFactory = _diFundTokenFactory; // Initialize the DDX market state index and block. These values // are critical for computing the DDX continuously issued per // block dsInsuranceFund.ddxMarketState.index = 1e36; dsInsuranceFund.ddxMarketState.block = block.number.safe32("IFund: exceeds 32 bits"); emit InsuranceFundInitialized( _interval, _withdrawalFactor, _mineRatePerBlock, _advanceIntervalReward, dsInsuranceFund.miningFinalBlockNumber ); } /** * @notice This function sets the DDX mine rate per block. * @param _mineRatePerBlock The DDX tokens mine rate per block. */ function setMineRatePerBlock(uint96 _mineRatePerBlock) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // NOTE(jalextowle): We must update the DDX Market State prior to // changing the mine rate per block in order to lock in earned rewards // for insurance mining participants. updateDDXMarketState(dsInsuranceFund); require(_mineRatePerBlock != dsInsuranceFund.mineRatePerBlock, "IFund: same as current value."); // Set the insurance mine rate per block. // (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens)) dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock; emit MineRatePerBlockSet(_mineRatePerBlock); } /** * @notice This function sets the advance interval reward. * @param _advanceIntervalReward DDX reward for advancing interval. */ function setAdvanceIntervalReward(uint96 _advanceIntervalReward) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_advanceIntervalReward != dsInsuranceFund.advanceIntervalReward, "IFund: same as current value."); // Set the advance interval reward dsInsuranceFund.advanceIntervalReward = _advanceIntervalReward; emit AdvanceIntervalRewardSet(_advanceIntervalReward); } /** * @notice This function sets the withdrawal factor. * @param _withdrawalFactor Withdrawal factor. */ function setWithdrawalFactor(uint32 _withdrawalFactor) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_withdrawalFactor != dsInsuranceFund.withdrawalFactor, "IFund: same as current value."); // Set the withdrawal factor, capped at 1000, implying 0% fee require(dsInsuranceFund.withdrawalFactor <= 1000, "IFund: withdrawal fee too high."); dsInsuranceFund.withdrawalFactor = _withdrawalFactor; emit WithdrawalFactorSet(_withdrawalFactor); } /** * @notice This function extends insurance mining. * @param _insuranceMiningExtension Insurance mining extension * (blocks). */ function extendInsuranceMining(uint256 _insuranceMiningExtension) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_insuranceMiningExtension != 0, "IFund: invalid extension."); // Extend the mining final block number dsInsuranceFund.miningFinalBlockNumber = dsInsuranceFund.miningFinalBlockNumber.add(_insuranceMiningExtension); emit InsuranceMiningExtended(dsInsuranceFund.miningFinalBlockNumber); } /** * @notice This function adds a new supported collateral type that * can be staked to the insurance fund. It can only * be called via governance. * @dev For vanilla contracts (e.g. USDT, USDC, etc.), the * underlying token equals address(0). * @param _collateralName Name of collateral. * @param _collateralSymbol Symbol of collateral. * @param _underlyingToken Deployed address of underlying token. * @param _collateralToken Deployed address of collateral token. * @param _flavor Collateral flavor (Vanilla, Compound, Aave, etc.). */ function addInsuranceFundCollateral( string memory _collateralName, string memory _collateralSymbol, address _underlyingToken, address _collateralToken, InsuranceFundDefs.Flavor _flavor ) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain bytes32 representation of collateral name bytes32 result; assembly { result := mload(add(_collateralName, 32)) } // Ensure collateral has not already been added require( dsInsuranceFund.stakeCollaterals[result].collateralToken == address(0), "IFund: collateral already added." ); require(_collateralToken != address(0), "IFund: collateral address must be non-zero."); require(!isCollateralTokenPresent(_collateralToken), "IFund: collateral token already present."); require(_underlyingToken != _collateralToken, "IFund: token addresses are same."); if (_flavor == InsuranceFundDefs.Flavor.Vanilla) { // If collateral is of vanilla flavor, there should only be // a value for collateral token, and underlying token should // be empty require(_underlyingToken == address(0), "IFund: underlying address non-zero for Vanilla."); } // Add collateral type to storage, including its underlying // token and collateral token addresses, and its flavor dsInsuranceFund.stakeCollaterals[result].underlyingToken = _underlyingToken; dsInsuranceFund.stakeCollaterals[result].collateralToken = _collateralToken; dsInsuranceFund.stakeCollaterals[result].flavor = _flavor; // Create a DerivaDEX Insurance Fund token contract associated // with this supported collateral dsInsuranceFund.stakeCollaterals[result].diFundToken = IDIFundToken( dsInsuranceFund.diFundTokenFactory.createNewDIFundToken( _collateralName, _collateralSymbol, IERCCustom(_collateralToken).decimals() ) ); dsInsuranceFund.collateralNames.push(result); emit InsuranceFundCollateralAdded(result, _underlyingToken, _collateralToken, _flavor); } /** * @notice This function allows participants to stake a supported * collateral type to the insurance fund. * @param _collateralName Name of collateral. * @param _amount Amount to stake. */ function stakeToInsuranceFund(bytes32 _collateralName, uint96 _amount) external insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Ensure this is a supported collateral type and that the user // has approved the proxy contract for transfer require(stakeCollateral.collateralToken != address(0), "IFund: invalid collateral."); // Ensure non-zero stake amount require(_amount > 0, "IFund: non-zero amount."); // Claim DDX for staking user. We do this prior to the stake // taking effect, thereby preventing someone from being rewarded // instantly for the stake. claimDDXFromInsuranceMining(msg.sender); // Increment the underlying capitalization stakeCollateral.cap = stakeCollateral.cap.add96(_amount); // Transfer collateral amount from user to proxy contract IERC20(stakeCollateral.collateralToken).safeTransferFrom(msg.sender, address(this), _amount); // Mint DIFund tokens to user stakeCollateral.diFundToken.mint(msg.sender, _amount); emit StakedToInsuranceFund(msg.sender, _amount, _collateralName); } /** * @notice This function allows participants to withdraw a supported * collateral type from the insurance fund. * @param _collateralName Name of collateral. * @param _amount Amount to stake. */ function withdrawFromInsuranceFund(bytes32 _collateralName, uint96 _amount) external isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Ensure this is a supported collateral type and that the user // has approved the proxy contract for transfer require(stakeCollateral.collateralToken != address(0), "IFund: invalid collateral."); // Ensure non-zero withdraw amount require(_amount > 0, "IFund: non-zero amount."); // Claim DDX for withdrawing user. We do this prior to the // redeem taking effect. claimDDXFromInsuranceMining(msg.sender); // Determine underlying to transfer based on how much underlying // can be redeemed given the current underlying capitalization // and how many DIFund tokens are globally available. This // theoretically fails in the scenario where globally there are // 0 insurance fund tokens, however that would mean the user // also has 0 tokens in their possession, and thus would have // nothing to be redeemed anyways. uint96 underlyingToTransferNoFee = _amount.proportion96(stakeCollateral.cap, stakeCollateral.diFundToken.totalSupply()); uint96 underlyingToTransfer = underlyingToTransferNoFee.proportion96(dsInsuranceFund.withdrawalFactor, 1e3); // Decrement the capitalization stakeCollateral.cap = stakeCollateral.cap.sub96(underlyingToTransferNoFee); // Increment the withdrawal fee cap stakeCollateral.withdrawalFeeCap = stakeCollateral.withdrawalFeeCap.add96( underlyingToTransferNoFee.sub96(underlyingToTransfer) ); // Transfer collateral amount from proxy contract to user IERC20(stakeCollateral.collateralToken).safeTransfer(msg.sender, underlyingToTransfer); // Burn DIFund tokens being redeemed from user stakeCollateral.diFundToken.burnFrom(msg.sender, _amount); emit WithdrawnFromInsuranceFund(msg.sender, _amount, _collateralName); } /** * @notice Advance other rewards interval */ function advanceOtherRewardsInterval() external otherRewardsOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Check if the current block has exceeded the interval bounds, // allowing for a new other rewards interval to be checkpointed require( block.number >= dsInsuranceFund.otherRewardsCheckpointBlock.add(dsInsuranceFund.interval), "IFund: advance too soon." ); // Maintain the USD-denominated sum of all Compound-flavor // assets. This needs to be stored separately than the rest // due to the way COMP tokens are rewarded to the contract in // order to properly disseminate to the user. uint96 normalizedCapCheckpointSumCompound; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Compound) { // If collateral is of type Compound, set the exchange // rate at this point in time. We do this so later on, // when claiming rewards, we know the exchange rate // checkpointed balances should be converted to // determine the USD-denominated value of holdings // needed to compute fair share of DDX rewards. stakeCollateral.exchangeRate = ICToken(stakeCollateral.collateralToken).exchangeRateStored().safe96( "IFund: amount exceeds 96 bits" ); // Set checkpoint cap for this Compound flavor // collateral to handle COMP distribution lookbacks stakeCollateral.checkpointCap = stakeCollateral.cap; // Increment the normalized Compound checkpoint cap // with the USD-denominated value normalizedCapCheckpointSumCompound = normalizedCapCheckpointSumCompound.add96( getUnderlyingTokenAmountForCompound(stakeCollateral.cap, stakeCollateral.exchangeRate) ); } else if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { // If collateral is of type Aave, we need to do some // custom Aave aToken reward distribution. We first // determine the contract's aToken balance for this // collateral type and subtract the underlying // aToken capitalization that are due to users. This // leaves us with the excess that has been rewarded // to the contract due to Aave's mechanisms, but // belong to the users. uint96 myATokenBalance = uint96(IAToken(stakeCollateral.collateralToken).balanceOf(address(this)).sub(stakeCollateral.cap)); // Store the aToken yield information dsInsuranceFund.aTokenYields[dsInsuranceFund.collateralNames[i]] = InsuranceFundDefs .ExternalYieldCheckpoint({ accrued: myATokenBalance, totalNormalizedCap: 0 }); } } // Ensure that the normalized cap sum is non-zero if (normalizedCapCheckpointSumCompound > 0) { // If there's Compound-type asset capitalization in the // system, claim COMP accrued to this contract. This COMP is // a result of holding all the cToken deposits from users. // We claim COMP via Compound's Comptroller contract. COMPTROLLER.claimComp(address(this)); // Obtain contract's balance of COMP uint96 myCompBalance = COMP_TOKEN.balanceOf(address(this)).safe96("IFund: amount exceeds 96 bits."); // Store the updated value as the checkpointed COMP yield owed // for this interval dsInsuranceFund.compYields = InsuranceFundDefs.ExternalYieldCheckpoint({ accrued: myCompBalance, totalNormalizedCap: normalizedCapCheckpointSumCompound }); } // Set other rewards checkpoint block to current block dsInsuranceFund.otherRewardsCheckpointBlock = block.number; // Issue DDX reward to trader's on-chain DDX wallet as an // incentive to users calling this function LibTraderInternal.issueDDXReward(dsInsuranceFund.advanceIntervalReward, msg.sender); emit AdvancedOtherRewards(msg.sender, dsInsuranceFund.advanceIntervalReward); } /** * @notice This function gets some high level insurance mining * details. * @return The interval length (blocks) for other rewards * claiming checkpoints (i.e. COMP and extra aTokens). * @return Current insurance mine withdrawal factor. * @return DDX reward for advancing interval. * @return Total global insurance mined amount in DDX. * @return Current insurance mine rate per block. * @return Insurance mining final block number. * @return DDX market state used for continuous DDX payouts. * @return Supported collateral names supported. */ function getInsuranceMineInfo() external view returns ( uint32, uint32, uint96, uint96, uint96, uint256, InsuranceFundDefs.DDXMarketState memory, bytes32[] memory ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return ( dsInsuranceFund.interval, dsInsuranceFund.withdrawalFactor, dsInsuranceFund.advanceIntervalReward, dsInsuranceFund.minedAmount, dsInsuranceFund.mineRatePerBlock, dsInsuranceFund.miningFinalBlockNumber, dsInsuranceFund.ddxMarketState, dsInsuranceFund.collateralNames ); } /** * @notice This function gets the current claimant state for a user. * @param _claimant Claimant address. * @return Claimant state. */ function getDDXClaimantState(address _claimant) external view returns (InsuranceFundDefs.DDXClaimantState memory) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return dsInsuranceFund.ddxClaimantState[_claimant]; } /** * @notice This function gets a supported collateral type's data, * including collateral's token addresses, collateral * flavor/type, current cap and withdrawal amounts, the * latest checkpointed cap, and exchange rate (for cTokens). * An interface for the DerivaDEX Insurance Fund token * corresponding to this collateral is also maintained. * @param _collateralName Name of collateral. * @return Stake collateral. */ function getStakeCollateralByCollateralName(bytes32 _collateralName) external view returns (InsuranceFundDefs.StakeCollateral memory) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return dsInsuranceFund.stakeCollaterals[_collateralName]; } /** * @notice This function gets unclaimed DDX rewards for a claimant. * @param _claimant Claimant address. * @return Unclaimed DDX rewards. */ function getUnclaimedDDXRewards(address _claimant) external view returns (uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Number of blocks that have elapsed from the last protocol // interaction resulting in DDX accrual. If insurance mining // has ended, we use this as the reference point, so deltaBlocks // will be 0 from the second time onwards. uint256 deltaBlocks = Math.min(block.number, dsInsuranceFund.miningFinalBlockNumber).sub(dsInsuranceFund.ddxMarketState.block); // Save off last index value uint256 index = dsInsuranceFund.ddxMarketState.index; // If number of blocks elapsed and mine rate per block are // non-zero if (deltaBlocks > 0 && dsInsuranceFund.mineRatePerBlock > 0) { // Maintain a running total of USDT-normalized claim tokens // (i.e. 1e6 multiplier) uint256 claimTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claim tokens count with // the current total supply claimTokens = claimTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits") ) ); } // Compute DDX accrued during the time elapsed and the // number of tokens accrued per claim token outstanding uint256 ddxAccrued = deltaBlocks.mul(dsInsuranceFund.mineRatePerBlock); uint256 ratio = claimTokens > 0 ? ddxAccrued.mul(1e36).div(claimTokens) : 0; // Increment the index index = index.add(ratio); } // Obtain the most recent claimant index uint256 ddxClaimantIndex = dsInsuranceFund.ddxClaimantState[_claimant].index; // If the claimant index is 0, i.e. it's the user's first time // interacting with the protocol, initialize it to this starting // value if ((ddxClaimantIndex == 0) && (index > 0)) { ddxClaimantIndex = 1e36; } // Maintain a running total of USDT-normalized claimant tokens // (i.e. 1e6 multiplier) uint256 claimantTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claimant tokens count with // the current balance claimantTokens = claimantTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.balanceOf(_claimant).safe96("IFund: exceeds 96 bits") ) ); } // Compute the unclaimed DDX based on the number of claimant // tokens and the difference between the user's index and the // claimant index computed above return claimantTokens.mul(index.sub(ddxClaimantIndex)).div(1e36).safe96("IFund: exceeds 96 bits"); } /** * @notice Calculate DDX accrued by a claimant and possibly transfer * it to them. * @param _claimant The address of the claimant. */ function claimDDXFromInsuranceMining(address _claimant) public { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Update the DDX Market State in order to determine the amount of // rewards that should be paid to the claimant. updateDDXMarketState(dsInsuranceFund); // Obtain the most recent claimant index uint256 ddxClaimantIndex = dsInsuranceFund.ddxClaimantState[_claimant].index; dsInsuranceFund.ddxClaimantState[_claimant].index = dsInsuranceFund.ddxMarketState.index; // If the claimant index is 0, i.e. it's the user's first time // interacting with the protocol, initialize it to this starting // value if ((ddxClaimantIndex == 0) && (dsInsuranceFund.ddxMarketState.index > 0)) { ddxClaimantIndex = 1e36; } // Compute the difference between the latest DDX market state // index and the claimant's index uint256 deltaIndex = uint256(dsInsuranceFund.ddxMarketState.index).sub(ddxClaimantIndex); // Maintain a running total of USDT-normalized claimant tokens // (i.e. 1e6 multiplier) uint256 claimantTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claimant tokens count with // the current balance claimantTokens = claimantTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.balanceOf(_claimant).safe96("IFund: exceeds 96 bits") ) ); } // Compute the claimed DDX based on the number of claimant // tokens and the difference between the user's index and the // claimant index computed above uint96 claimantDelta = claimantTokens.mul(deltaIndex).div(1e36).safe96("IFund: exceeds 96 bits"); if (claimantDelta != 0) { // Adjust insurance mined amount dsInsuranceFund.minedAmount = dsInsuranceFund.minedAmount.add96(claimantDelta); // Increment the insurance mined claimed DDX for claimant dsInsuranceFund.ddxClaimantState[_claimant].claimedDDX = dsInsuranceFund.ddxClaimantState[_claimant] .claimedDDX .add96(claimantDelta); // Mint the DDX governance/operational token claimed reward // from the proxy contract to the participant LibTraderInternal.issueDDXReward(claimantDelta, _claimant); } // Check if COMP or aTokens have not already been claimed if (dsInsuranceFund.stakerToOtherRewardsClaims[_claimant] < dsInsuranceFund.otherRewardsCheckpointBlock) { // Record the current block number preventing a user from // reclaiming the COMP reward unfairly dsInsuranceFund.stakerToOtherRewardsClaims[_claimant] = block.number; // Claim COMP and extra aTokens claimOtherRewardsFromInsuranceMining(_claimant); } emit InsuranceMineRewardsClaimed(_claimant, claimantDelta); } /** * @notice Get USDT-normalized collateral token amount. * @param _collateralName The collateral name. * @param _value The number of tokens. */ function getNormalizedCollateralValue(bytes32 _collateralName, uint96 _value) public view returns (uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; return (stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound) ? getUnderlyingTokenAmountForVanilla(_value, stakeCollateral.collateralToken) : getUnderlyingTokenAmountForCompound( _value, ICToken(stakeCollateral.collateralToken).exchangeRateStored() ); } /** * @notice This function gets a participant's current * USD-normalized/denominated stake and global * USD-normalized/denominated stake across all supported * collateral types. * @param _staker Participant's address. * @return Current USD redemption value of DIFund tokens staked. * @return Current USD global cap. */ function getCurrentTotalStakes(address _staker) public view returns (uint96, uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Maintain running totals uint96 normalizedStakerStakeSum; uint96 normalizedGlobalCapSum; // Loop through each supported collateral for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { (, , uint96 normalizedStakerStake, uint96 normalizedGlobalCap) = getCurrentStakeByCollateralNameAndStaker(dsInsuranceFund.collateralNames[i], _staker); normalizedStakerStakeSum = normalizedStakerStakeSum.add96(normalizedStakerStake); normalizedGlobalCapSum = normalizedGlobalCapSum.add96(normalizedGlobalCap); } return (normalizedStakerStakeSum, normalizedGlobalCapSum); } /** * @notice This function gets a participant's current DIFund token * holdings and global DIFund token holdings for a * collateral type and staker, in addition to the * USD-normalized collateral in the system and the * redemption value for the staker. * @param _collateralName Name of collateral. * @param _staker Participant's address. * @return DIFund tokens for staker. * @return DIFund tokens globally. * @return Redemption value for staker (USD-denominated). * @return Underlying collateral (USD-denominated) in staking system. */ function getCurrentStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker) public view returns ( uint96, uint96, uint96, uint96 ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Get DIFund tokens for staker uint96 stakerStake = stakeCollateral.diFundToken.balanceOf(_staker).safe96("IFund: exceeds 96 bits."); // Get DIFund tokens globally uint96 globalCap = stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits."); // Compute global USD-denominated stake capitalization. This is // is straightforward for non-Compound assets, but requires // exchange rate conversion for Compound assets. uint96 normalizedGlobalCap = (stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound) ? getUnderlyingTokenAmountForVanilla(stakeCollateral.cap, stakeCollateral.collateralToken) : getUnderlyingTokenAmountForCompound( stakeCollateral.cap, ICToken(stakeCollateral.collateralToken).exchangeRateStored() ); // Compute the redemption value (USD-normalized) for staker // given DIFund token holdings uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0; return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap); } /** * @notice This function gets a participant's DIFund token * holdings and global DIFund token holdings for Compound * and Aave tokens for a collateral type and staker as of * the checkpointed block, in addition to the * USD-normalized collateral in the system and the * redemption value for the staker. * @param _collateralName Name of collateral. * @param _staker Participant's address. * @return DIFund tokens for staker. * @return DIFund tokens globally. * @return Redemption value for staker (USD-denominated). * @return Underlying collateral (USD-denominated) in staking system. */ function getOtherRewardsStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker) public view returns ( uint96, uint96, uint96, uint96 ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Get DIFund tokens for staker as of the checkpointed block uint96 stakerStake = stakeCollateral.diFundToken.getPriorValues(_staker, dsInsuranceFund.otherRewardsCheckpointBlock.sub(1)); // Get DIFund tokens globally as of the checkpointed block uint96 globalCap = stakeCollateral.diFundToken.getTotalPriorValues(dsInsuranceFund.otherRewardsCheckpointBlock.sub(1)); // If Aave, don't worry about the normalized values since 1-1 if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { return (stakerStake, globalCap, 0, 0); } // Compute global USD-denominated stake capitalization. This is // is straightforward for non-Compound assets, but requires // exchange rate conversion for Compound assets. uint96 normalizedGlobalCap = getUnderlyingTokenAmountForCompound(stakeCollateral.checkpointCap, stakeCollateral.exchangeRate); // Compute the redemption value (USD-normalized) for staker // given DIFund token holdings uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0; return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap); } /** * @notice Claim other rewards (COMP and aTokens) for a claimant. * @param _claimant The address for the claimant. */ function claimOtherRewardsFromInsuranceMining(address _claimant) internal { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Maintain a running total of COMP to be claimed from // insurance mining contract as a by product of cToken deposits uint96 compClaimedAmountSum; // Loop through collateral names that are supported for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Vanilla) { // If collateral is of Vanilla flavor, we just // continue... continue; } // Compute the DIFund token holdings and the normalized, // USDT-normalized collateral value for the user (uint96 collateralStaker, uint96 collateralTotal, uint96 normalizedCollateralStaker, ) = getOtherRewardsStakeByCollateralNameAndStaker(dsInsuranceFund.collateralNames[i], _claimant); if ((collateralTotal == 0) || (collateralStaker == 0)) { // If there are no DIFund tokens, there is no reason to // claim rewards, so we continue... continue; } if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { // Aave has a special circumstance, where every // aToken results in additional aTokens accruing // to the holder's wallet. In this case, this is // the DerivaDEX contract. Therefore, we must // appropriately distribute the extra aTokens to // users claiming DDX for their aToken deposits. transferTokensAave(_claimant, dsInsuranceFund.collateralNames[i], collateralStaker, collateralTotal); } else if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Compound) { // If collateral is of type Compound, determine the // COMP claimant is entitled to based on the COMP // yield for this interval, the claimant's // DIFundToken share, and the USD-denominated // share for this market. uint96 compClaimedAmount = dsInsuranceFund.compYields.accrued.proportion96( normalizedCollateralStaker, dsInsuranceFund.compYields.totalNormalizedCap ); // Increment the COMP claimed sum to be paid out // later compClaimedAmountSum = compClaimedAmountSum.add96(compClaimedAmount); } } // Distribute any COMP to be shared with the user if (compClaimedAmountSum > 0) { transferTokensCompound(_claimant, compClaimedAmountSum); } } /** * @notice This function transfers extra Aave aTokens to claimant. */ function transferTokensAave( address _claimant, bytes32 _collateralName, uint96 _aaveStaker, uint96 _aaveTotal ) internal { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; uint96 aTokenClaimedAmount = dsInsuranceFund.aTokenYields[_collateralName].accrued.proportion96(_aaveStaker, _aaveTotal); // Continues in scenarios token transfer fails (such as // transferring 0 tokens) try IAToken(stakeCollateral.collateralToken).transfer(_claimant, aTokenClaimedAmount) {} catch {} } /** * @notice This function transfers COMP tokens from the contract to * a recipient. * @param _amount Amount of COMP to receive. */ function transferTokensCompound(address _claimant, uint96 _amount) internal { // Continues in scenarios token transfer fails (such as // transferring 0 tokens) try COMP_TOKEN.transfer(_claimant, _amount) {} catch {} } /** * @notice Updates the DDX market state to ensure that claimants can receive * their earned DDX rewards. */ function updateDDXMarketState(LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund) internal { // Number of blocks that have elapsed from the last protocol // interaction resulting in DDX accrual. If insurance mining // has ended, we use this as the reference point, so deltaBlocks // will be 0 from the second time onwards. uint256 endBlock = Math.min(block.number, dsInsuranceFund.miningFinalBlockNumber); uint256 deltaBlocks = endBlock.sub(dsInsuranceFund.ddxMarketState.block); // If number of blocks elapsed and mine rate per block are // non-zero if (deltaBlocks > 0 && dsInsuranceFund.mineRatePerBlock > 0) { // Maintain a running total of USDT-normalized claim tokens // (i.e. 1e6 multiplier) uint256 claimTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claim tokens count with // the current total supply claimTokens = claimTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits") ) ); } // Compute DDX accrued during the time elapsed and the // number of tokens accrued per claim token outstanding uint256 ddxAccrued = deltaBlocks.mul(dsInsuranceFund.mineRatePerBlock); uint256 ratio = claimTokens > 0 ? ddxAccrued.mul(1e36).div(claimTokens) : 0; // Increment the index uint256 index = uint256(dsInsuranceFund.ddxMarketState.index).add(ratio); // Update the claim ddx market state with the new index // and block dsInsuranceFund.ddxMarketState.index = index.safe224("IFund: exceeds 224 bits"); dsInsuranceFund.ddxMarketState.block = endBlock.safe32("IFund: exceeds 32 bits"); } else if (deltaBlocks > 0) { dsInsuranceFund.ddxMarketState.block = endBlock.safe32("IFund: exceeds 32 bits"); } } /** * @notice This function checks if a collateral token is present. * @param _collateralToken Collateral token address. * @return Whether collateral token is present or not. */ function isCollateralTokenPresent(address _collateralToken) internal view returns (bool) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Return true if collateral token has been added if ( dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]].collateralToken == _collateralToken ) { return true; } } // Collateral token has not been added, return false return false; } /** * @notice This function computes the underlying token amount for a * vanilla token. * @param _vanillaAmount Number of vanilla tokens. * @param _collateral Address of vanilla collateral. * @return Underlying token amount. */ function getUnderlyingTokenAmountForVanilla(uint96 _vanillaAmount, address _collateral) internal view returns (uint96) { uint256 vanillaDecimals = uint256(IERCCustom(_collateral).decimals()); if (vanillaDecimals >= 6) { return uint256(_vanillaAmount).div(10**(vanillaDecimals.sub(6))).safe96("IFund: amount exceeds 96 bits"); } return uint256(_vanillaAmount).mul(10**(uint256(6).sub(vanillaDecimals))).safe96("IFund: amount exceeds 96 bits"); } /** * @notice This function computes the underlying token amount for a * cToken amount by computing the current exchange rate. * @param _cTokenAmount Number of cTokens. * @param _exchangeRate Exchange rate derived from Compound. * @return Underlying token amount. */ function getUnderlyingTokenAmountForCompound(uint96 _cTokenAmount, uint256 _exchangeRate) internal pure returns (uint96) { return _exchangeRate.mul(_cTokenAmount).div(1e18).safe96("IFund: amount exceeds 96 bits."); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add32(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub32(uint32 a, uint32 b) internal pure returns (uint32) { return sub32(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 sub32( uint32 a, uint32 b, string memory errorMessage ) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { SafeMath96 } from "./SafeMath96.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library MathHelpers { using SafeMath96 for uint96; using SafeMath for uint256; function proportion96( uint96 a, uint256 b, uint256 c ) internal pure returns (uint96) { return safe96(uint256(a).mul(b).div(c), "Amount exceeds 96 bits"); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } /** * @dev Returns the largest of two numbers. */ function clamp96( uint96 a, uint256 b, uint256 c ) internal pure returns (uint96) { return safe96(Math.min(Math.max(a, b), c), "Amount exceeds 96 bits"); } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDIFundToken } from "../../tokens/interfaces/IDIFundToken.sol"; /** * @title InsuranceFundDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * the insurance fund. */ library InsuranceFundDefs { // DDX market state maintaining claim index and last updated block struct DDXMarketState { uint224 index; uint32 block; } // DDX claimant state maintaining claim index and claimed DDX struct DDXClaimantState { uint256 index; uint96 claimedDDX; } // Supported collateral struct consisting of the collateral's token // addresses, collateral flavor/type, current cap and withdrawal // amounts, the latest checkpointed cap, and exchange rate (for // cTokens). An interface for the DerivaDEX Insurance Fund token // corresponding to this collateral is also maintained. struct StakeCollateral { address underlyingToken; address collateralToken; IDIFundToken diFundToken; uint96 cap; uint96 withdrawalFeeCap; uint96 checkpointCap; uint96 exchangeRate; Flavor flavor; } // Contains the yield accrued and the total normalized cap. // Total normalized cap is maintained for Compound flavors so COMP // distribution can be paid out properly struct ExternalYieldCheckpoint { uint96 accrued; uint96 totalNormalizedCap; } // Type of collateral enum Flavor { Vanilla, Compound, Aave } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { InsuranceFundDefs } from "../libs/defs/InsuranceFundDefs.sol"; import { IDIFundTokenFactory } from "../tokens/interfaces/IDIFundTokenFactory.sol"; library LibDiamondStorageInsuranceFund { struct DiamondStorageInsuranceFund { // List of supported collateral names bytes32[] collateralNames; // Collateral name to stake collateral struct mapping(bytes32 => InsuranceFundDefs.StakeCollateral) stakeCollaterals; mapping(address => InsuranceFundDefs.DDXClaimantState) ddxClaimantState; // aToken name to yield checkpoints mapping(bytes32 => InsuranceFundDefs.ExternalYieldCheckpoint) aTokenYields; mapping(address => uint256) stakerToOtherRewardsClaims; // Interval to COMP yield checkpoint InsuranceFundDefs.ExternalYieldCheckpoint compYields; // Set the interval for other rewards claiming checkpoints // (i.e. COMP and aTokens that accrue to the contract) // (e.g. 40320 ~ 1 week = 7 * 24 * 60 * 60 / 15 blocks) uint32 interval; // Current insurance mining withdrawal factor uint32 withdrawalFactor; // DDX to be issued per block as insurance mining reward uint96 mineRatePerBlock; // Incentive to advance the insurance mining interval // (e.g. 100e18 = 100 DDX) uint96 advanceIntervalReward; // Total DDX insurance mined uint96 minedAmount; // Insurance fund capitalization due to liquidations and fees uint96 liqAndFeeCapitalization; // Checkpoint block for other rewards uint256 otherRewardsCheckpointBlock; // Insurance mining final block number uint256 miningFinalBlockNumber; InsuranceFundDefs.DDXMarketState ddxMarketState; IDIFundTokenFactory diFundTokenFactory; } bytes32 constant DIAMOND_STORAGE_POSITION_INSURANCE_FUND = keccak256("diamond.standard.diamond.storage.DerivaDEX.InsuranceFund"); function diamondStorageInsuranceFund() internal pure returns (DiamondStorageInsuranceFund storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_INSURANCE_FUND; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; library LibDiamondStoragePause { struct DiamondStoragePause { bool isPaused; } bytes32 constant DIAMOND_STORAGE_POSITION_PAUSE = keccak256("diamond.standard.diamond.storage.DerivaDEX.Pause"); function diamondStoragePause() internal pure returns (DiamondStoragePause storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_PAUSE; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAToken { function decimals() external returns (uint256); function transfer(address _recipient, uint256 _amount) external; function balanceOf(address _user) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; abstract contract IComptroller { struct CompMarketState { uint224 index; uint32 block; } /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; // solhint-disable-line const-name-snakecase // @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint256)) public compSupplierIndex; /// @notice The portion of compRate that each market currently receives mapping(address => uint256) public compSpeeds; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint256) public compAccrued; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external virtual returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external virtual; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external virtual returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external virtual; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external virtual returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external virtual; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external virtual returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external virtual; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external virtual returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external virtual; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external virtual returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external virtual; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external virtual returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external virtual; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external virtual returns (uint256, uint256); function claimComp(address holder) public virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ICToken { function accrueInterest() external returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function balanceOfUnderlying(address owner) external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrowsCurrent() external returns (uint256); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function decimals() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function getCash() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title IDIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ interface IDIFundToken { function transfer(address _recipient, uint256 _amount) external returns (bool); function mint(address _recipient, uint256 _amount) external; function burnFrom(address _account, uint256 _amount) external; function delegate(address _delegatee) external; function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool); function approve(address _spender, uint256 _amount) external returns (bool); function getPriorValues(address account, uint256 blockNumber) external view returns (uint96); function getTotalPriorValues(uint256 blockNumber) external view returns (uint96); function balanceOf(address _account) external view returns (uint256); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { DIFundToken } from "../DIFundToken.sol"; /** * @title DIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the token contract for tokenized DerivaDEX insurance * fund positions. It implements the ERC-20 standard, with * additional functionality around snapshotting user and global * balances. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DIFundToken makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances and allowances, this * allows us to more efficiently pack data together, thereby * resulting in cheaper transactions. */ interface IDIFundTokenFactory { function createNewDIFundToken( string calldata _name, string calldata _symbol, uint8 _decimals ) external returns (address); function diFundTokens(uint256 index) external returns (DIFundToken); function issuer() external view returns (address); function getDIFundTokens() external view returns (DIFundToken[] memory); function getDIFundTokensLength() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; import { IInsuranceFund } from "../facets/interfaces/IInsuranceFund.sol"; /** * @title DIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the token contract for tokenized DerivaDEX insurance * fund positions. It implements the ERC-20 standard, with * additional functionality around snapshotting user and global * balances. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DIFundToken makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances and allowances, this * allows us to more efficiently pack data together, thereby * resulting in cheaper transactions. */ contract DIFundToken { using SafeMath96 for uint96; using SafeMath for uint256; using LibBytes for bytes; uint256 internal _totalSupply; string private _name; string private _symbol; string private _version; uint8 private _decimals; /// @notice Address authorized to issue/mint DDX tokens address public issuer; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; /// @notice A checkpoint for marking vote count from given block struct Checkpoint { uint32 id; uint96 values; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; mapping(uint256 => Checkpoint) totalCheckpoints; uint256 numTotalCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice Emitted when a user account's balance changes event ValuesChanged(address indexed user, uint96 previousValue, uint96 newValue); /// @notice Emitted when a user account's balance changes event TotalValuesChanged(uint96 previousValue, uint96 newValue); /// @notice Emitted when transfer takes place event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice Emitted when approval takes place event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new DIFundToken token */ constructor( string memory name, string memory symbol, uint8 decimals, address _issuer ) public { _name = name; _symbol = symbol; _decimals = decimals; _version = "1"; // Set issuer to deploying address issuer = _issuer; } /** * @notice Returns the name of the token. * @return Name of the token. */ function name() public view returns (string memory) { return _name; } /** * @notice Returns the symbol of the token. * @return Symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. * @return Number of decimals. */ function decimals() public view returns (uint8) { return _decimals; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param _spender The address of the account which may transfer tokens * @param _amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address _spender, uint256 _amount) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Set allowance allowances[msg.sender][_spender] = amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * Emits an {Approval} event indicating the updated allowance. * Requirements: * - `spender` cannot be the zero address. */ function increaseAllowance(address _spender, uint256 _addedValue) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_addedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_addedValue, "DIFT: amount exceeds 96 bits."); } // Increase allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * Emits an {Approval} event indicating the updated allowance. * Requirements: * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_subtractedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_subtractedValue, "DIFT: amount exceeds 96 bits."); } // Decrease allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96( amount, "DIFT: decreased allowance below zero." ); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } /** * @notice Get the number of tokens held by the `account` * @param _account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address _account) external view returns (uint256) { return balances[_account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address _recipient, uint256 _amount) external returns (bool) { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Claim DDX rewards on behalf of the sender IInsuranceFund(issuer).claimDDXFromInsuranceMining(msg.sender); // Claim DDX rewards on behalf of the recipient IInsuranceFund(issuer).claimDDXFromInsuranceMining(_recipient); // Transfer tokens from sender to recipient _transferTokens(msg.sender, _recipient, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param _sender The address of the source account * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool) { uint96 spenderAllowance = allowances[_sender][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } if (msg.sender != _sender && spenderAllowance != uint96(-1)) { // Tx sender is not the same as transfer sender and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount); allowances[_sender][msg.sender] = newAllowance; emit Approval(_sender, msg.sender, newAllowance); } // Claim DDX rewards on behalf of the sender IInsuranceFund(issuer).claimDDXFromInsuranceMining(_sender); // Claim DDX rewards on behalf of the recipient IInsuranceFund(issuer).claimDDXFromInsuranceMining(_recipient); // Transfer tokens from sender to recipient _transferTokens(_sender, _recipient, amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function mint(address _recipient, uint256 _amount) external { require(msg.sender == issuer, "DIFT: unauthorized mint."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Mint tokens to recipient _transferTokensMint(_recipient, amount); } /** * @dev Creates `amount` tokens and assigns them to `account`, decreasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function burn(uint256 _amount) external { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Burn tokens from sender _transferTokensBurn(msg.sender, amount); } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function burnFrom(address _account, uint256 _amount) external { uint96 spenderAllowance = allowances[_account][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } if (msg.sender != _account && spenderAllowance != uint96(-1) && msg.sender != issuer) { // Tx sender is not the same as burn account and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount, "DIFT: burn amount exceeds allowance."); allowances[_account][msg.sender] = newAllowance; emit Approval(_account, msg.sender, newAllowance); } // Burn tokens from account _transferTokensBurn(_account, amount); } /** * @notice Permits allowance from signatory to `spender` * @param _spender The spender being approved * @param _value The value being approved * @param _nonce The contract state required to match the signature * @param _expiry The time at which to expire the signature * @param _signature Signature */ function permit( address _spender, uint256 _value, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(_name, _version, getChainId(), address(this)); bytes32 permitHash = LibPermit.getPermitHash( LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } address recovered = ecrecover(permitHash, v, r, s); require(recovered != address(0), "DIFT: invalid signature."); require(_nonce == nonces[recovered]++, "DIFT: invalid nonce."); require(block.timestamp <= _expiry, "DIFT: signature expired."); // Convert amount to uint96 uint96 amount; if (_value == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_value, "DIFT: amount exceeds 96 bits."); } // Set allowance allowances[recovered][_spender] = amount; emit Approval(recovered, _spender, _value); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param _account The address of the account holding the funds * @param _spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address _account, address _spender) external view returns (uint256) { return allowances[_account][_spender]; } /** * @notice Get the total max supply of DDX tokens * @return The total max supply of DDX */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @notice Determine the prior number of values 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 values the account had as of the given block */ function getPriorValues(address _account, uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DIFT: block not yet determined."); uint256 numCheckpointsAccount = numCheckpoints[_account]; if (numCheckpointsAccount == 0) { return 0; } // First check most recent balance if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) { return checkpoints[_account][numCheckpointsAccount - 1].values; } // Next check implicit zero balance if (checkpoints[_account][0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings uint256 lower = 0; uint256 upper = numCheckpointsAccount - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[_account][center]; if (cp.id == _blockNumber) { return cp.values; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[_account][lower].values; } /** * @notice Determine the prior number of values 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 _blockNumber The block number to get the vote balance at * @return The number of values the account had as of the given block */ function getTotalPriorValues(uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DIFT: block not yet determined."); if (numTotalCheckpoints == 0) { return 0; } // First check most recent balance if (totalCheckpoints[numTotalCheckpoints - 1].id <= _blockNumber) { return totalCheckpoints[numTotalCheckpoints - 1].values; } // Next check implicit zero balance if (totalCheckpoints[0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings // leading to a measure of voting power uint256 lower = 0; uint256 upper = numTotalCheckpoints - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = totalCheckpoints[center]; if (cp.id == _blockNumber) { return cp.values; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return totalCheckpoints[lower].values; } function _transferTokens( address _spender, address _recipient, uint96 _amount ) internal { require(_spender != address(0), "DIFT: cannot transfer from the zero address."); require(_recipient != address(0), "DIFT: cannot transfer to the zero address."); // Reduce spender's balance and increase recipient balance balances[_spender] = balances[_spender].sub96(_amount); balances[_recipient] = balances[_recipient].add96(_amount); emit Transfer(_spender, _recipient, _amount); // Move values from spender to recipient _moveTokens(_spender, _recipient, _amount); } function _transferTokensMint(address _recipient, uint96 _amount) internal { require(_recipient != address(0), "DIFT: cannot transfer to the zero address."); // Add to recipient's balance balances[_recipient] = balances[_recipient].add96(_amount); _totalSupply = _totalSupply.add(_amount); emit Transfer(address(0), _recipient, _amount); // Add value to recipient's checkpoint _moveTokens(address(0), _recipient, _amount); _writeTotalCheckpoint(_amount, true); } function _transferTokensBurn(address _spender, uint96 _amount) internal { require(_spender != address(0), "DIFT: cannot transfer from the zero address."); // Reduce the spender/burner's balance balances[_spender] = balances[_spender].sub96(_amount, "DIFT: not enough balance to burn."); // Reduce the circulating supply _totalSupply = _totalSupply.sub(_amount); emit Transfer(_spender, address(0), _amount); // Reduce value from spender's checkpoint _moveTokens(_spender, address(0), _amount); _writeTotalCheckpoint(_amount, false); } function _moveTokens( address _initUser, address _finUser, uint96 _amount ) internal { if (_initUser != _finUser && _amount > 0) { // Initial user address is different than final // user address and nonzero number of values moved if (_initUser != address(0)) { uint256 initUserNum = numCheckpoints[_initUser]; // Retrieve and compute the old and new initial user // address' values uint96 initUserOld = initUserNum > 0 ? checkpoints[_initUser][initUserNum - 1].values : 0; uint96 initUserNew = initUserOld.sub96(_amount); _writeCheckpoint(_initUser, initUserOld, initUserNew); } if (_finUser != address(0)) { uint256 finUserNum = numCheckpoints[_finUser]; // Retrieve and compute the old and new final user // address' values uint96 finUserOld = finUserNum > 0 ? checkpoints[_finUser][finUserNum - 1].values : 0; uint96 finUserNew = finUserOld.add96(_amount); _writeCheckpoint(_finUser, finUserOld, finUserNew); } } } function _writeCheckpoint( address _user, uint96 _oldValues, uint96 _newValues ) internal { uint32 blockNumber = safe32(block.number, "DIFT: exceeds 32 bits."); uint256 userNum = numCheckpoints[_user]; if (userNum > 0 && checkpoints[_user][userNum - 1].id == blockNumber) { // If latest checkpoint is current block, edit in place checkpoints[_user][userNum - 1].values = _newValues; } else { // Create a new id, value pair checkpoints[_user][userNum] = Checkpoint({ id: blockNumber, values: _newValues }); numCheckpoints[_user] = userNum.add(1); } emit ValuesChanged(_user, _oldValues, _newValues); } function _writeTotalCheckpoint(uint96 _amount, bool increase) internal { if (_amount > 0) { uint32 blockNumber = safe32(block.number, "DIFT: exceeds 32 bits."); uint96 oldValues = numTotalCheckpoints > 0 ? totalCheckpoints[numTotalCheckpoints - 1].values : 0; uint96 newValues = increase ? oldValues.add96(_amount) : oldValues.sub96(_amount); if (numTotalCheckpoints > 0 && totalCheckpoints[numTotalCheckpoints - 1].id == block.number) { // If latest checkpoint is current block, edit in place totalCheckpoints[numTotalCheckpoints - 1].values = newValues; } else { // Create a new id, value pair totalCheckpoints[numTotalCheckpoints].id = blockNumber; totalCheckpoints[numTotalCheckpoints].values = newValues; numTotalCheckpoints = numTotalCheckpoints.add(1); } emit TotalValuesChanged(oldValues, newValues); } } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for { } lt(source, sEnd) { } { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for { } slt(dest, dEnd) { } { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(from <= to, "FROM_LESS_THAN_TO_REQUIRED"); require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED"); // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy(result.contentAddress(), b.contentAddress() + from, result.length); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(from <= to, "FROM_LESS_THAN_TO_REQUIRED"); require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED"); // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { require(b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED"); // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Pops the last 20 bytes off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The 20 byte address that was popped off. function popLast20Bytes(bytes memory b) internal pure returns (address result) { require(b.length >= 20, "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"); // Store last 20 bytes. result = readAddress(b, b.length - 20); assembly { // Subtract 20 from byte array length. let newLen := sub(mload(b), 20) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return equal True if arrays are the same. False otherwise. function equals(bytes memory lhs, bytes memory rhs) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return result address from byte array. function readAddress(bytes memory b, uint256 index) internal pure returns (address result) { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return result bytes32 value from byte array. function readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) { require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return result uint256 value from byte array. function readUint256(bytes memory b, uint256 index) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return result bytes4 value from byte array. function readBytes4(bytes memory b, uint256 index) internal pure returns (bytes4 result) { require(b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"); // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads nested bytes from a specific position. /// @dev NOTE: the returned value overlaps with the input value. /// Both should be treated as immutable. /// @param b Byte array containing nested bytes. /// @param index Index of nested bytes. /// @return result Nested bytes. function readBytesWithLength(bytes memory b, uint256 index) internal pure returns (bytes memory result) { // Read length of nested bytes uint256 nestedBytesLength = readUint256(b, index); index += 32; // Assert length of <b> is valid, given // length of nested bytes require(b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"); // Return a pointer to the byte array as it exists inside `b` assembly { result := add(b, index) } return result; } /// @dev Inserts bytes at a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes to insert. function writeBytesWithLength( bytes memory b, uint256 index, bytes memory input ) internal pure { // Assert length of <b> is valid, given // length of input require( b.length >= index + 32 + input.length, // 32 bytes to store length "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Copy <input> into <b> memCopy( b.contentAddress() + index, input.rawAddress(), // includes length of <input> input.length + 32 // +32 bytes to store <input> length ); } /// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length. /// @param dest Byte array that will be overwritten with source bytes. /// @param source Byte array to copy onto dest bytes. function deepCopyBytes(bytes memory dest, bytes memory source) internal pure { uint256 sourceLen = source.length; // Dest length must be >= source length, or some bytes would not be copied. require(dest.length >= sourceLen, "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED"); memCopy(dest.contentAddress(), source.contentAddress(), sourceLen); } } // SPDX-License-Identifier: MIT /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 internal constant _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return result EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return result EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibPermit { struct Permit { address spender; // Spender uint256 value; // Value uint256 nonce; // Nonce uint256 expiry; // Expiry } // Hash for the EIP712 LibPermit Schema // bytes32 constant internal EIP712_PERMIT_SCHEMA_HASH = keccak256(abi.encodePacked( // "Permit(", // "address spender,", // "uint256 value,", // "uint256 nonce,", // "uint256 expiry", // ")" // )); bytes32 internal constant EIP712_PERMIT_SCHEMA_HASH = 0x58e19c95adc541dea238d3211d11e11e7def7d0c7fda4e10e0c45eb224ef2fb7; /// @dev Calculates Keccak-256 hash of the permit. /// @param permit The permit structure. /// @return permitHash Keccak-256 EIP712 hash of the permit. function getPermitHash(Permit memory permit, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 permitHash) { permitHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashPermit(permit)); return permitHash; } /// @dev Calculates EIP712 hash of the permit. /// @param permit The permit structure. /// @return result EIP712 hash of the permit. function hashPermit(Permit memory permit) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_PERMIT_SCHEMA_HASH; assembly { // Assert permit offset (this is an internal error that should never be triggered) if lt(permit, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(permit, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 160) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IInsuranceFund { function claimDDXFromInsuranceMining(address _claimant) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; import { DIFundToken } from "./DIFundToken.sol"; /** * @title DIFundTokenFactory * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ contract DIFundTokenFactory { DIFundToken[] public diFundTokens; address public issuer; /** * @notice Construct a new DDX token */ constructor(address _issuer) public { // Set issuer to deploying address issuer = _issuer; } function createNewDIFundToken( string calldata _name, string calldata _symbol, uint8 _decimals ) external returns (address) { require(msg.sender == issuer, "DIFTF: unauthorized."); DIFundToken diFundToken = new DIFundToken(_name, _symbol, _decimals, issuer); diFundTokens.push(diFundToken); return address(diFundToken); } function getDIFundTokens() external view returns (DIFundToken[] memory) { return diFundTokens; } function getDIFundTokensLength() external view returns (uint256) { return diFundTokens.length; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibDelegation } from "../libs/LibDelegation.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; /** * @title DDX * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ contract DDX { using SafeMath96 for uint96; using SafeMath for uint256; using LibBytes for bytes; /// @notice ERC20 token name for this token string public constant name = "DerivaDAO"; // solhint-disable-line const-name-snakecase /// @notice ERC20 token symbol for this token string public constant symbol = "DDX"; // solhint-disable-line const-name-snakecase /// @notice ERC20 token decimals for this token uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase /// @notice Version number for this token. Used for EIP712 hashing. string public constant version = "1"; // solhint-disable-line const-name-snakecase /// @notice Max number of tokens to be issued (100 million DDX) uint96 public constant MAX_SUPPLY = 100000000e18; /// @notice Total number of tokens in circulation (50 million DDX) uint96 public constant PRE_MINE_SUPPLY = 50000000e18; /// @notice Issued supply of tokens uint96 public issuedSupply; /// @notice Current total/circulating supply of tokens uint96 public totalSupply; /// @notice Whether ownership has been transferred to the DAO bool public ownershipTransferred; /// @notice Address authorized to issue/mint DDX tokens address public issuer; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking vote count from given block struct Checkpoint { uint32 id; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice Emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice Emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint96 previousBalance, uint96 newBalance); /// @notice Emitted when transfer takes place event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice Emitted when approval takes place event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new DDX token */ constructor() public { // Set issuer to deploying address issuer = msg.sender; // Issue pre-mine token supply to deploying address and // set the issued and circulating supplies to pre-mine amount _transferTokensMint(msg.sender, PRE_MINE_SUPPLY); } /** * @notice Transfer ownership of DDX token from the deploying * address to the DerivaDEX Proxy/DAO * @param _derivaDEXProxy DerivaDEX Proxy address */ function transferOwnershipToDerivaDEXProxy(address _derivaDEXProxy) external { // Ensure deploying address is calling this, destination is not // the zero address, and that ownership has never been // transferred thus far require(msg.sender == issuer, "DDX: unauthorized transfer of ownership."); require(_derivaDEXProxy != address(0), "DDX: transferring to zero address."); require(!ownershipTransferred, "DDX: ownership already transferred."); // Set ownership transferred boolean flag and the new authorized // issuer ownershipTransferred = true; issuer = _derivaDEXProxy; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param _spender The address of the account which may transfer tokens * @param _amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address _spender, uint256 _amount) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Set allowance allowances[msg.sender][_spender] = amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * Emits an {Approval} event indicating the updated allowance. * Requirements: * - `spender` cannot be the zero address. */ function increaseAllowance(address _spender, uint256 _addedValue) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_addedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_addedValue, "DDX: amount exceeds 96 bits."); } // Increase allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * Emits an {Approval} event indicating the updated allowance. * Requirements: * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_subtractedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_subtractedValue, "DDX: amount exceeds 96 bits."); } // Decrease allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96( amount, "DDX: decreased allowance below zero." ); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } /** * @notice Get the number of tokens held by the `account` * @param _account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address _account) external view returns (uint256) { return balances[_account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address _recipient, uint256 _amount) external returns (bool) { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Transfer tokens from sender to recipient _transferTokens(msg.sender, _recipient, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param _from The address of the source account * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address _from, address _recipient, uint256 _amount ) external returns (bool) { uint96 spenderAllowance = allowances[_from][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } if (msg.sender != _from && spenderAllowance != uint96(-1)) { // Tx sender is not the same as transfer sender and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount); allowances[_from][msg.sender] = newAllowance; emit Approval(_from, msg.sender, newAllowance); } // Transfer tokens from sender to recipient _transferTokens(_from, _recipient, amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function mint(address _recipient, uint256 _amount) external { require(msg.sender == issuer, "DDX: unauthorized mint."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Ensure the mint doesn't cause the issued supply to exceed // the total supply that could ever be issued require(issuedSupply.add96(amount) <= MAX_SUPPLY, "DDX: cap exceeded."); // Mint tokens to recipient _transferTokensMint(_recipient, amount); } /** * @dev Creates `amount` tokens and assigns them to `account`, decreasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function burn(uint256 _amount) external { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Burn tokens from sender _transferTokensBurn(msg.sender, amount); } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function burnFrom(address _account, uint256 _amount) external { uint96 spenderAllowance = allowances[_account][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } if (msg.sender != _account && spenderAllowance != uint96(-1)) { // Tx sender is not the same as burn account and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount, "DDX: burn amount exceeds allowance."); allowances[_account][msg.sender] = newAllowance; emit Approval(_account, msg.sender, newAllowance); } // Burn tokens from account _transferTokensBurn(_account, amount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param _delegatee The address to delegate votes to */ function delegate(address _delegatee) external { _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 _signature Signature */ function delegateBySig( address _delegatee, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 delegationHash = LibDelegation.getDelegationHash( LibDelegation.Delegation({ delegatee: _delegatee, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); address recovered = ecrecover(delegationHash, v, r, s); require(recovered != address(0), "DDX: invalid signature."); require(_nonce == nonces[recovered]++, "DDX: invalid nonce."); require(block.timestamp <= _expiry, "DDX: signature expired."); // Delegate votes from recovered address to delegatee _delegate(recovered, _delegatee); } /** * @notice Permits allowance from signatory to `spender` * @param _spender The spender being approved * @param _value The value being approved * @param _nonce The contract state required to match the signature * @param _expiry The time at which to expire the signature * @param _signature Signature */ function permit( address _spender, uint256 _value, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 permitHash = LibPermit.getPermitHash( LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } address recovered = ecrecover(permitHash, v, r, s); require(recovered != address(0), "DDX: invalid signature."); require(_nonce == nonces[recovered]++, "DDX: invalid nonce."); require(block.timestamp <= _expiry, "DDX: signature expired."); // Convert amount to uint96 uint96 amount; if (_value == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_value, "DDX: amount exceeds 96 bits."); } // Set allowance allowances[recovered][_spender] = amount; emit Approval(recovered, _spender, _value); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param _account The address of the account holding the funds * @param _spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address _account, address _spender) external view returns (uint256) { return allowances[_account][_spender]; } /** * @notice Gets the current votes balance. * @param _account The address to get votes balance. * @return The number of current votes. */ function getCurrentVotes(address _account) external view returns (uint96) { uint256 numCheckpointsAccount = numCheckpoints[_account]; return numCheckpointsAccount > 0 ? checkpoints[_account][numCheckpointsAccount - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param _account The address of the account to check * @param _blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address _account, uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DDX: block not yet determined."); uint256 numCheckpointsAccount = numCheckpoints[_account]; if (numCheckpointsAccount == 0) { return 0; } // First check most recent balance if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) { return checkpoints[_account][numCheckpointsAccount - 1].votes; } // Next check implicit zero balance if (checkpoints[_account][0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings // leading to a measure of voting power uint256 lower = 0; uint256 upper = numCheckpointsAccount - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[_account][center]; if (cp.id == _blockNumber) { return cp.votes; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[_account][lower].votes; } function _delegate(address _delegator, address _delegatee) internal { // Get the current address delegator has delegated address currentDelegate = _getDelegatee(_delegator); // Get delegator's DDX balance uint96 delegatorBalance = balances[_delegator]; // Set delegator's new delegatee address delegates[_delegator] = _delegatee; emit DelegateChanged(_delegator, currentDelegate, _delegatee); // Move votes from currently-delegated address to // new address _moveDelegates(currentDelegate, _delegatee, delegatorBalance); } function _transferTokens( address _spender, address _recipient, uint96 _amount ) internal { require(_spender != address(0), "DDX: cannot transfer from the zero address."); require(_recipient != address(0), "DDX: cannot transfer to the zero address."); // Reduce spender's balance and increase recipient balance balances[_spender] = balances[_spender].sub96(_amount); balances[_recipient] = balances[_recipient].add96(_amount); emit Transfer(_spender, _recipient, _amount); // Move votes from currently-delegated address to // recipient's delegated address _moveDelegates(_getDelegatee(_spender), _getDelegatee(_recipient), _amount); } function _transferTokensMint(address _recipient, uint96 _amount) internal { require(_recipient != address(0), "DDX: cannot transfer to the zero address."); // Add to recipient's balance balances[_recipient] = balances[_recipient].add96(_amount); // Increase the issued supply and circulating supply issuedSupply = issuedSupply.add96(_amount); totalSupply = totalSupply.add96(_amount); emit Transfer(address(0), _recipient, _amount); // Add delegates to recipient's delegated address _moveDelegates(address(0), _getDelegatee(_recipient), _amount); } function _transferTokensBurn(address _spender, uint96 _amount) internal { require(_spender != address(0), "DDX: cannot transfer from the zero address."); // Reduce the spender/burner's balance balances[_spender] = balances[_spender].sub96(_amount, "DDX: not enough balance to burn."); // Reduce the total supply totalSupply = totalSupply.sub96(_amount); emit Transfer(_spender, address(0), _amount); // MRedduce delegates from spender's delegated address _moveDelegates(_getDelegatee(_spender), address(0), _amount); } function _moveDelegates( address _initDel, address _finDel, uint96 _amount ) internal { if (_initDel != _finDel && _amount > 0) { // Initial delegated address is different than final // delegated address and nonzero number of votes moved if (_initDel != address(0)) { uint256 initDelNum = numCheckpoints[_initDel]; // Retrieve and compute the old and new initial delegate // address' votes uint96 initDelOld = initDelNum > 0 ? checkpoints[_initDel][initDelNum - 1].votes : 0; uint96 initDelNew = initDelOld.sub96(_amount); _writeCheckpoint(_initDel, initDelOld, initDelNew); } if (_finDel != address(0)) { uint256 finDelNum = numCheckpoints[_finDel]; // Retrieve and compute the old and new final delegate // address' votes uint96 finDelOld = finDelNum > 0 ? checkpoints[_finDel][finDelNum - 1].votes : 0; uint96 finDelNew = finDelOld.add96(_amount); _writeCheckpoint(_finDel, finDelOld, finDelNew); } } } function _writeCheckpoint( address _delegatee, uint96 _oldVotes, uint96 _newVotes ) internal { uint32 blockNumber = safe32(block.number, "DDX: exceeds 32 bits."); uint256 delNum = numCheckpoints[_delegatee]; if (delNum > 0 && checkpoints[_delegatee][delNum - 1].id == blockNumber) { // If latest checkpoint is current block, edit in place checkpoints[_delegatee][delNum - 1].votes = _newVotes; } else { // Create a new id, vote pair checkpoints[_delegatee][delNum] = Checkpoint({ id: blockNumber, votes: _newVotes }); numCheckpoints[_delegatee] = delNum.add(1); } emit DelegateVotesChanged(_delegatee, _oldVotes, _newVotes); } function _getDelegatee(address _delegator) internal view returns (address) { if (delegates[_delegator] == address(0)) { return _delegator; } return delegates[_delegator]; } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibDelegation { struct Delegation { address delegatee; // Delegatee uint256 nonce; // Nonce uint256 expiry; // Expiry } // Hash for the EIP712 OrderParams Schema // bytes32 constant internal EIP712_DELEGATION_SCHEMA_HASH = keccak256(abi.encodePacked( // "Delegation(", // "address delegatee,", // "uint256 nonce,", // "uint256 expiry", // ")" // )); bytes32 internal constant EIP712_DELEGATION_SCHEMA_HASH = 0xe48329057bfd03d55e49b547132e39cffd9c1820ad7b9d4c5307691425d15adf; /// @dev Calculates Keccak-256 hash of the delegation. /// @param delegation The delegation structure. /// @return delegationHash Keccak-256 EIP712 hash of the delegation. function getDelegationHash(Delegation memory delegation, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 delegationHash) { delegationHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashDelegation(delegation)); return delegationHash; } /// @dev Calculates EIP712 hash of the delegation. /// @param delegation The delegation structure. /// @return result EIP712 hash of the delegation. function hashDelegation(Delegation memory delegation) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_DELEGATION_SCHEMA_HASH; assembly { // Assert delegation offset (this is an internal error that should never be triggered) if lt(delegation, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(delegation, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 128) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibVoteCast { struct VoteCast { uint128 proposalId; // Proposal ID bool support; // Support } // Hash for the EIP712 OrderParams Schema // bytes32 constant internal EIP712_VOTE_CAST_SCHEMA_HASH = keccak256(abi.encodePacked( // "VoteCast(", // "uint128 proposalId,", // "bool support", // ")" // )); bytes32 internal constant EIP712_VOTE_CAST_SCHEMA_HASH = 0x4abb8ae9facc09d5584ac64f616551bfc03c3ac63e5c431132305bd9bc8f8246; /// @dev Calculates Keccak-256 hash of the vote cast. /// @param voteCast The vote cast structure. /// @return voteCastHash Keccak-256 EIP712 hash of the vote cast. function getVoteCastHash(VoteCast memory voteCast, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 voteCastHash) { voteCastHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashVoteCast(voteCast)); return voteCastHash; } /// @dev Calculates EIP712 hash of the vote cast. /// @param voteCast The vote cast structure. /// @return result EIP712 hash of the vote cast. function hashVoteCast(VoteCast memory voteCast) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_VOTE_CAST_SCHEMA_HASH; assembly { // Assert vote cast offset (this is an internal error that should never be triggered) if lt(voteCast, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(voteCast, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 96) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { GovernanceDefs } from "../../libs/defs/GovernanceDefs.sol"; import { LibEIP712 } from "../../libs/LibEIP712.sol"; import { LibVoteCast } from "../../libs/LibVoteCast.sol"; import { LibBytes } from "../../libs/LibBytes.sol"; import { SafeMath32 } from "../../libs/SafeMath32.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { SafeMath128 } from "../../libs/SafeMath128.sol"; import { MathHelpers } from "../../libs/MathHelpers.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageGovernance } from "../../storage/LibDiamondStorageGovernance.sol"; /** * @title Governance * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to governance. The Diamond storage * will only be affected when facet functions are called via * the proxy contract, no checks are necessary. * @dev The Diamond storage will only be affected when facet functions * are called via the proxy contract, no checks are necessary. */ contract Governance { using SafeMath32 for uint32; using SafeMath96 for uint96; using SafeMath128 for uint128; using SafeMath for uint256; using MathHelpers for uint96; using MathHelpers for uint256; using LibBytes for bytes; /// @notice name for this Governance contract string public constant name = "DDX Governance"; // solhint-disable-line const-name-snakecase /// @notice version for this Governance contract string public constant version = "1"; // solhint-disable-line const-name-snakecase /// @notice Emitted when a new proposal is created event ProposalCreated( uint128 indexed id, address indexed proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /// @notice Emitted when a vote has been cast on a proposal event VoteCast(address indexed voter, uint128 indexed proposalId, bool support, uint96 votes); /// @notice Emitted when a proposal has been canceled event ProposalCanceled(uint128 indexed id); /// @notice Emitted when a proposal has been queued event ProposalQueued(uint128 indexed id, uint256 eta); /// @notice Emitted when a proposal has been executed event ProposalExecuted(uint128 indexed id); /// @notice Emitted when a proposal action has been canceled event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /// @notice Emitted when a proposal action has been executed event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /// @notice Emitted when a proposal action has been queued event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Governance: must be called by Governance admin."); _; } /** * @notice This function initializes the state with some critical * information. This can only be called once and must be * done via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @param _quorumVotes Minimum number of for votes required, even * if there's a majority in favor. * @param _proposalThreshold Minimum DDX token holdings required * to create a proposal * @param _proposalMaxOperations Max number of operations/actions a * proposal can have * @param _votingDelay Number of blocks after a proposal is made * that voting begins. * @param _votingPeriod Number of blocks voting will be held. * @param _skipRemainingVotingThreshold Number of for or against * votes that are necessary to skip the remainder of the * voting period. * @param _gracePeriod Period in which a successful proposal must be * executed, otherwise will be expired. * @param _timelockDelay Time (s) in which a successful proposal * must be in the queue before it can be executed. */ function initialize( uint32 _proposalMaxOperations, uint32 _votingDelay, uint32 _votingPeriod, uint32 _gracePeriod, uint32 _timelockDelay, uint32 _quorumVotes, uint32 _proposalThreshold, uint32 _skipRemainingVotingThreshold ) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure state variable comparisons are valid requireValidSkipRemainingVotingThreshold(_skipRemainingVotingThreshold); requireSkipRemainingVotingThresholdGtQuorumVotes(_skipRemainingVotingThreshold, _quorumVotes); // Set initial variable values dsGovernance.proposalMaxOperations = _proposalMaxOperations; dsGovernance.votingDelay = _votingDelay; dsGovernance.votingPeriod = _votingPeriod; dsGovernance.gracePeriod = _gracePeriod; dsGovernance.timelockDelay = _timelockDelay; dsGovernance.quorumVotes = _quorumVotes; dsGovernance.proposalThreshold = _proposalThreshold; dsGovernance.skipRemainingVotingThreshold = _skipRemainingVotingThreshold; dsGovernance.fastPathFunctionSignatures["setIsPaused(bool)"] = true; } /** * @notice This function allows participants who have sufficient * DDX holdings to create new proposals up for vote. The * proposals contain the ordered lists of on-chain * executable calldata. * @param _targets Addresses of contracts involved. * @param _values Values to be passed along with the calls. * @param _signatures Function signatures. * @param _calldatas Calldata passed to the function. * @param _description Text description of proposal. */ function propose( address[] memory _targets, uint256[] memory _values, string[] memory _signatures, bytes[] memory _calldatas, string memory _description ) external returns (uint128) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposer has sufficient token holdings to propose require( dsDerivaDEX.ddxToken.getPriorVotes(msg.sender, block.number.sub(1)) >= getProposerThresholdCount(), "Governance: proposer votes below proposal threshold." ); require( _targets.length == _values.length && _targets.length == _signatures.length && _targets.length == _calldatas.length, "Governance: proposal function information parity mismatch." ); require(_targets.length != 0, "Governance: must provide actions."); require(_targets.length <= dsGovernance.proposalMaxOperations, "Governance: too many actions."); if (dsGovernance.latestProposalIds[msg.sender] != 0) { // Ensure proposer doesn't already have one active/pending GovernanceDefs.ProposalState proposersLatestProposalState = state(dsGovernance.latestProposalIds[msg.sender]); require( proposersLatestProposalState != GovernanceDefs.ProposalState.Active, "Governance: one live proposal per proposer, found an already active proposal." ); require( proposersLatestProposalState != GovernanceDefs.ProposalState.Pending, "Governance: one live proposal per proposer, found an already pending proposal." ); } // Proposal voting starts votingDelay after proposal is made uint256 startBlock = block.number.add(dsGovernance.votingDelay); // Increment count of proposals dsGovernance.proposalCount++; // Create new proposal struct and add to mapping GovernanceDefs.Proposal memory newProposal = GovernanceDefs.Proposal({ id: dsGovernance.proposalCount, proposer: msg.sender, delay: getTimelockDelayForSignatures(_signatures), eta: 0, targets: _targets, values: _values, signatures: _signatures, calldatas: _calldatas, startBlock: startBlock, endBlock: startBlock.add(dsGovernance.votingPeriod), forVotes: 0, againstVotes: 0, canceled: false, executed: false }); dsGovernance.proposals[newProposal.id] = newProposal; // Update proposer's latest proposal dsGovernance.latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated( newProposal.id, msg.sender, _targets, _values, _signatures, _calldatas, startBlock, startBlock.add(dsGovernance.votingPeriod), _description ); return newProposal.id; } /** * @notice This function allows any participant to queue a * successful proposal for execution. Proposals are deemed * successful if at any point the number of for votes has * exceeded the skip remaining voting threshold or if there * is a simple majority (and more for votes than the * minimum quorum) at the end of voting. * @param _proposalId Proposal id. */ function queue(uint128 _proposalId) external { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposal has succeeded (i.e. it has either enough for // votes to skip the remainder of the voting period or the // voting period has ended and there is a simple majority in // favor and also above the quorum require( state(_proposalId) == GovernanceDefs.ProposalState.Succeeded, "Governance: proposal can only be queued if it is succeeded." ); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Establish eta of execution, which is a number of seconds // after queuing at which point proposal can actually execute uint256 eta = block.timestamp.add(proposal.delay); for (uint256 i = 0; i < proposal.targets.length; i++) { // Ensure proposal action is not already in the queue bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ) ); require(!dsGovernance.queuedTransactions[txHash], "Governance: proposal action already queued at eta."); dsGovernance.queuedTransactions[txHash] = true; emit QueueTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ); } // Set proposal eta timestamp after which it can be executed proposal.eta = eta; emit ProposalQueued(_proposalId, eta); } /** * @notice This function allows any participant to execute a * queued proposal. A proposal in the queue must be in the * queue for the delay period it was proposed with prior to * executing, allowing the community to position itself * accordingly. * @param _proposalId Proposal id. */ function execute(uint128 _proposalId) external payable { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposal is queued require( state(_proposalId) == GovernanceDefs.ProposalState.Queued, "Governance: proposal can only be executed if it is queued." ); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Ensure proposal has been in the queue long enough require(block.timestamp >= proposal.eta, "Governance: proposal hasn't finished queue time length."); // Ensure proposal hasn't been in the queue for too long require(block.timestamp <= proposal.eta.add(dsGovernance.gracePeriod), "Governance: transaction is stale."); proposal.executed = true; // Loop through each of the actions in the proposal for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); require(dsGovernance.queuedTransactions[txHash], "Governance: transaction hasn't been queued."); dsGovernance.queuedTransactions[txHash] = false; // Execute action bytes memory callData; require(bytes(proposal.signatures[i]).length != 0, "Governance: Invalid function signature."); callData = abi.encodePacked(bytes4(keccak256(bytes(proposal.signatures[i]))), proposal.calldatas[i]); // solium-disable-next-line security/no-call-value (bool success, ) = proposal.targets[i].call{ value: proposal.values[i] }(callData); require(success, "Governance: transaction execution reverted."); emit ExecuteTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalExecuted(_proposalId); } /** * @notice This function allows any participant to cancel any non- * executed proposal. It can be canceled if the proposer's * token holdings has dipped below the proposal threshold * at the time of cancellation. * @param _proposalId Proposal id. */ function cancel(uint128 _proposalId) external { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.ProposalState state = state(_proposalId); // Ensure proposal hasn't executed require(state != GovernanceDefs.ProposalState.Executed, "Governance: cannot cancel executed proposal."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Ensure proposer's token holdings has dipped below the // proposer threshold, leaving their proposal subject to // cancellation require( dsDerivaDEX.ddxToken.getPriorVotes(proposal.proposer, block.number.sub(1)) < getProposerThresholdCount(), "Governance: proposer above threshold." ); proposal.canceled = true; // Loop through each of the proposal's actions for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); dsGovernance.queuedTransactions[txHash] = false; emit CancelTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalCanceled(_proposalId); } /** * @notice This function allows participants to cast either in * favor or against a particular proposal. * @param _proposalId Proposal id. * @param _support In favor (true) or against (false). */ function castVote(uint128 _proposalId, bool _support) external { return _castVote(msg.sender, _proposalId, _support); } /** * @notice This function allows participants to cast votes with * offline signatures in favor or against a particular * proposal. * @param _proposalId Proposal id. * @param _support In favor (true) or against (false). * @param _signature Signature */ function castVoteBySig( uint128 _proposalId, bool _support, bytes memory _signature ) external { // EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 voteCastHash = LibVoteCast.getVoteCastHash( LibVoteCast.VoteCast({ proposalId: _proposalId, support: _support }), eip712OrderParamsDomainHash ); // Recover the signature and EIP712 hash uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); address recovered = ecrecover(voteCastHash, v, r, s); require(recovered != address(0), "Governance: invalid signature."); return _castVote(recovered, _proposalId, _support); } /** * @notice This function sets the quorum votes required for a * proposal to pass. It must be called via * governance. * @param _quorumVotes Quorum votes threshold. */ function setQuorumVotes(uint32 _quorumVotes) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); requireSkipRemainingVotingThresholdGtQuorumVotes(dsGovernance.skipRemainingVotingThreshold, _quorumVotes); dsGovernance.quorumVotes = _quorumVotes; } /** * @notice This function sets the token holdings threshold required * to propose something. It must be called via * governance. * @param _proposalThreshold Proposal threshold. */ function setProposalThreshold(uint32 _proposalThreshold) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.proposalThreshold = _proposalThreshold; } /** * @notice This function sets the max operations a proposal can * carry out. It must be called via governance. * @param _proposalMaxOperations Proposal's max operations. */ function setProposalMaxOperations(uint32 _proposalMaxOperations) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.proposalMaxOperations = _proposalMaxOperations; } /** * @notice This function sets the voting delay in blocks from when * a proposal is made and voting begins. It must be called * via governance. * @param _votingDelay Voting delay (blocks). */ function setVotingDelay(uint32 _votingDelay) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.votingDelay = _votingDelay; } /** * @notice This function sets the voting period in blocks that a * vote will last. It must be called via * governance. * @param _votingPeriod Voting period (blocks). */ function setVotingPeriod(uint32 _votingPeriod) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.votingPeriod = _votingPeriod; } /** * @notice This function sets the threshold at which a proposal can * immediately be deemed successful or rejected if the for * or against votes exceeds this threshold, even if the * voting period is still ongoing. It must be called * governance. * @param _skipRemainingVotingThreshold Threshold for or against * votes must reach to skip remainder of voting period. */ function setSkipRemainingVotingThreshold(uint32 _skipRemainingVotingThreshold) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); requireValidSkipRemainingVotingThreshold(_skipRemainingVotingThreshold); requireSkipRemainingVotingThresholdGtQuorumVotes(_skipRemainingVotingThreshold, dsGovernance.quorumVotes); dsGovernance.skipRemainingVotingThreshold = _skipRemainingVotingThreshold; } /** * @notice This function sets the grace period in seconds that a * queued proposal can last before expiring. It must be * called via governance. * @param _gracePeriod Grace period (seconds). */ function setGracePeriod(uint32 _gracePeriod) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.gracePeriod = _gracePeriod; } /** * @notice This function sets the timelock delay (s) a proposal * must be queued before execution. * @param _timelockDelay Timelock delay (seconds). */ function setTimelockDelay(uint32 _timelockDelay) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.timelockDelay = _timelockDelay; } /** * @notice This function allows any participant to retrieve * the actions involved in a given proposal. * @param _proposalId Proposal id. * @return targets Addresses of contracts involved. * @return values Values to be passed along with the calls. * @return signatures Function signatures. * @return calldatas Calldata passed to the function. */ function getActions(uint128 _proposalId) external view returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.Proposal storage p = dsGovernance.proposals[_proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } /** * @notice This function allows any participant to retrieve * the receipt for a given proposal and voter. * @param _proposalId Proposal id. * @param _voter Voter address. * @return Voter receipt. */ function getReceipt(uint128 _proposalId, address _voter) external view returns (GovernanceDefs.Receipt memory) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.proposals[_proposalId].receipts[_voter]; } /** * @notice This function gets a proposal from an ID. * @param _proposalId Proposal id. * @return Proposal attributes. */ function getProposal(uint128 _proposalId) external view returns ( bool, bool, address, uint32, uint96, uint96, uint128, uint256, uint256, uint256 ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.Proposal memory proposal = dsGovernance.proposals[_proposalId]; return ( proposal.canceled, proposal.executed, proposal.proposer, proposal.delay, proposal.forVotes, proposal.againstVotes, proposal.id, proposal.eta, proposal.startBlock, proposal.endBlock ); } /** * @notice This function gets whether a proposal action transaction * hash is queued or not. * @param _txHash Proposal action tx hash. * @return Is proposal action transaction hash queued or not. */ function getIsQueuedTransaction(bytes32 _txHash) external view returns (bool) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.queuedTransactions[_txHash]; } /** * @notice This function gets the Governance facet's current * parameters. * @return Proposal max operations. * @return Voting delay. * @return Voting period. * @return Grace period. * @return Timelock delay. * @return Quorum votes threshold. * @return Proposal threshold. * @return Skip remaining voting threshold. */ function getGovernanceParameters() external view returns ( uint32, uint32, uint32, uint32, uint32, uint32, uint32, uint32 ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return ( dsGovernance.proposalMaxOperations, dsGovernance.votingDelay, dsGovernance.votingPeriod, dsGovernance.gracePeriod, dsGovernance.timelockDelay, dsGovernance.quorumVotes, dsGovernance.proposalThreshold, dsGovernance.skipRemainingVotingThreshold ); } /** * @notice This function gets the proposal count. * @return Proposal count. */ function getProposalCount() external view returns (uint128) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.proposalCount; } /** * @notice This function gets the latest proposal ID for a user. * @param _proposer Proposer's address. * @return Proposal ID. */ function getLatestProposalId(address _proposer) external view returns (uint128) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.latestProposalIds[_proposer]; } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getQuorumVoteCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.quorumVotes, 100); } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getProposerThresholdCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.proposalThreshold, 100); } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getSkipRemainingVotingThresholdCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.skipRemainingVotingThreshold, 100); } /** * @notice This function retrieves the status for any given * proposal. * @param _proposalId Proposal id. * @return Status of proposal. */ function state(uint128 _proposalId) public view returns (GovernanceDefs.ProposalState) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); require(dsGovernance.proposalCount >= _proposalId && _proposalId > 0, "Governance: invalid proposal id."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Note the 3rd conditional where we can escape out of the vote // phase if the for or against votes exceeds the skip remaining // voting threshold if (proposal.canceled) { return GovernanceDefs.ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return GovernanceDefs.ProposalState.Pending; } else if ( (block.number <= proposal.endBlock) && (proposal.forVotes < getSkipRemainingVotingThresholdCount()) && (proposal.againstVotes < getSkipRemainingVotingThresholdCount()) ) { return GovernanceDefs.ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < getQuorumVoteCount()) { return GovernanceDefs.ProposalState.Defeated; } else if (proposal.eta == 0) { return GovernanceDefs.ProposalState.Succeeded; } else if (proposal.executed) { return GovernanceDefs.ProposalState.Executed; } else if (block.timestamp >= proposal.eta.add(dsGovernance.gracePeriod)) { return GovernanceDefs.ProposalState.Expired; } else { return GovernanceDefs.ProposalState.Queued; } } function _castVote( address _voter, uint128 _proposalId, bool _support ) internal { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); require(state(_proposalId) == GovernanceDefs.ProposalState.Active, "Governance: voting is closed."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; GovernanceDefs.Receipt storage receipt = proposal.receipts[_voter]; // Ensure voter has not already voted require(!receipt.hasVoted, "Governance: voter already voted."); // Obtain the token holdings (voting power) for participant at // the time voting started. They may have gained or lost tokens // since then, doesn't matter. uint96 votes = dsDerivaDEX.ddxToken.getPriorVotes(_voter, proposal.startBlock); // Ensure voter has nonzero voting power require(votes > 0, "Governance: voter has no voting power."); if (_support) { // Increment the for votes in favor proposal.forVotes = proposal.forVotes.add96(votes); } else { // Increment the against votes proposal.againstVotes = proposal.againstVotes.add96(votes); } // Set receipt attributes based on cast vote parameters receipt.hasVoted = true; receipt.support = _support; receipt.votes = votes; emit VoteCast(_voter, _proposalId, _support, votes); } function getTimelockDelayForSignatures(string[] memory _signatures) internal view returns (uint32) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); for (uint256 i = 0; i < _signatures.length; i++) { if (!dsGovernance.fastPathFunctionSignatures[_signatures[i]]) { return dsGovernance.timelockDelay; } } return 1; } function requireSkipRemainingVotingThresholdGtQuorumVotes(uint32 _skipRemainingVotingThreshold, uint32 _quorumVotes) internal pure { require(_skipRemainingVotingThreshold > _quorumVotes, "Governance: skip rem votes must be higher than quorum."); } function requireValidSkipRemainingVotingThreshold(uint32 _skipRemainingVotingThreshold) internal pure { require(_skipRemainingVotingThreshold >= 50, "Governance: skip rem votes must be higher than 50pct."); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title GovernanceDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * the governance. */ library GovernanceDefs { struct Proposal { bool canceled; bool executed; address proposer; uint32 delay; uint96 forVotes; uint96 againstVotes; uint128 id; uint256 eta; address[] targets; string[] signatures; bytes[] calldatas; uint256[] values; uint256 startBlock; uint256 endBlock; mapping(address => Receipt) receipts; } struct Receipt { bool hasVoted; bool support; uint96 votes; } enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 SafeMath128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint128 a, uint128 b) internal pure returns (uint128) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint128 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { GovernanceDefs } from "../libs/defs/GovernanceDefs.sol"; library LibDiamondStorageGovernance { struct DiamondStorageGovernance { // Proposal struct by ID mapping(uint256 => GovernanceDefs.Proposal) proposals; // Latest proposal IDs by proposer address mapping(address => uint128) latestProposalIds; // Whether transaction hash is currently queued mapping(bytes32 => bool) queuedTransactions; // Fast path for governance mapping(string => bool) fastPathFunctionSignatures; // Max number of operations/actions a proposal can have uint32 proposalMaxOperations; // Number of blocks after a proposal is made that voting begins // (e.g. 1 block) uint32 votingDelay; // Number of blocks voting will be held // (e.g. 17280 blocks ~ 3 days of blocks) uint32 votingPeriod; // Time window (s) a successful proposal must be executed, // otherwise will be expired, measured in seconds // (e.g. 1209600 seconds) uint32 gracePeriod; // Minimum time (s) in which a successful proposal must be // in the queue before it can be executed // (e.g. 0 seconds) uint32 minimumDelay; // Maximum time (s) in which a successful proposal must be // in the queue before it can be executed // (e.g. 2592000 seconds ~ 30 days) uint32 maximumDelay; // Minimum number of for votes required, even if there's a // majority in favor // (e.g. 2000000e18 ~ 4% of pre-mine DDX supply) uint32 quorumVotes; // Minimum DDX token holdings required to create a proposal // (e.g. 500000e18 ~ 1% of pre-mine DDX supply) uint32 proposalThreshold; // Number of for or against votes that are necessary to skip // the remainder of the voting period // (e.g. 25000000e18 tokens/votes) uint32 skipRemainingVotingThreshold; // Time (s) proposals must be queued before executing uint32 timelockDelay; // Total number of proposals uint128 proposalCount; } bytes32 constant DIAMOND_STORAGE_POSITION_GOVERNANCE = keccak256("diamond.standard.diamond.storage.DerivaDEX.Governance"); function diamondStorageGovernance() internal pure returns (DiamondStorageGovernance storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_GOVERNANCE; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStoragePause } from "../../storage/LibDiamondStoragePause.sol"; /** * @title Pause * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to pausing functionality. The purpose * of this is to ensure the system can pause in the unlikely * scenario of a bug or issue materially jeopardizing users' * funds or experience. This facet will be removed entirely * as the system stabilizes shortly. It's important to note that * unlike the vast majority of projects, even during this * short-lived period of time in which the system can be paused, * no single admin address can wield this power, but rather * pausing must be carried out via governance. */ contract Pause { event PauseInitialized(); event IsPausedSet(bool isPaused); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Pause: must be called by Gov."); _; } /** * @notice This function initializes the facet. */ function initialize() external onlyAdmin { emit PauseInitialized(); } /** * @notice This function sets the paused status. * @param _isPaused Whether contracts are paused or not. */ function setIsPaused(bool _isPaused) external onlyAdmin { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); dsPause.isPaused = _isPaused; emit IsPausedSet(_isPaused); } /** * @notice This function gets whether the contract ecosystem is * currently paused. * @return Whether contracts are paused or not. */ function getIsPaused() public view returns (bool) { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); return dsPause.isPaused; } } // SPDX-License-Identifier: MIT /** *Submitted for verification at Etherscan.io on 2019-07-18 */ pragma solidity 0.6.12; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Ownable } from "openzeppelin-solidity/contracts/access/Ownable.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; library Roles { struct Role { mapping(address => bool) bearer; } function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract PauserRole is Ownable { using Roles for Roles.Role; Roles.Role private _pausers; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); constructor() internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyOwner { _addPauser(account); } function removePauser(address account) public onlyOwner { _removePauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } contract Pausable is PauserRole { bool private _paused; event Paused(address account); event Unpaused(address account); constructor() internal { _paused = false; } function paused() public view returns (bool) { return _paused; } modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } contract ERC20 is IERC20, Ownable { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; event Issue(address indexed account, uint256 amount); event Redeem(address indexed account, uint256 value); function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public virtual override returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 value ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } function _issue(address account, uint256 amount) internal { require(account != address(0), "CoinFactory: issue to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); emit Issue(account, amount); } function _redeem(address account, uint256 value) internal { require(account != address(0), "CoinFactory: redeem from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); emit Redeem(account, value); } } contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public virtual override whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public virtual override whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public virtual override whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public virtual override whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } contract CoinFactoryAdminRole is Ownable { using Roles for Roles.Role; event CoinFactoryAdminRoleAdded(address indexed account); event CoinFactoryAdminRoleRemoved(address indexed account); Roles.Role private _coinFactoryAdmins; constructor() internal { _addCoinFactoryAdmin(msg.sender); } modifier onlyCoinFactoryAdmin() { require(isCoinFactoryAdmin(msg.sender), "CoinFactoryAdminRole: caller does not have the CoinFactoryAdmin role"); _; } function isCoinFactoryAdmin(address account) public view returns (bool) { return _coinFactoryAdmins.has(account); } function addCoinFactoryAdmin(address account) public onlyOwner { _addCoinFactoryAdmin(account); } function removeCoinFactoryAdmin(address account) public onlyOwner { _removeCoinFactoryAdmin(account); } function renounceCoinFactoryAdmin() public { _removeCoinFactoryAdmin(msg.sender); } function _addCoinFactoryAdmin(address account) internal { _coinFactoryAdmins.add(account); emit CoinFactoryAdminRoleAdded(account); } function _removeCoinFactoryAdmin(address account) internal { _coinFactoryAdmins.remove(account); emit CoinFactoryAdminRoleRemoved(account); } } contract CoinFactory is ERC20, CoinFactoryAdminRole { function issue(address account, uint256 amount) public onlyCoinFactoryAdmin returns (bool) { _issue(account, amount); return true; } function redeem(address account, uint256 amount) public onlyCoinFactoryAdmin returns (bool) { _redeem(account, amount); return true; } } contract BlacklistAdminRole is Ownable { using Roles for Roles.Role; event BlacklistAdminAdded(address indexed account); event BlacklistAdminRemoved(address indexed account); Roles.Role private _blacklistAdmins; constructor() internal { _addBlacklistAdmin(msg.sender); } modifier onlyBlacklistAdmin() { require(isBlacklistAdmin(msg.sender), "BlacklistAdminRole: caller does not have the BlacklistAdmin role"); _; } function isBlacklistAdmin(address account) public view returns (bool) { return _blacklistAdmins.has(account); } function addBlacklistAdmin(address account) public onlyOwner { _addBlacklistAdmin(account); } function removeBlacklistAdmin(address account) public onlyOwner { _removeBlacklistAdmin(account); } function renounceBlacklistAdmin() public { _removeBlacklistAdmin(msg.sender); } function _addBlacklistAdmin(address account) internal { _blacklistAdmins.add(account); emit BlacklistAdminAdded(account); } function _removeBlacklistAdmin(address account) internal { _blacklistAdmins.remove(account); emit BlacklistAdminRemoved(account); } } contract Blacklist is ERC20, BlacklistAdminRole { mapping(address => bool) private _blacklist; event BlacklistAdded(address indexed account); event BlacklistRemoved(address indexed account); function addBlacklist(address[] memory accounts) public onlyBlacklistAdmin returns (bool) { for (uint256 i = 0; i < accounts.length; i++) { _addBlacklist(accounts[i]); } } function removeBlacklist(address[] memory accounts) public onlyBlacklistAdmin returns (bool) { for (uint256 i = 0; i < accounts.length; i++) { _removeBlacklist(accounts[i]); } } function isBlacklist(address account) public view returns (bool) { return _blacklist[account]; } function _addBlacklist(address account) internal { _blacklist[account] = true; emit BlacklistAdded(account); } function _removeBlacklist(address account) internal { _blacklist[account] = false; emit BlacklistRemoved(account); } } contract HDUMToken is ERC20, ERC20Pausable, CoinFactory, Blacklist { string public name; string public symbol; uint8 public decimals; uint256 private _totalSupply; constructor( string memory _name, string memory _symbol, uint8 _decimals ) public { _totalSupply = 0; name = _name; symbol = _symbol; decimals = _decimals; } function transfer(address to, uint256 value) public override(ERC20, ERC20Pausable) whenNotPaused returns (bool) { require(!isBlacklist(msg.sender), "HDUMToken: caller in blacklist can't transfer"); require(!isBlacklist(to), "HDUMToken: not allow to transfer to recipient address in blacklist"); return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public override(ERC20, ERC20Pausable) whenNotPaused returns (bool) { require(!isBlacklist(msg.sender), "HDUMToken: caller in blacklist can't transferFrom"); require(!isBlacklist(from), "HDUMToken: from in blacklist can't transfer"); require(!isBlacklist(to), "HDUMToken: not allow to transfer to recipient address in blacklist"); return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { Context } from "openzeppelin-solidity/contracts/GSN/Context.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; contract SafeERC20Wrapper is Context { using SafeERC20 for IERC20; IERC20 private _token; constructor(IERC20 token) public { _token = token; } function transfer(address recipient, uint256 amount) public { _token.safeTransfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public { _token.safeTransferFrom(sender, recipient, amount); } function approve(address spender, uint256 amount) public { _token.safeApprove(spender, amount); } function increaseAllowance(address spender, uint256 amount) public { _token.safeIncreaseAllowance(spender, amount); } function decreaseAllowance(address spender, uint256 amount) public { _token.safeDecreaseAllowance(spender, amount); } function allowance(address owner, address spender) public view returns (uint256) { return _token.allowance(owner, spender); } function balanceOf(address account) public view returns (uint256) { return _token.balanceOf(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; // mock class using ERC20 contract DummyToken is ERC20 { uint256 public constant INITIAL_SUPPLY = 100000000 * (10**18); constructor(string memory name, string memory symbol) public payable ERC20(name, symbol) { _mint(msg.sender, INITIAL_SUPPLY); } function mint(address account, uint256 amount) public { _mint(account, amount); } function burn(address account, uint256 amount) public { _burn(account, amount); } function transferInternal( address from, address to, uint256 value ) public { _transfer(from, to, value); } function approveInternal( address owner, address spender, uint256 value ) public { _approve(owner, spender, value); } }
Reads nested bytes from a specific position. NOTE: the returned value overlaps with the input value. Both should be treated as immutable. b Byte array containing nested bytes. index Index of nested bytes. return result Nested bytes. Read length of nested bytes Assert length of <b> is valid, given length of nested bytes Return a pointer to the byte array as it exists inside `b`
function readBytesWithLength(bytes memory b, uint256 index) internal pure returns (bytes memory result) { uint256 nestedBytesLength = readUint256(b, index); index += 32; require(b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"); assembly { result := add(b, index) } return result; }
1,813,781
./partial_match/1/0xe87dA6fAD508A9C21b999F252CCF0FC10A3E3cdd/sources/ProofOfContractSnipers.sol
Transfer tokens from the caller to a new holder. Remember, there's a 10% fee here as well./ setup make sure we have the requested tokens also disables transfers until ambassador phase is over ( we dont want whale premines ) withdraw all outstanding dividends first exchange tokens update dividend trackers fire event ERC20
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { address _customerAddress = msg.sender; require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); if(myDividends(true) > 0) withdraw(); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); Transfer(_customerAddress, _toAddress, _amountOfTokens); return true; }
2,617,156
//Address: 0xdac4f0d74592012eb4baeb608b1992ffe5cc537a //Contract name: WorldCupBroker //Balance: 1.88335987807420416 Ether //Verification Date: 6/9/2018 //Transacion Count: 33 // CODE STARTS HERE pragma solidity ^0.4.18; // 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/strings.sol /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ pragma solidity ^0.4.14; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice self) internal pure returns (slice) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal pure returns (string) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice self, slice rune) internal pure returns (slice) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice self) internal pure returns (slice ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice self, slice needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal pure returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, length), sha3(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice self, slice needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal pure returns (slice) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } event log_bytemask(bytes32 mask); // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice self, slice needle) internal pure returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice self, slice needle) internal pure returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal pure returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal pure returns (slice token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice self, slice needle, slice token) internal pure returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice self, slice needle) internal pure returns (slice token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice self, slice needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice self, slice other) internal pure returns (string) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal pure returns (string) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } // File: contracts/usingOraclize.sol // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity ^0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> // File: contracts/WorldCupBroker.sol /* * @title String & slice utility library for Solidity contracts. * @author Daniel Bennett <[email protected]> * * @dev This is a solitidy contract that facilitates betting for the 2018 world cup. The contract on does not act as a counter party to any bets placed and thus users bet on a decision pool for a match (win, lose, draw), and based on the results of users will be credited winnings proportional to their contributions to the winning pool. */ pragma solidity ^0.4.4; contract WorldCupBroker is Ownable, usingOraclize { using strings for *; struct Bet { bool cancelled; bool claimed; uint amount; uint8 option; // 1 - teamA, 2 - teamB, 3 - Draw address better; } struct Match { bool locked; // match will be locked after payout or all bets returned bool cancelled; uint8 teamA; uint8 teamB; uint8 winner; // 0 - not set, 1 - teamA, 2 - teamB, 3- Draw, 4 - no winner uint start; uint closeBettingTime; // since this the close delay is constant // this will always be the same, save gas for betters and just set the close time once uint totalTeamABets; uint totalTeamBBets; uint totalDrawBets; uint numBets; string fixtureId; string secondaryFixtureId; bool inverted; // inverted if the secondary api has the home team and away teams inverted string name; mapping(uint => Bet) bets; } event MatchCreated(uint8); event MatchUpdated(uint8); event MatchFailedPayoutRelease(uint8); event BetPlaced( uint8 matchId, uint8 outcome, uint betId, uint amount, address better ); event BetClaimed( uint8 matchId, uint betId ); event BetCancelled( uint8 matchId, uint betId ); string[32] public TEAMS = [ "Russia", "Saudi Arabia", "Egypt", "Uruguay", "Morocco", "Iran", "Portugal", "Spain", "France", "Australia", "Argentina", "Iceland", "Peru", "Denmark", "Croatia", "Nigeria", "Costa Rica", "Serbia", "Germany", "Mexico", "Brazil", "Switzerland", "Sweden", "South Korea", "Belgium", "Panama", "Tunisia", "England", "Poland", "Senegal", "Colombia", "Japan" ]; uint public constant MAX_NUM_PAYOUT_ATTEMPTS = 3; // after 3 consecutive failed payout attempts, lock the match uint public constant PAYOUT_ATTEMPT_INTERVAL = 10 minutes; // try every 10 minutes to release payout uint public commission_rate = 7; uint public minimum_bet = 0.01 ether; uint private commissions = 0; uint public primaryGasLimit = 225000; uint public secondaryGasLimit = 250000; Match[] matches; mapping(bytes32 => uint8) oraclizeIds; mapping(uint8 => uint8) payoutAttempts; mapping(uint8 => bool) firstStepVerified; mapping(uint8 => uint8) pendingWinner; /* * @dev Ensures a matchId points to a legitimate match * @param _matchId the uint to check if it points to a valid match. */ modifier validMatch(uint8 _matchId) { require(_matchId < uint8(matches.length)); _; } /* * @dev the validBet modifier does as it's name implies and ensures that a bet * is valid before proceeding with any methods called on the contract * that would require access to such a bet * @param _matchId the uint to check if it points to a valid match. * @param _betId the uint to check if it points to a valid bet for a match. */ modifier validBet(uint8 _matchId, uint _betId) { // short circuit to save gas require(_matchId < uint8(matches.length) && _betId < matches[_matchId].numBets); _; } /* * @dev Adds a new match to the smart contract and schedules an oraclize query call * to determine the winner of a match within 3 hours. Additionally emits an event * signifying a match was created. * @param _name the unique identifier of the match, should be of format Stage:Team A vs Team B * @param _fixture the fixtureId for the football-data.org endpoint * @param _secondary the fixtureId for the sportsmonk.com endpoint * @param _inverted should be set to true if the teams are inverted on either of the API * that is if the hometeam and localteam are swapped * @param _teamA index of the homeTeam from the TEAMS array * @param _teamB index of the awayTeam from the TEAMS array * @param _start the unix timestamp for when the match is scheduled to begin * @return `uint` the Id of the match in the matches array */ function addMatch(string _name, string _fixture, string _secondary, bool _invert, uint8 _teamA, uint8 _teamB, uint _start) public onlyOwner returns (uint8) { // Check that there's at least 15 minutes until the match starts require(_teamA < 32 && _teamB < 32 && _teamA != _teamB && (_start - 15 minutes) >= now); Match memory newMatch = Match({ locked: false, cancelled: false, teamA: _teamA, teamB: _teamB, winner: 0, fixtureId: _fixture, // The primary fixtureId that will be used to query the football-data API secondaryFixtureId: _secondary, // The secondary fixtureID used to query sports monk inverted: _invert, start: _start, closeBettingTime: _start - 3 minutes, // betting closes 3 minutes before a match starts totalTeamABets: 0, totalTeamBBets: 0, totalDrawBets: 0, numBets: 0, name: _name }); uint8 matchId = uint8(matches.push(newMatch)) - 1; // concatinate oraclize query string memory url = strConcat( "[URL] json(https://soccer.sportmonks.com/api/v2.0/fixtures/", newMatch.secondaryFixtureId, "?api_token=${[decrypt] BNxYykO2hsQ7iA7yRuDLSu1km6jFZwN5X87TY1BSmU30llRn8uWkJjHgx+YGytA1tmbRjb20CW0gIzcFmvq3yLZnitsvW28SPjlf+s9MK7hU+uRXqwhoW6dmWqKsBrCigrggFwMBRk4kA16jugtIr+enXHjOnAKSxd1dO4YXTCYvZc3T1pFA9PVyFFnd}).data.scores[localteam_score,visitorteam_score]"); // store the oraclize query id for later use // use hours to over estimate the amount of time it would take to safely get a correct result // 90 minutes of regulation play time + potential 30 minutes of extra time + 15 minutes break // + potential 10 minutes of stoppage time + potential 10 minutes of penalties // + 25 minutes of time for any APIs to correct and ensure their information is correct bytes32 oraclizeId = oraclize_query((_start + (3 hours)), "nested", url, primaryGasLimit); oraclizeIds[oraclizeId] = matchId; emit MatchCreated(matchId); return matchId; } function cancelMatch(uint8 _matchId) public onlyOwner validMatch(_matchId) returns (bool) { Match storage mtch = matches[_matchId]; require(!mtch.cancelled && now < mtch.closeBettingTime); mtch.cancelled = true; mtch.locked = true; emit MatchUpdated(_matchId); return true; } /* * @dev returns the number of matches on the contract */ function getNumMatches() public view returns (uint) { return matches.length; } /* * @dev Returns some of the properties of a match. Functionality had to be seperated * into 2 function calls to prevent stack too deep errors * @param _matchId the index of that match in the matches array * @return `string` the match name * @return `string` the fixutre Id of the match for the football-data endpoint * @return `string` the fixture Id fo the match for the sports monk endpoint * @return `uint8` the index of the home team * @return `uint8` the index of the away team * @return `uint8` the winner of the match * @return `uint` the unix timestamp for the match start time * @return `bool` Match cancelled boolean * @return `bool` Match locked boolean which is set to true if the match is payed out or bets are returned */ function getMatch(uint8 _matchId) public view validMatch(_matchId) returns (string, string, string, bool, uint8, uint8, uint8, uint, bool, bool) { Match memory mtch = matches[_matchId]; return ( mtch.name, mtch.fixtureId, mtch.secondaryFixtureId, mtch.inverted, mtch.teamA, mtch.teamB, mtch.winner, mtch.start, mtch.cancelled, mtch.locked ); } /* * @dev Returns remaining of the properties of a match. Functionality had to be seperated * into 2 function calls to prevent stack too deep errors * @param _matchId the index of that match in the matches array * @return `uint` timestamp for when betting for the match closes * @return `uint` total size of the home team bet pool * @return `uint` total size of the away team bet pool * @return `uint` total size of the draw bet pool * @return `uint` the total number of bets * @return `uint8` the number of payout attempts for the match */ function getMatchBettingDetails(uint8 _matchId) public view validMatch(_matchId) returns (uint, uint, uint, uint, uint, uint8) { Match memory mtch = matches[_matchId]; return ( mtch.closeBettingTime, mtch.totalTeamABets, mtch.totalTeamBBets, mtch.totalDrawBets, mtch.numBets, payoutAttempts[_matchId] ); } /* * @dev Adds a new bet to a match with the outcome passed where there are 3 possible outcomes * homeTeam wins(1), awayTeam wins(2), draw(3). While it is possible for some matches * to end in a draw, not all matches will have the possibility of ending in a draw * this functionality will be added in front end code to prevent betting on invalid decisions. * Emits a BetPlaced event. * @param _matchId the index of the match in matches that the bet is for * @param _outcome the possible outcome for the match that this bet is betting on * @return `uint` the Id of the bet in a match's bet array */ function placeBet(uint8 _matchId, uint8 _outcome) public payable validMatch(_matchId) returns (uint) { Match storage mtch = matches[_matchId]; // A bet must be a valid option, 1, 2, or 3, and cannot be less that the minimum bet amount require( !mtch.locked && !mtch.cancelled && now < mtch.closeBettingTime && _outcome > 0 && _outcome < 4 && msg.value >= minimum_bet ); Bet memory bet = Bet(false, false, msg.value, _outcome, msg.sender); uint betId = mtch.numBets; mtch.bets[betId] = bet; mtch.numBets++; if (_outcome == 1) { mtch.totalTeamABets += msg.value; // a bit of safe math checking here assert(mtch.totalTeamABets >= msg.value); } else if (_outcome == 2) { mtch.totalTeamBBets += msg.value; assert(mtch.totalTeamBBets >= msg.value); } else { mtch.totalDrawBets += msg.value; assert(mtch.totalDrawBets >= msg.value); } // emit bet placed event emit BetPlaced(_matchId, _outcome, betId, msg.value, msg.sender); return (betId); } /* * @dev Returns the properties of a bet for a match * @param _matchId the index of that match in the matches array * @param _betId the index of that bet in the match bets array * @return `address` the address that placed the bet and thus it's owner * @return `uint` the amount that was bet * @return `uint` the option that was bet on * @return `bool` wether or not the bet had been cancelled */ function getBet(uint8 _matchId, uint _betId) public view validBet(_matchId, _betId) returns (address, uint, uint, bool, bool) { Bet memory bet = matches[_matchId].bets[_betId]; // Don't return matchId and betId since you had to know them in the first place return (bet.better, bet.amount, bet.option, bet.cancelled, bet.claimed); } /* * @dev Cancel's a bet and returns the amount - commission fee. Emits a BetCancelled event * @param _matchId the index of that match in the matches array * @param _betId the index of that bet in the match bets array */ function cancelBet(uint8 _matchId, uint _betId) public validBet(_matchId, _betId) { Match memory mtch = matches[_matchId]; require(!mtch.locked && now < mtch.closeBettingTime); Bet storage bet = matches[_matchId].bets[_betId]; // only the person who made this bet can cancel it require(!bet.cancelled && !bet.claimed && bet.better == msg.sender ); // stop re-entry just in case of malicious attack to withdraw all contract eth bet.cancelled = true; uint commission = bet.amount / 100 * commission_rate; commissions += commission; assert(commissions >= commission); if (bet.option == 1) { matches[_matchId].totalTeamABets -= bet.amount; } else if (bet.option == 2) { matches[_matchId].totalTeamBBets -= bet.amount; } else if (bet.option == 3) { matches[_matchId].totalDrawBets -= bet.amount; } bet.better.transfer(bet.amount - commission); emit BetCancelled(_matchId, _betId); } /* * @dev Betters can claim there winnings using this method or reclaim their bet * if the match was cancelled * @param _matchId the index of the match in the matches array * @param _betId the bet being claimed */ function claimBet(uint8 _matchId, uint8 _betId) public validBet(_matchId, _betId) { Match storage mtch = matches[_matchId]; Bet storage bet = mtch.bets[_betId]; // ensures the match has been locked (payout either done or bets returned) // dead man's switch to prevent bets from ever getting locked in the contrat // from insufficient funds during an oracalize query // if the match isn't locked or cancelled, then you can claim your bet after // the world cup is over (noon July 16) require((mtch.locked || now >= 1531742400) && !bet.claimed && !bet.cancelled && msg.sender == bet.better ); bet.claimed = true; if (mtch.winner == 0) { // If the match is locked with no winner set // then either it was cancelled or a winner couldn't be determined // transfer better back their bet amount bet.better.transfer(bet.amount); } else { if (bet.option != mtch.winner) { return; } uint totalPool; uint winPool; if (mtch.winner == 1) { totalPool = mtch.totalTeamBBets + mtch.totalDrawBets; // once again do some safe math assert(totalPool >= mtch.totalTeamBBets); winPool = mtch.totalTeamABets; } else if (mtch.winner == 2) { totalPool = mtch.totalTeamABets + mtch.totalDrawBets; assert(totalPool >= mtch.totalTeamABets); winPool = mtch.totalTeamBBets; } else { totalPool = mtch.totalTeamABets + mtch.totalTeamBBets; assert(totalPool >= mtch.totalTeamABets); winPool = mtch.totalDrawBets; } uint winnings = totalPool * bet.amount / winPool; // calculate commissions percentage uint commission = winnings / 100 * commission_rate; commissions += commission; assert(commissions >= commission); // return original bet amount + winnings - commission bet.better.transfer(winnings + bet.amount - commission); } emit BetClaimed(_matchId, _betId); } /* * @dev Change the commission fee for the contract. The fee can never exceed 7% * @param _newCommission the new fee rate to be charged in wei */ function changeFees(uint8 _newCommission) public onlyOwner { // Max commission is 7%, but it can be FREE!! require(_newCommission <= 7); commission_rate = _newCommission; } /* * @dev Withdraw a portion of the commission from the commission pool. * @param _amount the amount of commission to be withdrawn */ function withdrawCommissions(uint _amount) public onlyOwner { require(_amount <= commissions); commissions -= _amount; owner.transfer(_amount); } /* * @dev Destroy the contract but only after the world cup is over for a month */ function withdrawBalance() public onlyOwner { // World cup is over for a full month withdraw the full balance of the contract // and destroy it to free space on the blockchain require(now >= 1534291200); // This is 12am August 15, 2018 selfdestruct(owner); } /* * @dev Change the minimum bet amount. Just in case the price of eth skyrockets or drops. * @param _newMin the new minimum bet amount */ function changeMiniumBet(uint _newMin) public onlyOwner { minimum_bet = _newMin; } /* * @dev sets the gas price to be used for oraclize quries in the contract * @param _price the price of each gas */ function setGasPrice(uint _price) public onlyOwner { require(_price >= 20000000000 wei); oraclize_setCustomGasPrice(_price); } /* * @dev Oraclize query callback to determine the winner of the match. * @param _myid the id for the oraclize query that is being returned * @param _result the result of the query */ function __callback(bytes32 _myid, string _result) public { // only oraclize can call this method if (msg.sender != oraclize_cbAddress()) revert(); uint8 matchId = oraclizeIds[_myid]; Match storage mtch = matches[matchId]; require(!mtch.locked && !mtch.cancelled); bool firstVerification = firstStepVerified[matchId]; // If there is no result or the result is null we want to do the following if (bytes(_result).length == 0 || (keccak256(_result) == keccak256("[null, null]"))) { // If max number of attempts has been reached then return all bets if (++payoutAttempts[matchId] >= MAX_NUM_PAYOUT_ATTEMPTS) { mtch.locked = true; emit MatchFailedPayoutRelease(matchId); } else { emit MatchUpdated(matchId); string memory url; string memory querytype; uint limit; // if the contract has already verified the sportsmonks api // use football-data.org as a secondary source of truth if (firstVerification) { url = strConcat( "json(https://api.football-data.org/v1/fixtures/", matches[matchId].fixtureId, ").fixture.result.[goalsHomeTeam,goalsAwayTeam]"); querytype = "URL"; limit = secondaryGasLimit; } else { url = strConcat( "[URL] json(https://soccer.sportmonks.com/api/v2.0/fixtures/", matches[matchId].secondaryFixtureId, "?api_token=${[decrypt] BNxYykO2hsQ7iA7yRuDLSu1km6jFZwN5X87TY1BSmU30llRn8uWkJjHgx+YGytA1tmbRjb20CW0gIzcFmvq3yLZnitsvW28SPjlf+s9MK7hU+uRXqwhoW6dmWqKsBrCigrggFwMBRk4kA16jugtIr+enXHjOnAKSxd1dO4YXTCYvZc3T1pFA9PVyFFnd}).data.scores[localteam_score,visitorteam_score]"); querytype = "nested"; // use primary gas limit since that query won't payout winners on callback limit = primaryGasLimit; } bytes32 oraclizeId = oraclize_query(PAYOUT_ATTEMPT_INTERVAL, querytype, url, limit); oraclizeIds[oraclizeId] = matchId; } } else { payoutAttempts[matchId] = 0; // eg. result = "[2, 4]" strings.slice memory s = _result.toSlice(); // remove the braces from the result s = s.beyond("[".toSlice()); s = s.until("]".toSlice()); // split the string to get the two string encoded ints strings.slice memory x = s.split(", ".toSlice()); // parse them to int to get the scores uint homeScore = parseInt(s.toString()); uint awayScore = parseInt(x.toString()); uint8 matchResult; // determine the winner if (homeScore > awayScore) { matchResult = 1; } else if (homeScore < awayScore) { matchResult = 2; } else { matchResult = 3; } // if this is the query to sportsmonks if (!firstVerification) { // set pending winner and call the second source of truth pendingWinner[matchId] = matchResult; firstStepVerified[matchId] = true; url = strConcat( "json(https://api.football-data.org/v1/fixtures/", matches[matchId].fixtureId, ").fixture.result.[goalsHomeTeam,goalsAwayTeam]"); oraclizeId = oraclize_query("nested", url, secondaryGasLimit); oraclizeIds[oraclizeId] = matchId; } else { mtch.locked = true; // if one of the APIs has the teams inverted then flip the result if (matches[matchId].inverted) { if (matchResult == 1) { matchResult = 2; } else if (matchResult == 2) { matchResult = 1; } } // if the both APIs confirm the same winner then payout the winners if (pendingWinner[matchId] == matchResult) { mtch.winner = matchResult; emit MatchUpdated(matchId); } else { // else don't set a winner because a source of truth couldn't be verified // this way users can still reclaim their original bet amount emit MatchFailedPayoutRelease(matchId); } } } } function() public payable {} }
Splits the slice, setting `self` to everything after the first occurrence of `needle`, and `token` to everything before it. If `needle` does not occur in `self`, `self` is set to the empty slice, and `token` is set to the entirety of `self`. self The slice to split. needle The text to search for in `self`. token An output parameter to which the first token is written. return `token`./ Not found
function split(slice self, slice needle, slice token) internal pure returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { self._len = 0; self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; }
1,790,098
./full_match/6119/0x24e8A5449eDeBA4D6108Fa9351E563965FDaA6c4/sources/contracts/ERC4906Upgradeable.sol
See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == bytes4(0x49064906) || super.supportsInterface(interfaceId); }
16,295,890
// Sources flattened with hardhat v2.4.1 https://hardhat.org // File contracts/interfaces/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IERC20 { 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 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); } // File contracts/utils/Address.sol pragma solidity >=0.5.0 <0.9.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } */ /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require( success, "Address: unable to send value, recipient may have reverted" ); } */ } // File contracts/utils/SafeMath.sol pragma solidity >=0.5.0 <0.9.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; } } // File contracts/utils/SafeERC20.sol pragma solidity >=0.5.0 <0.9.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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File contracts/utils/ReentrancyGuard.sol pragma solidity >=0.5.0 <0.9.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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor() public { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File contracts/interfaces/IAccessControl.sol // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File contracts/utils/Context.sol pragma solidity >=0.5.0 <0.9.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. */ contract Context { function _msgSender() internal view returns (address) { return msg.sender; } function _msgData() internal view returns (bytes memory) { return msg.data; } } // File contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File contracts/interfaces/IERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File contracts/utils/ERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File contracts/utils/AccessControl.sol // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File contracts/QUAICohortFarming.sol pragma solidity =0.8.4; /* * rewardIndex keeps track of the total amount of rewards to be distributed for * each supplied unit of 'stakedToken' tokens. When used together with supplierIndex, * the total amount of rewards to be paid out to individual users can be calculated * when the user claims their rewards. * * Consider the following: * * At contract deployment, the contract has a zero 'stakedToken' balance. Immediately, a new * user, User A, deposits 1000 'stakedToken' tokens, thus increasing the total supply to * 1000 'stakedToken'. After 60 seconds, a second user, User B, deposits an additional 500 'stakedToken', * increasing the total supplied amount to 1500 'stakedToken'. * * Because all balance-changing contract calls, as well as those changing the reward * speeds, must invoke the accrueRewards function, these deposit calls trigger the * function too. The accrueRewards function considers the reward speed (denoted in * reward tokens per second), the reward and supplier reward indexes, and the supply * balance to calculate the accrued rewards. * * When User A deposits their tokens, rewards are yet to be accrued due to previous * inactivity; the elapsed time since the previous, non-existent, reward-accruing * contract call is zero, thus having a reward accrual period of zero. The block * time of the deposit transaction is saved in the contract to indicate last * activity time. * * When User B deposits their tokens, 60 seconds has elapsed since the previous * call to the accrueRewards function, indicated by the difference of the current * block time and the last activity time. In other words, up till the time of * User B's deposit, the contract has had a 60 second accrual period for the total * amount of 1000 'stakedToken' tokens at the set reward speed. Assuming a reward speed of * 5 tokens per second (denoted 5 T/s), the accrueRewards function calculates the * accrued reward per supplied unit of 'stakedToken' tokens for the elapsed time period. * This works out to ((5 T/s) / 1000 'stakedToken') * 60 s = 0.3 T/'stakedToken' during the 60 second * period. At this point, the global reward index variable is updated, increasing * its value by 0.3 T/'stakedToken', and the reward accrual block timestamp, * initialised in the previous step, is updated. * * After 90 seconds of the contract deployment, User A decides to claim their accrued * rewards. Claiming affects token balances, thus requiring an invocation of the * accrueRewards function. This time, the accrual period is 30 seconds (90 s - 60 s), * for which the reward accrued per unit of 'stakedToken' is ((5 T/s) / 1500 'stakedToken') * 30 s = 0.1 T/'stakedToken'. * The reward index is updated to 0.4 T/'stakedToken' (0.3 T/'stakedToken' + 0.1 T/'stakedToken') and the reward * accrual block timestamp is set to the current block time. * * After the reward accrual, User A's rewards are claimed by transferring the correct * amount of T tokens from the contract to User A. Because User A has not claimed any * rewards yet, their supplier index is zero, the initial value determined by the * global reward index at the time of the user's first deposit. The amount of accrued * rewards is determined by the difference between the global reward index and the * user's own supplier index; essentially, this value represents the amount of * T tokens that have been accrued per supplied 'stakedToken' during the time since the user's * last claim. User A has a supply balance of 1000 'stakedToken', thus having an unclaimed * token amount of (0.4 T/'stakedToken' - 0 T/'stakedToken') * 1000 'stakedToken' = 400 T. This amount is * transferred to User A, and their supplier index is set to the current global reward * index to indicate that all previous rewards have been accrued. * * If User B was to claim their rewards at the same time, the calculation would take * the form of (0.4 T/'stakedToken' - 0.3 T/'stakedToken') * 500 'stakedToken' = 50 T. As expected, the total amount * of accrued reward (5 T/s * 90 s = 450 T) equals to the sum of the rewards paid * out to both User A and User B (400 T + 50 T = 450 T). * * This method of reward accrual is used to minimise the contract call complexity. * If a global mapping of users to their accrued rewards was implemented instead of * the index calculations, each function call invoking the accrueRewards function * would become immensely more expensive due to having to update the rewards for each * user. In contrast, the index approach allows the update of only a single user * while still keeping track of the other's rewards. * * Because rewards can be paid in multiple assets, reward indexes, reward supplier * indexes, and reward speeds depend on the StakingReward token. */ contract QuaiCohortFarming is AccessControl, ReentrancyGuard { using SafeERC20 for IERC20; bytes32 public constant SUB_ADMIN_ROLE = keccak256("SUB_ADMIN_ROLE"); //contract address for token that users stake for rewards address public immutable stakedToken; //number of rewards tokens distributed to users uint256 public numberStakingRewards; // Sum of all supplied 'stakedToken' tokens uint256 public totalSupplies; //see explanation of accrualBlockTimestamp, rewardIndex, and supplierRewardIndex above uint256 public accrualBlockTimestamp; mapping(uint256 => uint256) public rewardIndex; mapping(address => mapping(uint256 => uint256)) public supplierRewardIndex; // Supplied 'stakedToken' for each user mapping(address => uint256) public supplyAmount; // Addresses of the ERC20 reward tokens mapping(uint256 => address) public rewardTokenAddresses; // Reward accrual speeds per reward token as tokens per second mapping(uint256 => uint256) public rewardSpeeds; // Reward rewardPeriodFinishes per reward token as UTC timestamps mapping(uint256 => uint256) public rewardPeriodFinishes; // Total unclaimed amount of each reward token promised/accrued to users mapping(uint256 => uint256) public unwithdrawnAccruedRewards; // Unclaimed staking rewards per user and token mapping(address => mapping(uint256 => uint256)) public accruedReward; //special mechanism for stakedToken to offer specific yearly multiplier. non-compounded value, where 1e18 is a multiplier of 1 (i.e. 100% APR) uint256 public stakedTokenRewardIndex = 115792089237316195423570985008687907853269984665640564039457584007913129639935; uint256 public stakedTokenYearlyReturn; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); modifier onlyAdmins() { require (hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(SUB_ADMIN_ROLE, msg.sender), "only admin"); _; } constructor( address _stakedToken, uint256 _numberStakingRewards, address[] memory _rewardTokens, uint256[] memory _rewardPeriodFinishes, address masterAdmin, address[] memory subAdmins) { require(_stakedToken != address(0)); require(_rewardTokens.length == _numberStakingRewards, "bad _rewardTokens input"); require(_rewardPeriodFinishes.length == _numberStakingRewards, "bad _rewardPeriodFinishes input"); stakedToken = _stakedToken; numberStakingRewards = _numberStakingRewards; for (uint256 i = 0; i < _numberStakingRewards; i++) { require(_rewardTokens[i] != address(0)); require(_rewardPeriodFinishes[i] > block.timestamp, "cannot set rewards to finish in past"); if (_rewardTokens[i] == _stakedToken) { stakedTokenRewardIndex = i; } rewardTokenAddresses[i] = _rewardTokens[i]; rewardPeriodFinishes[i] = _rewardPeriodFinishes[i]; } _grantRole(DEFAULT_ADMIN_ROLE, masterAdmin); for (uint256 i = 0; i < subAdmins.length; i++) { _grantRole(SUB_ADMIN_ROLE, subAdmins[i]); } } /* * Get the current amount of available rewards for claiming. * * @param rewardToken Reward token whose claimable balance to query * @return Balance of claimable reward tokens */ function getClaimableRewards(uint256 rewardTokenIndex) external view returns(uint256) { return getUserClaimableRewards(msg.sender, rewardTokenIndex); } /* * Get the current amount of available rewards for claiming. * * @param user Address of user * @param rewardToken Reward token whose claimable balance to query * @return Balance of claimable reward tokens */ function getUserClaimableRewards(address user, uint256 rewardTokenIndex) public view returns(uint256) { require(rewardTokenIndex <= numberStakingRewards, "Invalid reward token"); uint256 rewardIndexToUse = rewardIndex[rewardTokenIndex]; //imitate accrual logic without state update if (block.timestamp > accrualBlockTimestamp && totalSupplies != 0) { uint256 rewardSpeed = rewardSpeeds[rewardTokenIndex]; if (rewardSpeed != 0 && accrualBlockTimestamp < rewardPeriodFinishes[rewardTokenIndex]) { uint256 blockTimestampDelta = (min(block.timestamp, rewardPeriodFinishes[rewardTokenIndex]) - accrualBlockTimestamp); uint256 accrued = (rewardSpeeds[rewardTokenIndex] * blockTimestampDelta); IERC20 token = IERC20(rewardTokenAddresses[rewardTokenIndex]); uint256 contractTokenBalance = token.balanceOf(address(this)); if (rewardTokenIndex == stakedTokenRewardIndex) { contractTokenBalance = (contractTokenBalance > totalSupplies) ? (contractTokenBalance - totalSupplies) : 0; } uint256 remainingToDistribute = (contractTokenBalance > unwithdrawnAccruedRewards[rewardTokenIndex]) ? (contractTokenBalance - unwithdrawnAccruedRewards[rewardTokenIndex]) : 0; if (accrued > remainingToDistribute) { accrued = remainingToDistribute; } uint256 accruedPerStakedToken = (accrued * 1e36) / totalSupplies; rewardIndexToUse += accruedPerStakedToken; } } uint256 rewardIndexDelta = rewardIndexToUse - (supplierRewardIndex[user][rewardTokenIndex]); uint256 claimableReward = ((rewardIndexDelta * supplyAmount[user]) / 1e36) + accruedReward[user][rewardTokenIndex]; return claimableReward; } //returns fraction of total deposits that user controls, *multiplied by 1e18* function getUserDepositedFraction(address user) external view returns(uint256) { if (totalSupplies == 0) { return 0; } else { return (supplyAmount[user] * 1e18) / totalSupplies; } } //returns amount of token left to distribute function getRemainingTokens(uint256 rewardTokenIndex) external view returns(uint256) { if (rewardPeriodFinishes[rewardTokenIndex] <= block.timestamp) { return 0; } else { uint256 amount = (rewardPeriodFinishes[rewardTokenIndex] - block.timestamp) * rewardSpeeds[rewardTokenIndex]; uint256 bal = IERC20(rewardTokenAddresses[rewardTokenIndex]).balanceOf(address(this)); uint256 totalOwed = unwithdrawnAccruedRewards[rewardTokenIndex]; uint256 rewardSpeed = rewardSpeeds[rewardTokenIndex]; if (rewardSpeed != 0 && accrualBlockTimestamp < rewardPeriodFinishes[rewardTokenIndex]) { uint256 blockTimestampDelta = (min(block.timestamp, rewardPeriodFinishes[rewardTokenIndex]) - accrualBlockTimestamp); uint256 accrued = (rewardSpeeds[rewardTokenIndex] * blockTimestampDelta); uint256 remainingToDistribute = (bal > totalOwed) ? (bal - totalOwed) : 0; if (accrued > remainingToDistribute) { accrued = remainingToDistribute; } totalOwed += accrued; } if (rewardTokenIndex == stakedTokenRewardIndex) { totalOwed += totalSupplies; if (bal > totalOwed) { return (bal - totalOwed); } else { return 0; } } if (bal > totalOwed) { bal -= totalOwed; } else { bal = 0; } return min(amount, bal); } } function lastTimeRewardApplicable(uint256 rewardTokenIndex) public view returns (uint256) { return min(block.timestamp, rewardPeriodFinishes[rewardTokenIndex]); } function deposit(uint256 amount) external nonReentrant { IERC20 token = IERC20(stakedToken); uint256 contractBalance = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), amount); uint256 depositedAmount = token.balanceOf(address(this)) - contractBalance; distributeReward(msg.sender); totalSupplies += depositedAmount; supplyAmount[msg.sender] += depositedAmount; autoUpdateStakedTokenRewardSpeed(); } function withdraw(uint amount) public nonReentrant { require(amount <= supplyAmount[msg.sender], "Too large withdrawal"); distributeReward(msg.sender); supplyAmount[msg.sender] -= amount; totalSupplies -= amount; IERC20 token = IERC20(stakedToken); autoUpdateStakedTokenRewardSpeed(); token.safeTransfer(msg.sender, amount); } function exit() external { withdraw(supplyAmount[msg.sender]); claimRewards(); } function claimRewards() public nonReentrant { distributeReward(msg.sender); for (uint256 i = 0; i < numberStakingRewards; i++) { uint256 amount = accruedReward[msg.sender][i]; claimErc20(i, msg.sender, amount); } } function setRewardSpeed(uint256 rewardTokenIndex, uint256 speed) external onlyAdmins { if (accrualBlockTimestamp != 0) { accrueReward(); } rewardSpeeds[rewardTokenIndex] = speed; } function setRewardPeriodFinish(uint256 rewardTokenIndex, uint256 rewardPeriodFinish) external onlyAdmins { require(rewardPeriodFinish > block.timestamp, "cannot set rewards to finish in past"); rewardPeriodFinishes[rewardTokenIndex] = rewardPeriodFinish; } function setStakedTokenYearlyReturn(uint256 _stakedTokenYearlyReturn) external onlyAdmins { stakedTokenYearlyReturn = _stakedTokenYearlyReturn; autoUpdateStakedTokenRewardSpeed(); } function setStakedTokenRewardIndex(uint256 _stakedTokenRewardIndex) external onlyAdmins { require(rewardTokenAddresses[_stakedTokenRewardIndex] == stakedToken, "can only set for stakedToken"); stakedTokenRewardIndex = _stakedTokenRewardIndex; autoUpdateStakedTokenRewardSpeed(); } function addNewRewardToken(address rewardTokenAddress) external onlyAdmins { require(rewardTokenAddress != address(0), "Cannot set zero address"); numberStakingRewards += 1; rewardTokenAddresses[numberStakingRewards - 1] = rewardTokenAddress; } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant { require(tokenAddress != address(stakedToken), "Cannot withdraw the staked token"); IERC20(tokenAddress).safeTransfer(msg.sender, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /** * Update reward accrual state. * * @dev accrueReward() must be called every time the token balances * or reward speeds change */ function accrueReward() internal { if (block.timestamp == accrualBlockTimestamp) { return; } else if (totalSupplies == 0) { accrualBlockTimestamp = block.timestamp; return; } for (uint256 i = 0; i < numberStakingRewards; i += 1) { uint256 rewardSpeed = rewardSpeeds[i]; if (rewardSpeed == 0 || accrualBlockTimestamp >= rewardPeriodFinishes[i]) { continue; } uint256 blockTimestampDelta = (min(block.timestamp, rewardPeriodFinishes[i]) - accrualBlockTimestamp); uint256 accrued = (rewardSpeeds[i] * blockTimestampDelta); IERC20 token = IERC20(rewardTokenAddresses[i]); uint256 contractTokenBalance = token.balanceOf(address(this)); if (i == stakedTokenRewardIndex) { contractTokenBalance = (contractTokenBalance > totalSupplies) ? (contractTokenBalance - totalSupplies) : 0; } uint256 remainingToDistribute = (contractTokenBalance > unwithdrawnAccruedRewards[i]) ? (contractTokenBalance - unwithdrawnAccruedRewards[i]) : 0; if (accrued > remainingToDistribute) { accrued = remainingToDistribute; rewardSpeeds[i] = 0; } unwithdrawnAccruedRewards[i] += accrued; uint256 accruedPerStakedToken = (accrued * 1e36) / totalSupplies; rewardIndex[i] += accruedPerStakedToken; } accrualBlockTimestamp = block.timestamp; } /** * Calculate accrued rewards for a single account based on the reward indexes. * * @param recipient Account for which to calculate accrued rewards */ function distributeReward(address recipient) internal { accrueReward(); for (uint256 i = 0; i < numberStakingRewards; i += 1) { uint256 rewardIndexDelta = (rewardIndex[i] - supplierRewardIndex[recipient][i]); uint256 accruedAmount = (rewardIndexDelta * supplyAmount[recipient]) / 1e36; accruedReward[recipient][i] += accruedAmount; supplierRewardIndex[recipient][i] = rewardIndex[i]; } } /** * Transfer ERC20 rewards from the contract to the reward recipient. * * @param rewardTokenIndex ERC20 reward token which is claimed * @param recipient Address, whose rewards are claimed * @param amount The amount of claimed reward */ function claimErc20(uint256 rewardTokenIndex, address recipient, uint256 amount) internal { require(accruedReward[recipient][rewardTokenIndex] <= amount, "Not enough accrued rewards"); IERC20 token = IERC20(rewardTokenAddresses[rewardTokenIndex]); accruedReward[recipient][rewardTokenIndex] -= amount; unwithdrawnAccruedRewards[rewardTokenIndex] -= min(unwithdrawnAccruedRewards[rewardTokenIndex], amount); token.safeTransfer(recipient, amount); } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } //special mechanism for stakedToken to offer specific yearly multiplier. called within deposits and withdrawals to auto-update its reward speed function autoUpdateStakedTokenRewardSpeed() internal { if (rewardPeriodFinishes[stakedTokenRewardIndex] <= block.timestamp) { rewardSpeeds[stakedTokenRewardIndex] = 0; } else { //31536000 is the number of seconds in a year uint256 newRewardSpeed = totalSupplies * stakedTokenYearlyReturn / (31536000 * 1e18); rewardSpeeds[stakedTokenRewardIndex] = newRewardSpeed; } } }
Get the current amount of available rewards for claiming. rewardToken Reward token whose claimable balance to query return Balance of claimable reward tokens/
function getClaimableRewards(uint256 rewardTokenIndex) external view returns(uint256) { return getUserClaimableRewards(msg.sender, rewardTokenIndex); }
1,159,423
pragma solidity ^0.4.24; // File: contracts/GanapatiToken.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; } } /** * @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; } } /** * @title ERC223 * @dev ERC223 contract interface with ERC20 functions and events * Fully backward compatible with ERC20 * Recommended implementation used at https://github.com/Dexaran/ERC223-token-standard/tree/Recommended */ contract ERC223 { uint public totalSupply; // ERC223 and ERC20 functions and events function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title ContractReceiver * @dev Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint256 _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* * tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function if data of token transaction is a function execution */ } } /** * @title GanapatiToken * @dev GanapatiToken is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ contract GanapatiToken is ERC223, Ownable { using SafeMath for uint256; string public constant name = "G8C"; string public constant symbol = "GAEC"; uint8 public constant decimals = 8; uint256 public totalSupply = 7000000000000 * 10 ** 8; // This token is locked on the initial condition // bool public locked = true; bool public mintingFinished = false; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; // This is the mapping of locked validAddress mapping( address => bool ) public banAddresses; event Mint(address indexed to, uint256 amount); event BanAddresses(address indexed to, bool lock); event MintFinished(); // This is a modifier whether transfering token is available or not modifier isValidTransfer() { require(!banAddresses[msg.sender]); _; } modifier canMint() { require(!mintingFinished); _; } /** * @dev constructor */ constructor(address _owner) public { // set the owner address owner = _owner; // the tokens of 60% of the totalSupply is set to the sale address address sale = 0x0301e60b967A088aAd7b6a0Dd3745608068c2574; balanceOf[sale] = totalSupply.mul(60).div(100); emit Transfer(0x0, sale, balanceOf[sale]); // the tokens of 15% of the totalSupply is set to the team address address team = 0x2EeF18D08B3278f7d9C76Ffb50C279490f54c6B3; balanceOf[team] = totalSupply.mul(15).div(100); emit Transfer(0x0, team, balanceOf[team]); // the tokens of 12% of the totalSupply is set to the marketor address address marketor = 0x76FA8c2952CcA46f874a598A6064C699C634CdAA; balanceOf[marketor] = totalSupply.mul(12).div(100); emit Transfer(0x0, marketor, balanceOf[marketor]); // the tokens of 10% of the totalSupply is set to the advisor address address advisor = 0xCCbc32321baeBa72f35590B084D38adC77e74123; balanceOf[advisor] = totalSupply.mul(10).div(100); emit Transfer(0x0, advisor, balanceOf[advisor]); // the tokens of 3% of the totalSupply is set to the developer address address developer = 0x80459F7e1139d4cc97673131f2986000C024248e; balanceOf[developer] = totalSupply.mul(3).div(100); emit Transfer(0x0, developer, balanceOf[developer]); } /** * @dev Owner can lock the feature to transfer token */ function setLocked(address _to, bool _locked) onlyOwner public { banAddresses[_to] = _locked; BanAddresses(_to, _locked); } /** * @dev Standard function transfer based on ERC223 */ function transfer(address _to, uint _value, bytes _data) public isValidTransfer returns (bool success) { require(_value > 0 && _to != address(0)); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) public isValidTransfer returns (bool success) { require(_value > 0 && _to != address(0)); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @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 isValidTransfer returns (bool success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _unitAmount The amount of tokens to mint. */ function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); emit Mint(_to, _unitAmount); emit Transfer(address(0), _to, _unitAmount); return true; } /** * @dev Function to stop minting new tokens. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } }
Standard function transfer based on ERC223/
function transfer(address _to, uint _value, bytes _data) public isValidTransfer returns (bool success) { require(_value > 0 && _to != address(0)); if (isContract(_to)) { return transferToContract(_to, _value, _data); return transferToAddress(_to, _value, _data); } }
5,472,967
pragma solidity ^0.4.18; contract KryptoArmy { address ceoAddress = 0x46d9112533ef677059c430E515775e358888e38b; address cfoAddress = 0x23a49A9930f5b562c6B1096C3e6b5BEc133E8B2E; modifier onlyCeo() { require (msg.sender == ceoAddress); _; } // Struct for Army struct Army { string name; // The name of the army (invented by the user) string idArmy; // The id of the army (USA for United States) uint experiencePoints; // The experience points of the army, we will use this to handle uint256 price; // The cost of the Army in Wei (1 ETH = 1000000000000000000 Wei) uint attackBonus; // The attack bonus for the soldiers (from 0 to 10) uint defenseBonus; // The defense bonus for the soldiers (from 0 to 10) bool isForSale; // User is selling this army, it can be purchase on the marketplace address ownerAddress; // The address of the owner uint soldiersCount; // The count of all the soldiers in this army } Army[] armies; // Struct for Battles struct Battle { uint idArmyAttacking; // The id of the army attacking uint idArmyDefensing; // The id of the army defensing uint idArmyVictorious; // The id of the winning army } Battle[] battles; // Mapping army mapping (address => uint) public ownerToArmy; // Which army does this address own mapping (address => uint) public ownerArmyCount; // How many armies own this address? // Mapping weapons to army mapping (uint => uint) public armyDronesCount; mapping (uint => uint) public armyPlanesCount; mapping (uint => uint) public armyHelicoptersCount; mapping (uint => uint) public armyTanksCount; mapping (uint => uint) public armyAircraftCarriersCount; mapping (uint => uint) public armySubmarinesCount; mapping (uint => uint) public armySatelitesCount; // Mapping battles mapping (uint => uint) public armyCountBattlesWon; mapping (uint => uint) public armyCountBattlesLost; // This function creates a new army and saves it in the array with its parameters function _createArmy(string _name, string _idArmy, uint _price, uint _attackBonus, uint _defenseBonus) public onlyCeo { // We add the new army to the list and save the id in a variable armies.push(Army(_name, _idArmy, 0, _price, _attackBonus, _defenseBonus, true, address(this), 0)); } // We use this function to purchase an army with Metamask function purchaseArmy(uint _armyId) public payable { // We verify that the value paid is equal to the cost of the army require(msg.value == armies[_armyId].price); require(msg.value > 0); // We check if this army is owned by another user if(armies[_armyId].ownerAddress != address(this)) { uint CommissionOwnerValue = msg.value - (msg.value / 10); armies[_armyId].ownerAddress.transfer(CommissionOwnerValue); } // We modify the ownership of the army _ownershipArmy(_armyId); } // Function to purchase a soldier function purchaseSoldiers(uint _armyId, uint _countSoldiers) public payable { // Check that message value > 0 require(msg.value > 0); uint256 msgValue = msg.value; if(msgValue == 1000000000000000 && _countSoldiers == 1) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } else if(msgValue == 8000000000000000 && _countSoldiers == 10) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } else if(msgValue == 65000000000000000 && _countSoldiers == 100) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } else if(msgValue == 500000000000000000 && _countSoldiers == 1000) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } } // Payable function to purchase weapons function purchaseWeapons(uint _armyId, uint _weaponId, uint _bonusAttack, uint _bonusDefense ) public payable { // Check that message value > 0 uint isValid = 0; uint256 msgValue = msg.value; if(msgValue == 10000000000000000 && _weaponId == 0) { armyDronesCount[_armyId]++; isValid = 1; } else if(msgValue == 25000000000000000 && _weaponId == 1) { armyPlanesCount[_armyId]++; isValid = 1; } else if(msgValue == 25000000000000000 && _weaponId == 2) { armyHelicoptersCount[_armyId]++; isValid = 1; } else if(msgValue == 45000000000000000 && _weaponId == 3) { armyTanksCount[_armyId]++; isValid = 1; } else if(msgValue == 100000000000000000 && _weaponId == 4) { armyAircraftCarriersCount[_armyId]++; isValid = 1; } else if(msgValue == 100000000000000000 && _weaponId == 5) { armySubmarinesCount[_armyId]++; isValid = 1; } else if(msgValue == 120000000000000000 && _weaponId == 6) { armySatelitesCount[_armyId]++; isValid = 1; } // We check if the data has been verified as valid if(isValid == 1) { armies[_armyId].attackBonus = armies[_armyId].attackBonus + _bonusAttack; armies[_armyId].defenseBonus = armies[_armyId].defenseBonus + _bonusDefense; } } // We use this function to affect an army to an address (when someone purchase an army) function _ownershipArmy(uint armyId) private { // We check if the sender already own an army require (ownerArmyCount[msg.sender] == 0); // If this army has alreay been purchased we verify that the owner put it on sale require(armies[armyId].isForSale == true); // We check one more time that the price paid is the price of the army require(armies[armyId].price == msg.value); // We decrement the army count for the previous owner (in case a user is selling army on marketplace) ownerArmyCount[armies[armyId].ownerAddress]--; // We set the new army owner armies[armyId].ownerAddress = msg.sender; ownerToArmy[msg.sender] = armyId; // We increment the army count for this address ownerArmyCount[msg.sender]++; // Send event for new ownership armies[armyId].isForSale = false; } // We use this function to start a new battle function startNewBattle(uint _idArmyAttacking, uint _idArmyDefensing, uint _randomIndicatorAttack, uint _randomIndicatorDefense) public returns(uint) { // We verify that the army attacking is the army of msg.sender require (armies[_idArmyAttacking].ownerAddress == msg.sender); // Get details for army attacking uint ScoreAttack = armies[_idArmyAttacking].attackBonus * (armies[_idArmyAttacking].soldiersCount/3) + armies[_idArmyAttacking].soldiersCount + _randomIndicatorAttack; // Get details for army defending uint ScoreDefense = armies[_idArmyAttacking].defenseBonus * (armies[_idArmyDefensing].soldiersCount/2) + armies[_idArmyDefensing].soldiersCount + _randomIndicatorDefense; uint VictoriousArmy; uint ExperiencePointsGained; if(ScoreDefense >= ScoreAttack) { VictoriousArmy = _idArmyDefensing; ExperiencePointsGained = armies[_idArmyAttacking].attackBonus + 2; armies[_idArmyDefensing].experiencePoints = armies[_idArmyDefensing].experiencePoints + ExperiencePointsGained; // Increment mapping battles won armyCountBattlesWon[_idArmyDefensing]++; armyCountBattlesLost[_idArmyAttacking]++; } else { VictoriousArmy = _idArmyAttacking; ExperiencePointsGained = armies[_idArmyDefensing].defenseBonus + 2; armies[_idArmyAttacking].experiencePoints = armies[_idArmyAttacking].experiencePoints + ExperiencePointsGained; // Increment mapping battles won armyCountBattlesWon[_idArmyAttacking]++; armyCountBattlesLost[_idArmyDefensing]++; } // We add the new battle to the blockchain and save its id in a variable battles.push(Battle(_idArmyAttacking, _idArmyDefensing, VictoriousArmy)); // Send event return (VictoriousArmy); } // Owner can sell army function ownerSellArmy(uint _armyId, uint256 _amount) public { // We close the function if the user calling this function doesn't own the army require (armies[_armyId].ownerAddress == msg.sender); require (_amount > 0); require (armies[_armyId].isForSale == false); armies[_armyId].isForSale = true; armies[_armyId].price = _amount; } // Owner remove army from marketplace function ownerCancelArmyMarketplace(uint _armyId) public { require (armies[_armyId].ownerAddress == msg.sender); require (armies[_armyId].isForSale == true); armies[_armyId].isForSale = false; } // Function to return all the value of an army function getArmyFullData(uint armyId) public view returns(string, string, uint, uint256, uint, uint, bool) { string storage ArmyName = armies[armyId].name; string storage ArmyId = armies[armyId].idArmy; uint ArmyExperiencePoints = armies[armyId].experiencePoints; uint256 ArmyPrice = armies[armyId].price; uint ArmyAttack = armies[armyId].attackBonus; uint ArmyDefense = armies[armyId].defenseBonus; bool ArmyIsForSale = armies[armyId].isForSale; return (ArmyName, ArmyId, ArmyExperiencePoints, ArmyPrice, ArmyAttack, ArmyDefense, ArmyIsForSale); } // Function to return the owner of the army function getArmyOwner(uint armyId) public view returns(address, bool) { return (armies[armyId].ownerAddress, armies[armyId].isForSale); } // Function to return the owner of the army function getSenderArmyDetails() public view returns(uint, string) { uint ArmyId = ownerToArmy[msg.sender]; string storage ArmyName = armies[ArmyId].name; return (ArmyId, ArmyName); } // Function to return the owner army count function getSenderArmyCount() public view returns(uint) { uint ArmiesCount = ownerArmyCount[msg.sender]; return (ArmiesCount); } // Function to return the soldiers count of an army function getArmySoldiersCount(uint armyId) public view returns(uint) { uint SoldiersCount = armies[armyId].soldiersCount; return (SoldiersCount); } // Return an array with the weapons of the army function getWeaponsArmy1(uint armyId) public view returns(uint, uint, uint, uint) { uint CountDrones = armyDronesCount[armyId]; uint CountPlanes = armyPlanesCount[armyId]; uint CountHelicopters = armyHelicoptersCount[armyId]; uint CountTanks = armyTanksCount[armyId]; return (CountDrones, CountPlanes, CountHelicopters, CountTanks); } function getWeaponsArmy2(uint armyId) public view returns(uint, uint, uint) { uint CountAircraftCarriers = armyAircraftCarriersCount[armyId]; uint CountSubmarines = armySubmarinesCount[armyId]; uint CountSatelites = armySatelitesCount[armyId]; return (CountAircraftCarriers, CountSubmarines, CountSatelites); } // Retrieve count battles won function getArmyBattles(uint _armyId) public view returns(uint, uint) { return (armyCountBattlesWon[_armyId], armyCountBattlesLost[_armyId]); } // Retrieve the details of a battle function getDetailsBattles(uint battleId) public view returns(uint, uint, uint, string, string) { return (battles[battleId].idArmyAttacking, battles[battleId].idArmyDefensing, battles[battleId].idArmyVictorious, armies[battles[battleId].idArmyAttacking].idArmy, armies[battles[battleId].idArmyDefensing].idArmy); } // Get battles count function getBattlesCount() public view returns(uint) { return (battles.length); } // To withdraw fund from this contract function withdraw(uint amount, uint who) public onlyCeo returns(bool) { require(amount <= this.balance); if(who == 0) { ceoAddress.transfer(amount); } else { cfoAddress.transfer(amount); } return true; } // Initial function to create the 100 armies with their attributes function KryptoArmy() public onlyCeo { // 1. USA _createArmy("United States", "USA", 550000000000000000, 8, 9); // 2. North Korea _createArmy("North Korea", "NK", 500000000000000000, 10, 5); // 3. Russia _createArmy("Russia", "RUS", 450000000000000000, 8, 7); // 4. China _createArmy("China", "CHN", 450000000000000000, 7, 8); // 5. Japan _createArmy("Japan", "JPN", 420000000000000000, 7, 7); // 6. France _createArmy("France", "FRA", 400000000000000000, 6, 8); // 7. Germany _createArmy("Germany", "GER", 400000000000000000, 7, 6); // 8. India _createArmy("India", "IND", 400000000000000000, 7, 6); // 9. United Kingdom _createArmy("United Kingdom", "UK", 350000000000000000, 5, 7); // 10. South Korea _createArmy("South Korea", "SK", 350000000000000000, 6, 6); // 11. Turkey _createArmy("Turkey", "TUR", 300000000000000000, 7, 4); // 12. Italy //_createArmy("Italy", "ITA", 280000000000000000, 5, 5); } }
Function to return the owner of the army
function getArmyOwner(uint armyId) public view returns(address, bool) { return (armies[armyId].ownerAddress, armies[armyId].isForSale); }
13,131,599
pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getBountyAmount() public view returns(uint256); } contract EmalBounty is Ownable { using SafeMath for uint256; // The token being sold EmalToken public token; // Bounty contract state Data structures enum State { Active, Closed } // contains current state of bounty contract State public state; // Bounty limit in EMAL tokens uint256 public bountyLimit; // Count of total number of EML tokens that have been currently allocated to bounty users uint256 public totalTokensAllocated = 0; // Count of allocated tokens (not issued only allocated) for each bounty user mapping(address => uint256) public allocatedTokens; // Count of allocated tokens issued to each bounty user. mapping(address => uint256) public amountOfAllocatedTokensGivenOut; /** @dev Event fired when tokens are allocated to a bounty user account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** * @dev Event fired when EML tokens are sent to a bounty user * @param beneficiary Address where the allocated tokens were sent * @param tokenCount The amount of tokens that were sent */ event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount); /** @param _token Address of the token that will be rewarded for the investors */ constructor(address _token) public { require(_token != address(0)); owner = msg.sender; token = EmalToken(_token); state = State.Active; bountyLimit = token.getBountyAmount(); } /* Do not accept ETH */ function() external payable { revert(); } function closeBounty() public onlyOwner returns(bool){ require( state!=State.Closed ); state = State.Closed; return true; } /** @dev Public function to check if bounty isActive or not * @return True if Bounty event has ended */ function isBountyActive() public view returns(bool) { if (state==State.Active && totalTokensAllocated<bountyLimit){ return true; } else { return false; } } /** @dev Allocates tokens to a bounty user * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensAllocated.add(tokens) > bountyLimit) { tokens = bountyLimit.sub(totalTokensAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool isActive = state==State.Active; bool positiveAllocation = tokenCount>0; bool bountyLimitNotReached = totalTokensAllocated<bountyLimit; return isActive && positiveAllocation && bountyLimitNotReached; } /** @dev Remove tokens from a bounty user's allocation. * @dev Used in game based bounty allocation, automatically called from the Sails app * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be deallocated to this address */ function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor or the bounty user */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } /** @dev Bounty users will be issued EML Tokens by the sails api, * @dev after the Bounty has ended to their address * @param beneficiary address of the bounty user */ function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) { require(beneficiary!=address(0)); require(allocatedTokens[beneficiary]>0); uint256 tokensToSend = allocatedTokens[beneficiary]; allocatedTokens[beneficiary] = 0; amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend); assert(token.transferFrom(owner, beneficiary, tokensToSend)); emit IssuedAllocatedTokens(beneficiary, tokensToSend); return true; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getCrowdsaleAmount() public view returns(uint256); function setStartTimeForTokenTransfers(uint256 _startTime) external; } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalCrowdsale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Switched to true once token contract is notified of when to enable token transfers bool private isStartTimeSetForTokenTransfers = false; // Hard cap in EMAL tokens uint256 public hardCap; // Soft cap in EMAL tokens uint256 constant public soft_cap = 50000000 * (10 ** 18); // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Crowdsale uint256 public totalEtherRaisedByCrowdsale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Crowdsale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** * @dev Event for refund logging * @param receiver The address that received the refund * @param amount The amount that is being refunded (in wei) */ event Refund(address indexed receiver, uint256 amount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 25; uint256 bonusPercent2 = 15; uint256 bonusPercent3 = 0; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** * @dev public function that is used to determine the current rate for token / ETH conversion * @dev there exists a case where rate cant be set to 0, which is fine. * @return The current token rate */ function getRate() public view returns(uint256) { require( priceOfEMLTokenInUSDPenny !=0 ); require( priceOfEthInUSD !=0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { if (now <= (startTime + 1 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100); } } return rate; } /** @dev Initialise the Crowdsale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getCrowdsaleAmount(); } /** @dev Fallback function that can be used to buy EML tokens. Or in * case of the owner, return ether to allow refunds in case crowdsale * ended or paused and didnt reach soft_cap. */ function() external payable { if (msg.sender == multisigWallet) { require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap); } else { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { revert(); } } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Update token contract. _postValidationUpdateTokenContract(); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } function _postValidationUpdateTokenContract() internal { /** @dev If hard cap is reachde allow token transfers after two weeks * @dev Allow users to transfer tokens only after hardCap is reached * @dev Notiy token contract about startTime to start transfers */ if (totalTokensSoldandAllocated == hardCap) { token.setStartTimeForTokenTransfers(now + 2 weeks); } /** @dev If its the first token sold or allocated then set s, allow after 2 weeks * @dev Allow users to transfer tokens only after ICO crowdsale ends. * @dev Notify token contract about sale end time */ if (!isStartTimeSetForTokenTransfers) { isStartTimeSetForTokenTransfers = true; token.setStartTimeForTokenTransfers(endTime + 2 weeks); } } /** @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Crowdsale isActive or not * @return True if Crowdsale event has ended */ function isCrowdsaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev Returns ether to token holders in case soft cap is not reached. */ function claimRefund() public whenNotPaused onlyOwner { require(now>endTime); require(totalTokensSoldandAllocated<soft_cap); uint256 amount = etherInvestments[msg.sender]; if (address(this).balance >= amount) { etherInvestments[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit Refund(msg.sender, amount); } } } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); /* Update token contract. */ _postValidationUpdateTokenContract(); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getPresaleAmount() public view returns(uint256); } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalPresale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Hard cap in EMAL tokens uint256 public hardCap; // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Presale uint256 public totalEtherRaisedByPresale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Presale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 35; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** @dev public function that is used to determine the current rate for ETH to EML conversion * @return The current token rate */ function getRate() public view returns(uint256) { require(priceOfEMLTokenInUSDPenny > 0 ); require(priceOfEthInUSD > 0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } return rate; } /** @dev Initialise the Presale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getPresaleAmount(); } /** @dev Fallback function that can be used to buy tokens. */ function() external payable { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { /* Do not accept ETH */ revert(); } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } /** * @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Presale isActive or not * @return True if Presale event has ended */ function isPresaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import './StandardToken.sol'; import './Ownable.sol'; contract EmalToken is StandardToken, Ownable { using SafeMath for uint256; string public constant symbol = "EML"; string public constant name = "e-Mal Token"; uint8 public constant decimals = 18; // Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals); // 24% of initial supply uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals); // 60% of inital supply uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals); uint256 private initialSupply = minting_capped_amount; address public presaleAddress; address public crowdsaleAddress; address public vestingAddress; address public bountyAddress; /** @dev Defines the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ uint256 public startTimeForTransfers; /** @dev to cap the total number of tokens that will ever be newly minted * owner has to stop the minting by setting this variable to true. */ bool public mintingFinished = false; /** @dev Miniting Essentials functions as per OpenZeppelin standards */ modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** @dev to prevent malicious use of EML tokens and to comply with Anti * Money laundering regulations EML tokens can be frozen. */ mapping (address => bool) public frozenAccount; /** @dev This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); constructor() public { startTimeForTransfers = now - 210 days; _totalSupply = initialSupply; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); } /* Do not accept ETH */ function() public payable { revert(); } /** @dev Basic setters and getters to allocate tokens for vesting factory, presale * crowdsale and bounty this is done so that no need of actually transferring EML * tokens to sale contracts and hence preventing EML tokens from the risk of being * locked out in future inside the subcontracts. */ function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); } function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner { crowdsaleAddress = _crowdsaleAddress; assert(approve(crowdsaleAddress, crowdsale_amount)); } function setVestingAddress(address _vestingAddress) external onlyOwner { vestingAddress = _vestingAddress; assert(approve(vestingAddress, vesting_amount)); } function setBountyAddress(address _bountyAddress) external onlyOwner { bountyAddress = _bountyAddress; assert(approve(bountyAddress, bounty_amount)); } function getPresaleAmount() internal pure returns(uint256) { return presale_amount; } function getCrowdsaleAmount() internal pure returns(uint256) { return crowdsale_amount; } function getVestingAmount() internal pure returns(uint256) { return vesting_amount; } function getBountyAmount() internal pure returns(uint256) { return bounty_amount; } /** @dev Sets the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external { require(msg.sender == crowdsaleAddress); if (_startTimeForTransfers < startTimeForTransfers) { startTimeForTransfers = _startTimeForTransfers; } } /** @dev Transfer possible only after ICO ends and Frozen accounts * wont be able to transfer funds to other any other account and viz. * @notice added safeTransfer functionality */ function transfer(address _to, uint256 _value) public returns(bool) { require(now >= startTimeForTransfers); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(super.transfer(_to, _value)); return true; } /** @dev Only owner's tokens can be transferred before Crowdsale ends. * beacuse the inital supply of EML is allocated to owners acc and later * distributed to various subcontracts. * @notice added safeTransferFrom functionality */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); if (now < startTimeForTransfers) { require(_from == owner); } require(super.transferFrom(_from, _to, _value)); return true; } /** @notice added safeApprove functionality */ function approve(address spender, uint256 tokens) public returns (bool){ require(super.approve(spender, tokens)); return true; } /** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyOwner { require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) { require(_totalSupply.add(_amount) <= minting_capped_amount); _totalSupply = _totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import './Ownable.sol'; /** @notice This contract provides support for whitelisting addresses. * only whitelisted addresses are allowed to send ether and buy tokens * during preSale and Pulic crowdsale. * @dev after deploying contract, deploy Presale / Crowdsale contract using * EmalWhitelist address. To allow claim refund functionality and allow wallet * owner efatoora to send ether to Crowdsale contract for refunds add wallet * address to whitelist. */ contract EmalWhitelist is Ownable { mapping(address => bool) whitelist; event AddToWhitelist(address investorAddr); event RemoveFromWhitelist(address investorAddr); /** @dev Throws if operator is not whitelisted. */ modifier onlyIfWhitelisted(address investorAddr) { require(whitelist[investorAddr]); _; } constructor() public { owner = msg.sender; } /** @dev Returns if an address is whitelisted or not */ function isWhitelisted(address investorAddr) public view returns(bool whitelisted) { return whitelist[investorAddr]; } /** * @dev Adds an investor to whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = true; return true; } /** * @dev Removes an investor's address from whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; } } pragma solidity 0.4.24; contract ERC20Token { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity 0.4.24; import "./Ownable.sol"; /* Pausable contract */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } pragma solidity 0.4.24; import './ERC20Token.sol'; import './SafeMath.sol'; contract StandardToken is ERC20Token { using SafeMath for uint256; // Global variable to store total number of tokens passed from EmalToken.sol uint256 _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint256){ return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool){ require(to != address(0)); require(tokens > 0 && tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // Transfer tokens from one address to another function transferFrom(address from, address to, uint256 tokens) public returns (bool success){ require(to != address(0)); require(tokens > 0 && tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. function approve(address spender, uint256 tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // Function to check the amount of tokens that an owner allowed to a spender. function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // Increase the amount of tokens that an owner allowed to a spender. // approve should be called when allowed[spender] == 0. // To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) function increaseApproval(address spender, uint256 addedValue) public returns (bool) { allowed[msg.sender][spender] = (allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } // Decrease the amount of tokens that an owner allowed to a spender. // approve should be called when allowed[spender] == 0. // To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) function decreaseApproval(address spender, uint256 subtractedValue ) public returns (bool){ uint256 oldValue = allowed[msg.sender][spender]; if (subtractedValue >= oldValue) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getBountyAmount() public view returns(uint256); } contract EmalBounty is Ownable { using SafeMath for uint256; // The token being sold EmalToken public token; // Bounty contract state Data structures enum State { Active, Closed } // contains current state of bounty contract State public state; // Bounty limit in EMAL tokens uint256 public bountyLimit; // Count of total number of EML tokens that have been currently allocated to bounty users uint256 public totalTokensAllocated = 0; // Count of allocated tokens (not issued only allocated) for each bounty user mapping(address => uint256) public allocatedTokens; // Count of allocated tokens issued to each bounty user. mapping(address => uint256) public amountOfAllocatedTokensGivenOut; /** @dev Event fired when tokens are allocated to a bounty user account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** * @dev Event fired when EML tokens are sent to a bounty user * @param beneficiary Address where the allocated tokens were sent * @param tokenCount The amount of tokens that were sent */ event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount); /** @param _token Address of the token that will be rewarded for the investors */ constructor(address _token) public { require(_token != address(0)); owner = msg.sender; token = EmalToken(_token); state = State.Active; bountyLimit = token.getBountyAmount(); } /* Do not accept ETH */ function() external payable { revert(); } function closeBounty() public onlyOwner returns(bool){ require( state!=State.Closed ); state = State.Closed; return true; } /** @dev Public function to check if bounty isActive or not * @return True if Bounty event has ended */ function isBountyActive() public view returns(bool) { if (state==State.Active && totalTokensAllocated<bountyLimit){ return true; } else { return false; } } /** @dev Allocates tokens to a bounty user * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensAllocated.add(tokens) > bountyLimit) { tokens = bountyLimit.sub(totalTokensAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool isActive = state==State.Active; bool positiveAllocation = tokenCount>0; bool bountyLimitNotReached = totalTokensAllocated<bountyLimit; return isActive && positiveAllocation && bountyLimitNotReached; } /** @dev Remove tokens from a bounty user's allocation. * @dev Used in game based bounty allocation, automatically called from the Sails app * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be deallocated to this address */ function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor or the bounty user */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } /** @dev Bounty users will be issued EML Tokens by the sails api, * @dev after the Bounty has ended to their address * @param beneficiary address of the bounty user */ function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) { require(beneficiary!=address(0)); require(allocatedTokens[beneficiary]>0); uint256 tokensToSend = allocatedTokens[beneficiary]; allocatedTokens[beneficiary] = 0; amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend); assert(token.transferFrom(owner, beneficiary, tokensToSend)); emit IssuedAllocatedTokens(beneficiary, tokensToSend); return true; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getCrowdsaleAmount() public view returns(uint256); function setStartTimeForTokenTransfers(uint256 _startTime) external; } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalCrowdsale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Switched to true once token contract is notified of when to enable token transfers bool private isStartTimeSetForTokenTransfers = false; // Hard cap in EMAL tokens uint256 public hardCap; // Soft cap in EMAL tokens uint256 constant public soft_cap = 50000000 * (10 ** 18); // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Crowdsale uint256 public totalEtherRaisedByCrowdsale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Crowdsale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** * @dev Event for refund logging * @param receiver The address that received the refund * @param amount The amount that is being refunded (in wei) */ event Refund(address indexed receiver, uint256 amount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 25; uint256 bonusPercent2 = 15; uint256 bonusPercent3 = 0; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** * @dev public function that is used to determine the current rate for token / ETH conversion * @dev there exists a case where rate cant be set to 0, which is fine. * @return The current token rate */ function getRate() public view returns(uint256) { require( priceOfEMLTokenInUSDPenny !=0 ); require( priceOfEthInUSD !=0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { if (now <= (startTime + 1 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100); } } return rate; } /** @dev Initialise the Crowdsale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getCrowdsaleAmount(); } /** @dev Fallback function that can be used to buy EML tokens. Or in * case of the owner, return ether to allow refunds in case crowdsale * ended or paused and didnt reach soft_cap. */ function() external payable { if (msg.sender == multisigWallet) { require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap); } else { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { revert(); } } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Update token contract. _postValidationUpdateTokenContract(); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } function _postValidationUpdateTokenContract() internal { /** @dev If hard cap is reachde allow token transfers after two weeks * @dev Allow users to transfer tokens only after hardCap is reached * @dev Notiy token contract about startTime to start transfers */ if (totalTokensSoldandAllocated == hardCap) { token.setStartTimeForTokenTransfers(now + 2 weeks); } /** @dev If its the first token sold or allocated then set s, allow after 2 weeks * @dev Allow users to transfer tokens only after ICO crowdsale ends. * @dev Notify token contract about sale end time */ if (!isStartTimeSetForTokenTransfers) { isStartTimeSetForTokenTransfers = true; token.setStartTimeForTokenTransfers(endTime + 2 weeks); } } /** @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Crowdsale isActive or not * @return True if Crowdsale event has ended */ function isCrowdsaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev Returns ether to token holders in case soft cap is not reached. */ function claimRefund() public whenNotPaused onlyOwner { require(now>endTime); require(totalTokensSoldandAllocated<soft_cap); uint256 amount = etherInvestments[msg.sender]; if (address(this).balance >= amount) { etherInvestments[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit Refund(msg.sender, amount); } } } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); /* Update token contract. */ _postValidationUpdateTokenContract(); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getPresaleAmount() public view returns(uint256); } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalPresale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Hard cap in EMAL tokens uint256 public hardCap; // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Presale uint256 public totalEtherRaisedByPresale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Presale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 35; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** @dev public function that is used to determine the current rate for ETH to EML conversion * @return The current token rate */ function getRate() public view returns(uint256) { require(priceOfEMLTokenInUSDPenny > 0 ); require(priceOfEthInUSD > 0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } return rate; } /** @dev Initialise the Presale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getPresaleAmount(); } /** @dev Fallback function that can be used to buy tokens. */ function() external payable { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { /* Do not accept ETH */ revert(); } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } /** * @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Presale isActive or not * @return True if Presale event has ended */ function isPresaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import './StandardToken.sol'; import './Ownable.sol'; contract EmalToken is StandardToken, Ownable { using SafeMath for uint256; string public constant symbol = "EML"; string public constant name = "e-Mal Token"; uint8 public constant decimals = 18; // Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals); // 24% of initial supply uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals); // 60% of inital supply uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals); uint256 private initialSupply = minting_capped_amount; address public presaleAddress; address public crowdsaleAddress; address public vestingAddress; address public bountyAddress; /** @dev Defines the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ uint256 public startTimeForTransfers; /** @dev to cap the total number of tokens that will ever be newly minted * owner has to stop the minting by setting this variable to true. */ bool public mintingFinished = false; /** @dev Miniting Essentials functions as per OpenZeppelin standards */ modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** @dev to prevent malicious use of EML tokens and to comply with Anti * Money laundering regulations EML tokens can be frozen. */ mapping (address => bool) public frozenAccount; /** @dev This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); constructor() public { startTimeForTransfers = now - 210 days; _totalSupply = initialSupply; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); } /* Do not accept ETH */ function() public payable { revert(); } /** @dev Basic setters and getters to allocate tokens for vesting factory, presale * crowdsale and bounty this is done so that no need of actually transferring EML * tokens to sale contracts and hence preventing EML tokens from the risk of being * locked out in future inside the subcontracts. */ function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); } function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner { crowdsaleAddress = _crowdsaleAddress; assert(approve(crowdsaleAddress, crowdsale_amount)); } function setVestingAddress(address _vestingAddress) external onlyOwner { vestingAddress = _vestingAddress; assert(approve(vestingAddress, vesting_amount)); } function setBountyAddress(address _bountyAddress) external onlyOwner { bountyAddress = _bountyAddress; assert(approve(bountyAddress, bounty_amount)); } function getPresaleAmount() internal pure returns(uint256) { return presale_amount; } function getCrowdsaleAmount() internal pure returns(uint256) { return crowdsale_amount; } function getVestingAmount() internal pure returns(uint256) { return vesting_amount; } function getBountyAmount() internal pure returns(uint256) { return bounty_amount; } /** @dev Sets the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external { require(msg.sender == crowdsaleAddress); if (_startTimeForTransfers < startTimeForTransfers) { startTimeForTransfers = _startTimeForTransfers; } } /** @dev Transfer possible only after ICO ends and Frozen accounts * wont be able to transfer funds to other any other account and viz. * @notice added safeTransfer functionality */ function transfer(address _to, uint256 _value) public returns(bool) { require(now >= startTimeForTransfers); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(super.transfer(_to, _value)); return true; } /** @dev Only owner's tokens can be transferred before Crowdsale ends. * beacuse the inital supply of EML is allocated to owners acc and later * distributed to various subcontracts. * @notice added safeTransferFrom functionality */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); if (now < startTimeForTransfers) { require(_from == owner); } require(super.transferFrom(_from, _to, _value)); return true; } /** @notice added safeApprove functionality */ function approve(address spender, uint256 tokens) public returns (bool){ require(super.approve(spender, tokens)); return true; } /** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyOwner { require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) { require(_totalSupply.add(_amount) <= minting_capped_amount); _totalSupply = _totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import './Ownable.sol'; /** @notice This contract provides support for whitelisting addresses. * only whitelisted addresses are allowed to send ether and buy tokens * during preSale and Pulic crowdsale. * @dev after deploying contract, deploy Presale / Crowdsale contract using * EmalWhitelist address. To allow claim refund functionality and allow wallet * owner efatoora to send ether to Crowdsale contract for refunds add wallet * address to whitelist. */ contract EmalWhitelist is Ownable { mapping(address => bool) whitelist; event AddToWhitelist(address investorAddr); event RemoveFromWhitelist(address investorAddr); /** @dev Throws if operator is not whitelisted. */ modifier onlyIfWhitelisted(address investorAddr) { require(whitelist[investorAddr]); _; } constructor() public { owner = msg.sender; } /** @dev Returns if an address is whitelisted or not */ function isWhitelisted(address investorAddr) public view returns(bool whitelisted) { return whitelist[investorAddr]; } /** * @dev Adds an investor to whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = true; return true; } /** * @dev Removes an investor's address from whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; } } pragma solidity 0.4.24; contract ERC20Token { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity 0.4.24; import "./Ownable.sol"; /* Pausable contract */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } pragma solidity 0.4.24; import './ERC20Token.sol'; import './SafeMath.sol'; contract StandardToken is ERC20Token { using SafeMath for uint256; // Global variable to store total number of tokens passed from EmalToken.sol uint256 _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint256){ return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool){ require(to != address(0)); require(tokens > 0 && tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // Transfer tokens from one address to another function transferFrom(address from, address to, uint256 tokens) public returns (bool success){ require(to != address(0)); require(tokens > 0 && tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. function approve(address spender, uint256 tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // Function to check the amount of tokens that an owner allowed to a spender. function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // Increase the amount of tokens that an owner allowed to a spender. // approve should be called when allowed[spender] == 0. // To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) function increaseApproval(address spender, uint256 addedValue) public returns (bool) { allowed[msg.sender][spender] = (allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } // Decrease the amount of tokens that an owner allowed to a spender. // approve should be called when allowed[spender] == 0. // To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) function decreaseApproval(address spender, uint256 subtractedValue ) public returns (bool){ uint256 oldValue = allowed[msg.sender][spender]; if (subtractedValue >= oldValue) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getBountyAmount() public view returns(uint256); } contract EmalBounty is Ownable { using SafeMath for uint256; // The token being sold EmalToken public token; // Bounty contract state Data structures enum State { Active, Closed } // contains current state of bounty contract State public state; // Bounty limit in EMAL tokens uint256 public bountyLimit; // Count of total number of EML tokens that have been currently allocated to bounty users uint256 public totalTokensAllocated = 0; // Count of allocated tokens (not issued only allocated) for each bounty user mapping(address => uint256) public allocatedTokens; // Count of allocated tokens issued to each bounty user. mapping(address => uint256) public amountOfAllocatedTokensGivenOut; /** @dev Event fired when tokens are allocated to a bounty user account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** * @dev Event fired when EML tokens are sent to a bounty user * @param beneficiary Address where the allocated tokens were sent * @param tokenCount The amount of tokens that were sent */ event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount); /** @param _token Address of the token that will be rewarded for the investors */ constructor(address _token) public { require(_token != address(0)); owner = msg.sender; token = EmalToken(_token); state = State.Active; bountyLimit = token.getBountyAmount(); } /* Do not accept ETH */ function() external payable { revert(); } function closeBounty() public onlyOwner returns(bool){ require( state!=State.Closed ); state = State.Closed; return true; } /** @dev Public function to check if bounty isActive or not * @return True if Bounty event has ended */ function isBountyActive() public view returns(bool) { if (state==State.Active && totalTokensAllocated<bountyLimit){ return true; } else { return false; } } /** @dev Allocates tokens to a bounty user * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensAllocated.add(tokens) > bountyLimit) { tokens = bountyLimit.sub(totalTokensAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool isActive = state==State.Active; bool positiveAllocation = tokenCount>0; bool bountyLimitNotReached = totalTokensAllocated<bountyLimit; return isActive && positiveAllocation && bountyLimitNotReached; } /** @dev Remove tokens from a bounty user's allocation. * @dev Used in game based bounty allocation, automatically called from the Sails app * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be deallocated to this address */ function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor or the bounty user */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } /** @dev Bounty users will be issued EML Tokens by the sails api, * @dev after the Bounty has ended to their address * @param beneficiary address of the bounty user */ function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) { require(beneficiary!=address(0)); require(allocatedTokens[beneficiary]>0); uint256 tokensToSend = allocatedTokens[beneficiary]; allocatedTokens[beneficiary] = 0; amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend); assert(token.transferFrom(owner, beneficiary, tokensToSend)); emit IssuedAllocatedTokens(beneficiary, tokensToSend); return true; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getCrowdsaleAmount() public view returns(uint256); function setStartTimeForTokenTransfers(uint256 _startTime) external; } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalCrowdsale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Switched to true once token contract is notified of when to enable token transfers bool private isStartTimeSetForTokenTransfers = false; // Hard cap in EMAL tokens uint256 public hardCap; // Soft cap in EMAL tokens uint256 constant public soft_cap = 50000000 * (10 ** 18); // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Crowdsale uint256 public totalEtherRaisedByCrowdsale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Crowdsale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** * @dev Event for refund logging * @param receiver The address that received the refund * @param amount The amount that is being refunded (in wei) */ event Refund(address indexed receiver, uint256 amount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 25; uint256 bonusPercent2 = 15; uint256 bonusPercent3 = 0; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** * @dev public function that is used to determine the current rate for token / ETH conversion * @dev there exists a case where rate cant be set to 0, which is fine. * @return The current token rate */ function getRate() public view returns(uint256) { require( priceOfEMLTokenInUSDPenny !=0 ); require( priceOfEthInUSD !=0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { if (now <= (startTime + 1 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100); } } return rate; } /** @dev Initialise the Crowdsale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getCrowdsaleAmount(); } /** @dev Fallback function that can be used to buy EML tokens. Or in * case of the owner, return ether to allow refunds in case crowdsale * ended or paused and didnt reach soft_cap. */ function() external payable { if (msg.sender == multisigWallet) { require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap); } else { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { revert(); } } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Update token contract. _postValidationUpdateTokenContract(); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } function _postValidationUpdateTokenContract() internal { /** @dev If hard cap is reachde allow token transfers after two weeks * @dev Allow users to transfer tokens only after hardCap is reached * @dev Notiy token contract about startTime to start transfers */ if (totalTokensSoldandAllocated == hardCap) { token.setStartTimeForTokenTransfers(now + 2 weeks); } /** @dev If its the first token sold or allocated then set s, allow after 2 weeks * @dev Allow users to transfer tokens only after ICO crowdsale ends. * @dev Notify token contract about sale end time */ if (!isStartTimeSetForTokenTransfers) { isStartTimeSetForTokenTransfers = true; token.setStartTimeForTokenTransfers(endTime + 2 weeks); } } /** @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Crowdsale isActive or not * @return True if Crowdsale event has ended */ function isCrowdsaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev Returns ether to token holders in case soft cap is not reached. */ function claimRefund() public whenNotPaused onlyOwner { require(now>endTime); require(totalTokensSoldandAllocated<soft_cap); uint256 amount = etherInvestments[msg.sender]; if (address(this).balance >= amount) { etherInvestments[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit Refund(msg.sender, amount); } } } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); /* Update token contract. */ _postValidationUpdateTokenContract(); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getPresaleAmount() public view returns(uint256); } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalPresale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Hard cap in EMAL tokens uint256 public hardCap; // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Presale uint256 public totalEtherRaisedByPresale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Presale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 35; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** @dev public function that is used to determine the current rate for ETH to EML conversion * @return The current token rate */ function getRate() public view returns(uint256) { require(priceOfEMLTokenInUSDPenny > 0 ); require(priceOfEthInUSD > 0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } return rate; } /** @dev Initialise the Presale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getPresaleAmount(); } /** @dev Fallback function that can be used to buy tokens. */ function() external payable { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { /* Do not accept ETH */ revert(); } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } /** * @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Presale isActive or not * @return True if Presale event has ended */ function isPresaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import './StandardToken.sol'; import './Ownable.sol'; contract EmalToken is StandardToken, Ownable { using SafeMath for uint256; string public constant symbol = "EML"; string public constant name = "e-Mal Token"; uint8 public constant decimals = 18; // Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals); // 24% of initial supply uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals); // 60% of inital supply uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals); uint256 private initialSupply = minting_capped_amount; address public presaleAddress; address public crowdsaleAddress; address public vestingAddress; address public bountyAddress; /** @dev Defines the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ uint256 public startTimeForTransfers; /** @dev to cap the total number of tokens that will ever be newly minted * owner has to stop the minting by setting this variable to true. */ bool public mintingFinished = false; /** @dev Miniting Essentials functions as per OpenZeppelin standards */ modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** @dev to prevent malicious use of EML tokens and to comply with Anti * Money laundering regulations EML tokens can be frozen. */ mapping (address => bool) public frozenAccount; /** @dev This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); constructor() public { startTimeForTransfers = now - 210 days; _totalSupply = initialSupply; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); } /* Do not accept ETH */ function() public payable { revert(); } /** @dev Basic setters and getters to allocate tokens for vesting factory, presale * crowdsale and bounty this is done so that no need of actually transferring EML * tokens to sale contracts and hence preventing EML tokens from the risk of being * locked out in future inside the subcontracts. */ function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); } function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner { crowdsaleAddress = _crowdsaleAddress; assert(approve(crowdsaleAddress, crowdsale_amount)); } function setVestingAddress(address _vestingAddress) external onlyOwner { vestingAddress = _vestingAddress; assert(approve(vestingAddress, vesting_amount)); } function setBountyAddress(address _bountyAddress) external onlyOwner { bountyAddress = _bountyAddress; assert(approve(bountyAddress, bounty_amount)); } function getPresaleAmount() internal pure returns(uint256) { return presale_amount; } function getCrowdsaleAmount() internal pure returns(uint256) { return crowdsale_amount; } function getVestingAmount() internal pure returns(uint256) { return vesting_amount; } function getBountyAmount() internal pure returns(uint256) { return bounty_amount; } /** @dev Sets the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external { require(msg.sender == crowdsaleAddress); if (_startTimeForTransfers < startTimeForTransfers) { startTimeForTransfers = _startTimeForTransfers; } } /** @dev Transfer possible only after ICO ends and Frozen accounts * wont be able to transfer funds to other any other account and viz. * @notice added safeTransfer functionality */ function transfer(address _to, uint256 _value) public returns(bool) { require(now >= startTimeForTransfers); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(super.transfer(_to, _value)); return true; } /** @dev Only owner's tokens can be transferred before Crowdsale ends. * beacuse the inital supply of EML is allocated to owners acc and later * distributed to various subcontracts. * @notice added safeTransferFrom functionality */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); if (now < startTimeForTransfers) { require(_from == owner); } require(super.transferFrom(_from, _to, _value)); return true; } /** @notice added safeApprove functionality */ function approve(address spender, uint256 tokens) public returns (bool){ require(super.approve(spender, tokens)); return true; } /** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyOwner { require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) { require(_totalSupply.add(_amount) <= minting_capped_amount); _totalSupply = _totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import './Ownable.sol'; /** @notice This contract provides support for whitelisting addresses. * only whitelisted addresses are allowed to send ether and buy tokens * during preSale and Pulic crowdsale. * @dev after deploying contract, deploy Presale / Crowdsale contract using * EmalWhitelist address. To allow claim refund functionality and allow wallet * owner efatoora to send ether to Crowdsale contract for refunds add wallet * address to whitelist. */ contract EmalWhitelist is Ownable { mapping(address => bool) whitelist; event AddToWhitelist(address investorAddr); event RemoveFromWhitelist(address investorAddr); /** @dev Throws if operator is not whitelisted. */ modifier onlyIfWhitelisted(address investorAddr) { require(whitelist[investorAddr]); _; } constructor() public { owner = msg.sender; } /** @dev Returns if an address is whitelisted or not */ function isWhitelisted(address investorAddr) public view returns(bool whitelisted) { return whitelist[investorAddr]; } /** * @dev Adds an investor to whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = true; return true; } /** * @dev Removes an investor's address from whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; } } pragma solidity 0.4.24; contract ERC20Token { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity 0.4.24; import "./Ownable.sol"; /* Pausable contract */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } pragma solidity 0.4.24; import './ERC20Token.sol'; import './SafeMath.sol'; contract StandardToken is ERC20Token { using SafeMath for uint256; // Global variable to store total number of tokens passed from EmalToken.sol uint256 _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint256){ return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool){ require(to != address(0)); require(tokens > 0 && tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // Transfer tokens from one address to another function transferFrom(address from, address to, uint256 tokens) public returns (bool success){ require(to != address(0)); require(tokens > 0 && tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. function approve(address spender, uint256 tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // Function to check the amount of tokens that an owner allowed to a spender. function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // Increase the amount of tokens that an owner allowed to a spender. // approve should be called when allowed[spender] == 0. // To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) function increaseApproval(address spender, uint256 addedValue) public returns (bool) { allowed[msg.sender][spender] = (allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } // Decrease the amount of tokens that an owner allowed to a spender. // approve should be called when allowed[spender] == 0. // To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) function decreaseApproval(address spender, uint256 subtractedValue ) public returns (bool){ uint256 oldValue = allowed[msg.sender][spender]; if (subtractedValue >= oldValue) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } }
Removes an investor's address from whitelist investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements./
function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; }
7,279,346
./partial_match/42/0x1810Dc6C1dba820F5800b90b99dBB7b5214075A0/sources/ERC20TokenContract.sol
Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - `_frozen` should be enabled (true)/
function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(_frozen == false, "Transfers are disabled"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
3,314,854
./full_match/1284/0xb89279DEd0AD7cD573D164b03424E1E2BbE1e2Be/sources/contracts/tgev5.sol
Unlock apes without spending Shakes Deployer Required _collectionsId: 1 for GLMA, 2 for GLMJ _tokensId: tokens ID to unlock/
function unlockApes(uint8[] calldata _collectionsId, uint16[] calldata _tokensId) public payable onlyOwner { for (uint256 i = 0; i < _collectionsId.length; i++) { if (_collectionsId[i] == 1) { lockedGlma[_tokensId[i]] = block.number; } else if (_collectionsId[i] == 2) { lockedGlmj[_tokensId[i]] = block.number; } } }
16,368,413
./full_match/8453/0xae39367558D255B9440c50B6A594e857Cc672f49/sources/PropGenesisRewardPool.sol
Add a new token to the pool. Can only be called by the owner. chef is sleeping chef is cooking
function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, uint256 _lastRewardTime ) public onlyOperator { checkPoolDuplicate(_token); if (_withUpdate) { massUpdatePools(); } if (block.timestamp < poolStartTime) { if (_lastRewardTime == 0) { _lastRewardTime = poolStartTime; if (_lastRewardTime < poolStartTime) { _lastRewardTime = poolStartTime; } } if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) { _lastRewardTime = block.timestamp; } } bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp); poolInfo.push(PoolInfo({ token : _token, allocPoint : _allocPoint, lastRewardTime : _lastRewardTime, accPropPerShare : 0, isStarted : _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } }
11,550,550
./full_match/1/0xb2bf8D922dB107e73BCd0E5f8Da7068dE0CB71ca/sources/contracts/BirdX.sol
Allows the contract owner to add liquidity to the Uniswap pool. amountTokenDesired The desired amount of tokens for liquidity. amountETHDesired The desired amount of Ether for liquidity./
function addLiquidity(uint256 amountTokenDesired, uint256 amountETHDesired) external nonReentrant onlyOwner { require(balanceOf[msg.sender] >= amountTokenDesired, "Insufficient balance"); require(address(this).balance >= amountETHDesired, "Contract does not have enough Ether for liquidity"); uint256 amountTokenMin = amountTokenDesired; uint256 amountETHMin = amountETHDesired; _transfer(msg.sender, address(this), amountTokenDesired); address(this), amountTokenDesired, amountTokenMin, amountETHMin, msg.sender, block.timestamp ); emit LiquidityAdded(msg.sender, amountToken, amountETH); }
2,922,559
./full_match/3/0xb945F8EfE7F7dF7972113a5D7E03E254e00353C6/sources/browser/sushiswap/MasterChef_May.sol
Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 l = ( _to.sub(_from) ).div(bonusEndBlock); uint256 nowJinagli = sushiPerBlock/(2**(l.sub(1))).mul(_to.sub( _from).mod(bonusEndBlock)); uint256 sumJiang = nowJinagli; for(uint256 i = 0; i < l; i++) { sumJiang = sumJiang.add(sushiPerBlock/(2**i).mul(bonusEndBlock)); } return (sumJiang); }
14,248,907
./full_match/1/0xf7E49a9D1dfeD8E533e3C6d2A5977e6d240e07f5/sources/solady/src/utils/ECDSA.sol
Recovers the signer's address from a message digest `hash`, and the `signature`. This function does NOT accept EIP-2098 short form signatures. Use `recover(bytes32 hash, bytes32 r, bytes32 vs)` for EIP-2098 short form signatures instead. @solidity memory-safe-assembly If the signature is exactly 65 bytes in length. If `s` in lower half order, such that the signature is not malleable. `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
function tryRecoverCalldata(bytes32 hash, bytes calldata signature) internal view returns (address result) { assembly { mstore(0x00, hash) pop( staticcall( and( eq(signature.length, 65), lt(mload(0x60), _MALLEABILITY_THRESHOLD_PLUS_ONE) ) ) result := mload(xor(0x60, returndatasize())) } }
4,969,025
./partial_match/1/0x936dF79234533F9A7765841653E2e191441A9Ee2/sources/contracts/HoneyBBToken.sol
----- HELPER FUNCTIONS ----- /
function whichSwapCalled() private view returns (SwapRouterVersion version) { address sender = _msgSender(); if (sender == address(swapRouterV3)) { return SwapRouterVersion.V3; return SwapRouterVersion.V2; } return SwapRouterVersion.NotSupported; }
4,482,014
pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } pragma solidity ^0.6.0; /** * @dev 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); } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only // solhint-disable // Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5**18`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } // SPDX-License-Identifier: MIT // Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IERC20withDec.sol"; interface ICUSDCContract is IERC20withDec { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, address cTokenCollateral ) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function balanceOfUnderlying(address owner) external returns (uint256); function exchangeRateCurrent() external returns (uint256); /*** Admin Functions ***/ function _addReserves(uint256 addAmount) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract ICreditDesk { uint256 public totalWritedowns; uint256 public totalLoansOutstanding; function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual; function drawdown(address creditLineAddress, uint256 amount) external virtual; function pay(address creditLineAddress, uint256 amount) external virtual; function assessCreditLine(address creditLineAddress) external virtual; function applyPayment(address creditLineAddress, uint256 amount) external virtual; function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock) external view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ICreditLine { function borrower() external view returns (address); function limit() external view returns (uint256); function interestApr() external view returns (uint256); function paymentPeriodInDays() external view returns (uint256); function termInDays() external view returns (uint256); function lateFeeApr() external view returns (uint256); // Accounting variables function balance() external view returns (uint256); function interestOwed() external view returns (uint256); function principalOwed() external view returns (uint256); function termEndTime() external view returns (uint256); function nextDueTime() external view returns (uint256); function interestAccruedAsOf() external view returns (uint256); function lastFullPaymentTime() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; /* Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's. */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20withDec is IERC20 { /** * @dev Returns the number of decimals used for the token */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IERC20withDec.sol"; interface IFidu is IERC20withDec { function mintTo(address to, uint256 amount) external; function burnFrom(address to, uint256 amount) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGo { /// @notice Returns the address of the UniqueIdentity contract. function uniqueIdentity() external view returns (address); function go(address account) external view returns (bool); function updateGoldfinchConfig() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGoldfinchConfig { function getNumber(uint256 index) external returns (uint256); function getAddress(uint256 index) external returns (address); function setAddress(uint256 index, address newAddress) external returns (address); function setNumber(uint256 index, uint256 newNumber) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGoldfinchFactory { function createCreditLine() external returns (address); function createBorrower(address owner) external returns (address); function createPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) external returns (address); function createMigratedPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) external returns (address); function updateGoldfinchConfig() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IPool { uint256 public sharePrice; function deposit(uint256 amount) external virtual; function withdraw(uint256 usdcAmount) external virtual; function withdrawInFidu(uint256 fiduAmount) external virtual; function collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) public virtual; function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool); function drawdown(address to, uint256 amount) public virtual returns (bool); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual; function assets() public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; interface IPoolTokens is IERC721 { event TokenMinted( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 amount, uint256 tranche ); event TokenRedeemed( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 principalRedeemed, uint256 interestRedeemed, uint256 tranche ); event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId); struct TokenInfo { address pool; uint256 tranche; uint256 principalAmount; uint256 principalRedeemed; uint256 interestRedeemed; } struct MintParams { uint256 principalAmount; uint256 tranche; } function mint(MintParams calldata params, address to) external returns (uint256); function redeem( uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed ) external; function burn(uint256 tokenId) external; function onPoolCreated(address newPool) external; function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory); function validPool(address sender) external view returns (bool); function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ITranchedPool.sol"; abstract contract ISeniorPool { uint256 public sharePrice; uint256 public totalLoansOutstanding; uint256 public totalWritedowns; function deposit(uint256 amount) external virtual returns (uint256 depositShares); function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 depositShares); function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount); function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function invest(ITranchedPool pool) public virtual; function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256); function investJunior(ITranchedPool pool, uint256 amount) public virtual; function redeem(uint256 tokenId) public virtual; function writedown(uint256 tokenId) public virtual; function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount); function assets() public view virtual returns (uint256); function getNumShares(uint256 amount) public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ISeniorPool.sol"; import "./ITranchedPool.sol"; abstract contract ISeniorPoolStrategy { function getLeverageRatio(ITranchedPool pool) public view virtual returns (uint256); function invest(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256 amount); function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IV2CreditLine.sol"; abstract contract ITranchedPool { IV2CreditLine public creditLine; uint256 public createdAt; enum Tranches { Reserved, Senior, Junior } struct TrancheInfo { uint256 id; uint256 principalDeposited; uint256 principalSharePrice; uint256 interestSharePrice; uint256 lockedUntil; } function initialize( address _config, address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public virtual; function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory); function pay(uint256 amount) external virtual; function lockJuniorCapital() external virtual; function lockPool() external virtual; function drawdown(uint256 amount) external virtual; function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId); function assess() external virtual; function depositWithPermit( uint256 tranche, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 tokenId); function availableToWithdraw(uint256 tokenId) external view virtual returns (uint256 interestRedeemable, uint256 principalRedeemable); function withdraw(uint256 tokenId, uint256 amount) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMax(uint256 tokenId) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ICreditLine.sol"; abstract contract IV2CreditLine is ICreditLine { function principal() external view virtual returns (uint256); function totalInterestAccrued() external view virtual returns (uint256); function termStartTime() external view virtual returns (uint256); function setLimit(uint256 newAmount) external virtual; function setBalance(uint256 newBalance) external virtual; function setPrincipal(uint256 _principal) external virtual; function setTotalInterestAccrued(uint256 _interestAccrued) external virtual; function drawdown(uint256 amount) external virtual; function assess() external virtual returns ( uint256, uint256, uint256 ); function initialize( address _config, address owner, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public virtual; function setTermEndTime(uint256 newTermEndTime) external virtual; function setNextDueTime(uint256 newNextDueTime) external virtual; function setInterestOwed(uint256 newInterestOwed) external virtual; function setPrincipalOwed(uint256 newPrincipalOwed) external virtual; function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual; function setWritedownAmount(uint256 newWritedownAmount) external virtual; function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual; function setLateFeeApr(uint256 newLateFeeApr) external virtual; function updateGoldfinchConfig() external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./CreditLine.sol"; import "../../interfaces/ICreditLine.sol"; import "../../external/FixedPoint.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title The Accountant * @notice Library for handling key financial calculations, such as interest and principal accrual. * @author Goldfinch */ library Accountant { using SafeMath for uint256; using FixedPoint for FixedPoint.Signed; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for int256; using FixedPoint for uint256; // Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled uint256 public constant FP_SCALING_FACTOR = 10**18; uint256 public constant INTEREST_DECIMALS = 1e18; uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; uint256 public constant SECONDS_PER_YEAR = (SECONDS_PER_DAY * 365); struct PaymentAllocation { uint256 interestPayment; uint256 principalPayment; uint256 additionalBalancePayment; } function calculateInterestAndPrincipalAccrued( CreditLine cl, uint256 timestamp, uint256 lateFeeGracePeriod ) public view returns (uint256, uint256) { uint256 balance = cl.balance(); // gas optimization uint256 interestAccrued = calculateInterestAccrued(cl, balance, timestamp, lateFeeGracePeriod); uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, timestamp); return (interestAccrued, principalAccrued); } function calculateInterestAndPrincipalAccruedOverPeriod( CreditLine cl, uint256 balance, uint256 startTime, uint256 endTime, uint256 lateFeeGracePeriod ) public view returns (uint256, uint256) { uint256 interestAccrued = calculateInterestAccruedOverPeriod(cl, balance, startTime, endTime, lateFeeGracePeriod); uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, endTime); return (interestAccrued, principalAccrued); } function calculatePrincipalAccrued( ICreditLine cl, uint256 balance, uint256 timestamp ) public view returns (uint256) { // If we've already accrued principal as of the term end time, then don't accrue more principal uint256 termEndTime = cl.termEndTime(); if (cl.interestAccruedAsOf() >= termEndTime) { return 0; } if (timestamp >= termEndTime) { return balance; } else { return 0; } } function calculateWritedownFor( ICreditLine cl, uint256 timestamp, uint256 gracePeriodInDays, uint256 maxDaysLate ) public view returns (uint256, uint256) { return calculateWritedownForPrincipal(cl, cl.balance(), timestamp, gracePeriodInDays, maxDaysLate); } function calculateWritedownForPrincipal( ICreditLine cl, uint256 principal, uint256 timestamp, uint256 gracePeriodInDays, uint256 maxDaysLate ) public view returns (uint256, uint256) { FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl); if (amountOwedPerDay.isEqual(0)) { return (0, 0); } FixedPoint.Unsigned memory fpGracePeriod = FixedPoint.fromUnscaledUint(gracePeriodInDays); FixedPoint.Unsigned memory daysLate; // Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30, // Before the term end date, we use the interestOwed to calculate the periods late. However, after the loan term // has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to // calculate the periods later. uint256 totalOwed = cl.interestOwed().add(cl.principalOwed()); daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay); if (timestamp > cl.termEndTime()) { uint256 secondsLate = timestamp.sub(cl.termEndTime()); daysLate = daysLate.add(FixedPoint.fromUnscaledUint(secondsLate).div(SECONDS_PER_DAY)); } FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate); FixedPoint.Unsigned memory writedownPercent; if (daysLate.isLessThanOrEqual(fpGracePeriod)) { // Within the grace period, we don't have to write down, so assume 0% writedownPercent = FixedPoint.fromUnscaledUint(0); } else { writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate)); } FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(principal).div(FP_SCALING_FACTOR); // This will return a number between 0-100 representing the write down percent with no decimals uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue; return (unscaledWritedownPercent, writedownAmount.rawValue); } function calculateAmountOwedForOneDay(ICreditLine cl) public view returns (FixedPoint.Unsigned memory interestOwed) { // Determine theoretical interestOwed for one full day uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS); interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365); return interestOwed; } function calculateInterestAccrued( CreditLine cl, uint256 balance, uint256 timestamp, uint256 lateFeeGracePeriodInDays ) public view returns (uint256) { // We use Math.min here to prevent integer overflow (ie. go negative) when calculating // numSecondsElapsed. Typically this shouldn't be possible, because // the interestAccruedAsOf couldn't be *after* the current timestamp. However, when assessing // we allow this function to be called with a past timestamp, which raises the possibility // of overflow. // This use of min should not generate incorrect interest calculations, since // this function's purpose is just to normalize balances, and handing in a past timestamp // will necessarily return zero interest accrued (because zero elapsed time), which is correct. uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf()); return calculateInterestAccruedOverPeriod(cl, balance, startTime, timestamp, lateFeeGracePeriodInDays); } function calculateInterestAccruedOverPeriod( CreditLine cl, uint256 balance, uint256 startTime, uint256 endTime, uint256 lateFeeGracePeriodInDays ) public view returns (uint256 interestOwed) { uint256 secondsElapsed = endTime.sub(startTime); uint256 totalInterestPerYear = balance.mul(cl.interestApr()).div(INTEREST_DECIMALS); interestOwed = totalInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR); if (lateFeeApplicable(cl, endTime, lateFeeGracePeriodInDays)) { uint256 lateFeeInterestPerYear = balance.mul(cl.lateFeeApr()).div(INTEREST_DECIMALS); uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR); interestOwed = interestOwed.add(additionalLateFeeInterest); } return interestOwed; } function lateFeeApplicable( CreditLine cl, uint256 timestamp, uint256 gracePeriodInDays ) public view returns (bool) { uint256 secondsLate = timestamp.sub(cl.lastFullPaymentTime()); return cl.lateFeeApr() > 0 && secondsLate > gracePeriodInDays.mul(SECONDS_PER_DAY); } function allocatePayment( uint256 paymentAmount, uint256 balance, uint256 interestOwed, uint256 principalOwed ) public pure returns (PaymentAllocation memory) { uint256 paymentRemaining = paymentAmount; uint256 interestPayment = Math.min(interestOwed, paymentRemaining); paymentRemaining = paymentRemaining.sub(interestPayment); uint256 principalPayment = Math.min(principalOwed, paymentRemaining); paymentRemaining = paymentRemaining.sub(principalPayment); uint256 balanceRemaining = balance.sub(principalPayment); uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining); return PaymentAllocation({ interestPayment: interestPayment, principalPayment: principalPayment, additionalBalancePayment: additionalBalancePayment }); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./PauserPausable.sol"; /** * @title BaseUpgradeablePausable contract * @notice This is our Base contract that most other contracts inherit from. It includes many standard * useful abilities like ugpradeability, pausability, access control, and re-entrancy guards. * @author Goldfinch */ contract BaseUpgradeablePausable is Initializable, AccessControlUpgradeSafe, PauserPausable, ReentrancyGuardUpgradeSafe { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); using SafeMath for uint256; // Pre-reserving a few slots in the base contract in case we need to add things in the future. // This does not actually take up gas cost or storage cost, but it does reserve the storage slots. // See OpenZeppelin's use of this pattern here: // https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37 uint256[50] private __gap1; uint256[50] private __gap2; uint256[50] private __gap3; uint256[50] private __gap4; // solhint-disable-next-line func-name-mixedcase function __BaseUpgradeablePausable__init(address owner) public initializer { require(owner != address(0), "Owner cannot be the zero address"); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "../../interfaces/IPool.sol"; import "../../interfaces/IFidu.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/ISeniorPoolStrategy.sol"; import "../../interfaces/ICreditDesk.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ICUSDCContract.sol"; import "../../interfaces/IPoolTokens.sol"; import "../../interfaces/IGoldfinchFactory.sol"; import "../../interfaces/IGo.sol"; /** * @title ConfigHelper * @notice A convenience library for getting easy access to other contracts and constants within the * protocol, through the use of the GoldfinchConfig contract * @author Goldfinch */ library ConfigHelper { function getPool(GoldfinchConfig config) internal view returns (IPool) { return IPool(poolAddress(config)); } function getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) { return ISeniorPool(seniorPoolAddress(config)); } function getSeniorPoolStrategy(GoldfinchConfig config) internal view returns (ISeniorPoolStrategy) { return ISeniorPoolStrategy(seniorPoolStrategyAddress(config)); } function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) { return IERC20withDec(usdcAddress(config)); } function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) { return ICreditDesk(creditDeskAddress(config)); } function getFidu(GoldfinchConfig config) internal view returns (IFidu) { return IFidu(fiduAddress(config)); } function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) { return ICUSDCContract(cusdcContractAddress(config)); } function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) { return IPoolTokens(poolTokensAddress(config)); } function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) { return IGoldfinchFactory(goldfinchFactoryAddress(config)); } function getGFI(GoldfinchConfig config) internal view returns (IERC20withDec) { return IERC20withDec(gfiAddress(config)); } function getGo(GoldfinchConfig config) internal view returns (IGo) { return IGo(goAddress(config)); } function oneInchAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.OneInch)); } function creditLineImplementationAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation)); } function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder)); } function configAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig)); } function poolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Pool)); } function poolTokensAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens)); } function seniorPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPool)); } function seniorPoolStrategyAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPoolStrategy)); } function creditDeskAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk)); } function goldfinchFactoryAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory)); } function gfiAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GFI)); } function fiduAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Fidu)); } function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract)); } function usdcAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.USDC)); } function tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation)); } function migratedTranchedPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.MigratedTranchedPoolImplementation)); } function reserveAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve)); } function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin)); } function borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation)); } function goAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Go)); } function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator)); } function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator)); } function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays)); } function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays)); } function getDrawdownPeriodInSeconds(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds)); } function getTransferRestrictionPeriodInDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays)); } function getLeverageRatio(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LeverageRatio)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title ConfigOptions * @notice A central place for enumerating the configurable options of our GoldfinchConfig contract * @author Goldfinch */ library ConfigOptions { // NEVER EVER CHANGE THE ORDER OF THESE! // You can rename or append. But NEVER change the order. enum Numbers { TransactionLimit, TotalFundsLimit, MaxUnderwriterLimit, ReserveDenominator, WithdrawFeeDenominator, LatenessGracePeriodInDays, LatenessMaxDays, DrawdownPeriodInSeconds, TransferRestrictionPeriodInDays, LeverageRatio } enum Addresses { Pool, CreditLineImplementation, GoldfinchFactory, CreditDesk, Fidu, USDC, TreasuryReserve, ProtocolAdmin, OneInch, TrustedForwarder, CUSDCContract, GoldfinchConfig, PoolTokens, TranchedPoolImplementation, SeniorPool, SeniorPoolStrategy, MigratedTranchedPoolImplementation, BorrowerImplementation, GFI, Go } function getNumberName(uint256 number) public pure returns (string memory) { Numbers numberName = Numbers(number); if (Numbers.TransactionLimit == numberName) { return "TransactionLimit"; } if (Numbers.TotalFundsLimit == numberName) { return "TotalFundsLimit"; } if (Numbers.MaxUnderwriterLimit == numberName) { return "MaxUnderwriterLimit"; } if (Numbers.ReserveDenominator == numberName) { return "ReserveDenominator"; } if (Numbers.WithdrawFeeDenominator == numberName) { return "WithdrawFeeDenominator"; } if (Numbers.LatenessGracePeriodInDays == numberName) { return "LatenessGracePeriodInDays"; } if (Numbers.LatenessMaxDays == numberName) { return "LatenessMaxDays"; } if (Numbers.DrawdownPeriodInSeconds == numberName) { return "DrawdownPeriodInSeconds"; } if (Numbers.TransferRestrictionPeriodInDays == numberName) { return "TransferRestrictionPeriodInDays"; } if (Numbers.LeverageRatio == numberName) { return "LeverageRatio"; } revert("Unknown value passed to getNumberName"); } function getAddressName(uint256 addressKey) public pure returns (string memory) { Addresses addressName = Addresses(addressKey); if (Addresses.Pool == addressName) { return "Pool"; } if (Addresses.CreditLineImplementation == addressName) { return "CreditLineImplementation"; } if (Addresses.GoldfinchFactory == addressName) { return "GoldfinchFactory"; } if (Addresses.CreditDesk == addressName) { return "CreditDesk"; } if (Addresses.Fidu == addressName) { return "Fidu"; } if (Addresses.USDC == addressName) { return "USDC"; } if (Addresses.TreasuryReserve == addressName) { return "TreasuryReserve"; } if (Addresses.ProtocolAdmin == addressName) { return "ProtocolAdmin"; } if (Addresses.OneInch == addressName) { return "OneInch"; } if (Addresses.TrustedForwarder == addressName) { return "TrustedForwarder"; } if (Addresses.CUSDCContract == addressName) { return "CUSDCContract"; } if (Addresses.PoolTokens == addressName) { return "PoolTokens"; } if (Addresses.TranchedPoolImplementation == addressName) { return "TranchedPoolImplementation"; } if (Addresses.SeniorPool == addressName) { return "SeniorPool"; } if (Addresses.SeniorPoolStrategy == addressName) { return "SeniorPoolStrategy"; } if (Addresses.MigratedTranchedPoolImplementation == addressName) { return "MigratedTranchedPoolImplementation"; } if (Addresses.BorrowerImplementation == addressName) { return "BorrowerImplementation"; } if (Addresses.GFI == addressName) { return "GFI"; } if (Addresses.Go == addressName) { return "Go"; } revert("Unknown value passed to getAddressName"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "./ConfigHelper.sol"; import "./BaseUpgradeablePausable.sol"; import "./Accountant.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ICreditLine.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; /** * @title CreditLine * @notice A contract that represents the agreement between Backers and * a Borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed. * A CreditLine belongs to a TranchedPool, and is fully controlled by that TranchedPool. It does not * operate in any standalone capacity. It should generally be considered internal to the TranchedPool. * @author Goldfinch */ // solhint-disable-next-line max-states-count contract CreditLine is BaseUpgradeablePausable, ICreditLine { uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; event GoldfinchConfigUpdated(address indexed who, address configAddress); // Credit line terms address public override borrower; uint256 public override limit; uint256 public override interestApr; uint256 public override paymentPeriodInDays; uint256 public override termInDays; uint256 public override lateFeeApr; // Accounting variables uint256 public override balance; uint256 public override interestOwed; uint256 public override principalOwed; uint256 public override termEndTime; uint256 public override nextDueTime; uint256 public override interestAccruedAsOf; uint256 public override lastFullPaymentTime; uint256 public totalInterestAccrued; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; function initialize( address _config, address owner, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public initializer { require(_config != address(0) && owner != address(0) && _borrower != address(0), "Zero address passed in"); __BaseUpgradeablePausable__init(owner); config = GoldfinchConfig(_config); borrower = _borrower; limit = _limit; interestApr = _interestApr; paymentPeriodInDays = _paymentPeriodInDays; termInDays = _termInDays; lateFeeApr = _lateFeeApr; interestAccruedAsOf = block.timestamp; // Unlock owner, which is a TranchedPool, for infinite amount bool success = config.getUSDC().approve(owner, uint256(-1)); require(success, "Failed to approve USDC"); } /** * @notice Updates the internal accounting to track a drawdown as of current block timestamp. * Does not move any money * @param amount The amount in USDC that has been drawndown */ function drawdown(uint256 amount) external onlyAdmin { require(amount.add(balance) <= limit, "Cannot drawdown more than the limit"); uint256 timestamp = currentTime(); if (balance == 0) { setInterestAccruedAsOf(timestamp); setLastFullPaymentTime(timestamp); setTotalInterestAccrued(0); setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays))); } (uint256 _interestOwed, uint256 _principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp); balance = balance.add(amount); updateCreditLineAccounting(balance, _interestOwed, _principalOwed); require(!isLate(timestamp), "Cannot drawdown when payments are past due"); } /** * @notice Migrates to a new goldfinch config address */ function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } function setLateFeeApr(uint256 newLateFeeApr) external onlyAdmin { lateFeeApr = newLateFeeApr; } function setLimit(uint256 newAmount) external onlyAdmin { limit = newAmount; } function termStartTime() external view returns (uint256) { return termEndTime.sub(SECONDS_PER_DAY.mul(termInDays)); } function setTermEndTime(uint256 newTermEndTime) public onlyAdmin { termEndTime = newTermEndTime; } function setNextDueTime(uint256 newNextDueTime) public onlyAdmin { nextDueTime = newNextDueTime; } function setBalance(uint256 newBalance) public onlyAdmin { balance = newBalance; } function setTotalInterestAccrued(uint256 _totalInterestAccrued) public onlyAdmin { totalInterestAccrued = _totalInterestAccrued; } function setInterestOwed(uint256 newInterestOwed) public onlyAdmin { interestOwed = newInterestOwed; } function setPrincipalOwed(uint256 newPrincipalOwed) public onlyAdmin { principalOwed = newPrincipalOwed; } function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) public onlyAdmin { interestAccruedAsOf = newInterestAccruedAsOf; } function setLastFullPaymentTime(uint256 newLastFullPaymentTime) public onlyAdmin { lastFullPaymentTime = newLastFullPaymentTime; } /** * @notice Triggers an assessment of the creditline. Any USDC balance available in the creditline is applied * towards the interest and principal. * @return Any amount remaining after applying payments towards the interest and principal * @return Amount applied towards interest * @return Amount applied towards principal */ function assess() public onlyAdmin returns ( uint256, uint256, uint256 ) { // Do not assess until a full period has elapsed or past due require(balance > 0, "Must have balance to assess credit line"); // Don't assess credit lines early! if (currentTime() < nextDueTime && !isLate(currentTime())) { return (0, 0, 0); } uint256 timeToAssess = calculateNextDueTime(); setNextDueTime(timeToAssess); // We always want to assess for the most recently *past* nextDueTime. // So if the recalculation above sets the nextDueTime into the future, // then ensure we pass in the one just before this. if (timeToAssess > currentTime()) { uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); timeToAssess = timeToAssess.sub(secondsPerPeriod); } return handlePayment(getUSDCBalance(address(this)), timeToAssess); } function calculateNextDueTime() internal view returns (uint256) { uint256 newNextDueTime = nextDueTime; uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); uint256 curTimestamp = currentTime(); // You must have just done your first drawdown if (newNextDueTime == 0 && balance > 0) { return curTimestamp.add(secondsPerPeriod); } // Active loan that has entered a new period, so return the *next* newNextDueTime. // But never return something after the termEndTime if (balance > 0 && curTimestamp >= newNextDueTime) { uint256 secondsToAdvance = (curTimestamp.sub(newNextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod); newNextDueTime = newNextDueTime.add(secondsToAdvance); return Math.min(newNextDueTime, termEndTime); } // You're paid off, or have not taken out a loan yet, so no next due time. if (balance == 0 && newNextDueTime != 0) { return 0; } // Active loan in current period, where we've already set the newNextDueTime correctly, so should not change. if (balance > 0 && curTimestamp < newNextDueTime) { return newNextDueTime; } revert("Error: could not calculate next due time."); } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function isLate(uint256 timestamp) internal view returns (bool) { uint256 secondsElapsedSinceFullPayment = timestamp.sub(lastFullPaymentTime); return secondsElapsedSinceFullPayment > paymentPeriodInDays.mul(SECONDS_PER_DAY); } /** * @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool. * It also updates all the accounting variables. Note that interest is always paid back first, then principal. * Any extra after paying the minimum will go towards existing principal (reducing the * effective interest rate). Any extra after the full loan has been paid off will remain in the * USDC Balance of the creditLine, where it will be automatically used for the next drawdown. * @param paymentAmount The amount, in USDC atomic units, to be applied * @param timestamp The timestamp on which accrual calculations should be based. This allows us * to be precise when we assess a Credit Line */ function handlePayment(uint256 paymentAmount, uint256 timestamp) internal returns ( uint256, uint256, uint256 ) { (uint256 newInterestOwed, uint256 newPrincipalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp); Accountant.PaymentAllocation memory pa = Accountant.allocatePayment( paymentAmount, balance, newInterestOwed, newPrincipalOwed ); uint256 newBalance = balance.sub(pa.principalPayment); // Apply any additional payment towards the balance newBalance = newBalance.sub(pa.additionalBalancePayment); uint256 totalPrincipalPayment = balance.sub(newBalance); uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment); updateCreditLineAccounting( newBalance, newInterestOwed.sub(pa.interestPayment), newPrincipalOwed.sub(pa.principalPayment) ); assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount); return (paymentRemaining, pa.interestPayment, totalPrincipalPayment); } function updateAndGetInterestAndPrincipalOwedAsOf(uint256 timestamp) internal returns (uint256, uint256) { (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued( this, timestamp, config.getLatenessGracePeriodInDays() ); if (interestAccrued > 0) { // If we've accrued any interest, update interestAccruedAsOf to the time that we've // calculated interest for. If we've not accrued any interest, then we keep the old value so the next // time the entire period is taken into account. setInterestAccruedAsOf(timestamp); totalInterestAccrued = totalInterestAccrued.add(interestAccrued); } return (interestOwed.add(interestAccrued), principalOwed.add(principalAccrued)); } function updateCreditLineAccounting( uint256 newBalance, uint256 newInterestOwed, uint256 newPrincipalOwed ) internal nonReentrant { setBalance(newBalance); setInterestOwed(newInterestOwed); setPrincipalOwed(newPrincipalOwed); // This resets lastFullPaymentTime. These conditions assure that they have // indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown) uint256 _nextDueTime = nextDueTime; if (newInterestOwed == 0 && _nextDueTime != 0) { // If interest was fully paid off, then set the last full payment as the previous due time uint256 mostRecentLastDueTime; if (currentTime() < _nextDueTime) { uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); mostRecentLastDueTime = _nextDueTime.sub(secondsPerPeriod); } else { mostRecentLastDueTime = _nextDueTime; } setLastFullPaymentTime(mostRecentLastDueTime); } setNextDueTime(calculateNextDueTime()); } function getUSDCBalance(address _address) internal view returns (uint256) { return config.getUSDC().balanceOf(_address); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "../../interfaces/IGoldfinchConfig.sol"; import "./ConfigOptions.sol"; /** * @title GoldfinchConfig * @notice This contract stores mappings of useful "protocol config state", giving a central place * for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars * are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol. * Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this * is mostly to save gas costs of having each call go through a proxy) * @author Goldfinch */ contract GoldfinchConfig is BaseUpgradeablePausable { bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE"); mapping(uint256 => address) public addresses; mapping(uint256 => uint256) public numbers; mapping(address => bool) public goList; event AddressUpdated(address owner, uint256 index, address oldValue, address newValue); event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue); event GoListed(address indexed member); event NoListed(address indexed member); bool public valuesInitialized; function initialize(address owner) public initializer { require(owner != address(0), "Owner address cannot be empty"); __BaseUpgradeablePausable__init(owner); _setupRole(GO_LISTER_ROLE, owner); _setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE); } function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin { require(addresses[addressIndex] == address(0), "Address has already been initialized"); emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress); addresses[addressIndex] = newAddress; } function setNumber(uint256 index, uint256 newNumber) public onlyAdmin { emit NumberUpdated(msg.sender, index, numbers[index], newNumber); numbers[index] = newNumber; } function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve); emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve); addresses[key] = newTreasuryReserve; } function setSeniorPoolStrategy(address newStrategy) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy); emit AddressUpdated(msg.sender, key, addresses[key], newStrategy); addresses[key] = newStrategy; } function setCreditLineImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setBorrowerImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setGoldfinchConfig(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function initializeFromOtherConfig(address _initialConfig) public onlyAdmin { require(!valuesInitialized, "Already initialized values"); IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig); for (uint256 i = 0; i < 10; i++) { setNumber(i, initialConfig.getNumber(i)); } for (uint256 i = 0; i < 11; i++) { if (getAddress(i) == address(0)) { setAddress(i, initialConfig.getAddress(i)); } } valuesInitialized = true; } /** * @dev Adds a user to go-list * @param _member address to add to go-list */ function addToGoList(address _member) public onlyGoListerRole { goList[_member] = true; emit GoListed(_member); } /** * @dev removes a user from go-list * @param _member address to remove from go-list */ function removeFromGoList(address _member) public onlyGoListerRole { goList[_member] = false; emit NoListed(_member); } /** * @dev adds many users to go-list at once * @param _members addresses to ad to go-list */ function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole { for (uint256 i = 0; i < _members.length; i++) { addToGoList(_members[i]); } } /** * @dev removes many users from go-list at once * @param _members addresses to remove from go-list */ function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole { for (uint256 i = 0; i < _members.length; i++) { removeFromGoList(_members[i]); } } /* Using custom getters in case we want to change underlying implementation later, or add checks or validations later on. */ function getAddress(uint256 index) public view returns (address) { return addresses[index]; } function getNumber(uint256 index) public view returns (uint256) { return numbers[index]; } modifier onlyGoListerRole() { require(hasRole(GO_LISTER_ROLE, _msgSender()), "Must have go-lister role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; /** * @title PauserPausable * @notice Inheriting from OpenZeppelin's Pausable contract, this does small * augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract. * It is meant to be inherited. * @author Goldfinch */ contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __PauserPausable__init() public initializer { __Pausable_init_unchained(); } /** * @dev Pauses all functions guarded by Pause * * See {Pausable-_pause}. * * Requirements: * * - the caller must have the PAUSER_ROLE. */ function pause() public onlyPauserRole { _pause(); } /** * @dev Unpauses the contract * * See {Pausable-_unpause}. * * Requirements: * * - the caller must have the Pauser role */ function unpause() public onlyPauserRole { _unpause(); } modifier onlyPauserRole() { require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action"); _; } }
Determine theoretical interestOwed for one full day
function calculateAmountOwedForOneDay(ICreditLine cl) public view returns (FixedPoint.Unsigned memory interestOwed) { uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS); interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365); return interestOwed; }
470,033
/** *Submitted for verification at Etherscan.io on 2021-04-03 */ // SPDX-License-Identifier: BUSL-1.1 // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IDMMFactory.sol pragma solidity 0.6.12; interface IDMMFactory { function createPool( IERC20 tokenA, IERC20 tokenB, uint32 ampBps ) external returns (address pool); function setFeeConfiguration(address feeTo, uint16 governmentFeeBps) external; function setFeeToSetter(address) external; function getFeeConfiguration() external view returns (address feeTo, uint16 governmentFeeBps); function feeToSetter() external view returns (address); function allPools(uint256) external view returns (address pool); function allPoolsLength() external view returns (uint256); function getUnamplifiedPool(IERC20 token0, IERC20 token1) external view returns (address); function getPools(IERC20 token0, IERC20 token1) external view returns (address[] memory _tokenPools); function isPool( IERC20 token0, IERC20 token1, address pool ) external view returns (bool); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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/math/Math.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Address.sol 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 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/libraries/MathExt.sol pragma solidity 0.6.12; library MathExt { using SafeMath for uint256; uint256 public constant PRECISION = (10**18); /// @dev Returns x*y in precision function mulInPrecision(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(y) / PRECISION; } /// @dev source: dsMath /// @param xInPrecision should be < PRECISION, so this can not overflow /// @return zInPrecision = (x/PRECISION) ^k * PRECISION function unsafePowInPrecision(uint256 xInPrecision, uint256 k) internal pure returns (uint256 zInPrecision) { require(xInPrecision <= PRECISION, "MathExt: x > PRECISION"); zInPrecision = k % 2 != 0 ? xInPrecision : PRECISION; for (k /= 2; k != 0; k /= 2) { xInPrecision = (xInPrecision * xInPrecision) / PRECISION; if (k % 2 != 0) { zInPrecision = (zInPrecision * xInPrecision) / PRECISION; } } } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/libraries/FeeFomula.sol pragma solidity 0.6.12; library FeeFomula { using SafeMath for uint256; using MathExt for uint256; uint256 private constant PRECISION = 10**18; uint256 private constant R0 = 1477405064814996100; // 1.4774050648149961 uint256 private constant C0 = (60 * PRECISION) / 10000; uint256 private constant A = uint256(PRECISION * 20000) / 27; uint256 private constant B = uint256(PRECISION * 250) / 9; uint256 private constant C1 = uint256(PRECISION * 985) / 27; uint256 private constant U = (120 * PRECISION) / 100; uint256 private constant G = (836 * PRECISION) / 1000; uint256 private constant F = 5 * PRECISION; uint256 private constant L = (2 * PRECISION) / 10000; // C2 = 25 * PRECISION - (F * (PRECISION - G)**2) / ((PRECISION - G)**2 + L * PRECISION) uint256 private constant C2 = 20036905816356657810; /// @dev calculate fee from rFactorInPrecision, see section 3.2 in dmmSwap white paper /// @dev fee in [15, 60] bps /// @return fee percentage in Precision function getFee(uint256 rFactorInPrecision) internal pure returns (uint256) { if (rFactorInPrecision >= R0) { return C0; } else if (rFactorInPrecision >= PRECISION) { // C1 + A * (r-U)^3 + b * (r -U) if (rFactorInPrecision > U) { uint256 tmp = rFactorInPrecision - U; uint256 tmp3 = tmp.unsafePowInPrecision(3); return (C1.add(A.mulInPrecision(tmp3)).add(B.mulInPrecision(tmp))) / 10000; } else { uint256 tmp = U - rFactorInPrecision; uint256 tmp3 = tmp.unsafePowInPrecision(3); return C1.sub(A.mulInPrecision(tmp3)).sub(B.mulInPrecision(tmp)) / 10000; } } else { // [ C2 + sign(r - G) * F * (r-G) ^2 / (L + (r-G) ^2) ] / 10000 uint256 tmp = ( rFactorInPrecision > G ? (rFactorInPrecision - G) : (G - rFactorInPrecision) ); tmp = tmp.unsafePowInPrecision(2); uint256 tmp2 = F.mul(tmp).div(tmp.add(L)); if (rFactorInPrecision > G) { return C2.add(tmp2) / 10000; } else { return C2.sub(tmp2) / 10000; } } } } // File: @openzeppelin/contracts/utils/Context.sol 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/token/ERC20/ERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/interfaces/IERC20Permit.sol pragma solidity 0.6.12; interface IERC20Permit is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File: contracts/libraries/ERC20Permit.sol pragma solidity 0.6.12; /// @dev https://eips.ethereum.org/EIPS/eip-2612 contract ERC20Permit is ERC20, IERC20Permit { /// @dev To make etherscan auto-verify new pool, this variable is not immutable bytes32 public domainSeparator; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; constructor( string memory name, string memory symbol, string memory version ) public ERC20(name, symbol) { uint256 chainId; assembly { chainId := chainid() } domainSeparator = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(deadline >= block.timestamp, "ERC20Permit: EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, keccak256( abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( recoveredAddress != address(0) && recoveredAddress == owner, "ERC20Permit: INVALID_SIGNATURE" ); _approve(owner, spender, value); } } // File: contracts/interfaces/IDMMCallee.sol pragma solidity 0.6.12; interface IDMMCallee { function dmmSwapCall( address sender, uint256 amount0, uint256 amount1, bytes calldata data ) external; } // File: contracts/interfaces/IDMMPool.sol pragma solidity 0.6.12; interface IDMMPool { function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function sync() external; function getReserves() external view returns (uint112 reserve0, uint112 reserve1); function getTradeInfo() external view returns ( uint112 _vReserve0, uint112 _vReserve1, uint112 reserve0, uint112 reserve1, uint256 feeInPrecision ); function token0() external view returns (IERC20); function token1() external view returns (IERC20); function ampBps() external view returns (uint32); function factory() external view returns (IDMMFactory); function kLast() external view returns (uint256); } // File: contracts/interfaces/IERC20Metadata.sol pragma solidity 0.6.12; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: contracts/VolumeTrendRecorder.sol pragma solidity 0.6.12; /// @dev contract to calculate volume trend. See secion 3.1 in the white paper /// @dev EMA stands for Exponential moving average /// @dev https://en.wikipedia.org/wiki/Moving_average contract VolumeTrendRecorder { using MathExt for uint256; using SafeMath for uint256; uint256 private constant MAX_UINT128 = 2**128 - 1; uint256 internal constant PRECISION = 10**18; uint256 private constant SHORT_ALPHA = (2 * PRECISION) / 5401; uint256 private constant LONG_ALPHA = (2 * PRECISION) / 10801; uint128 internal shortEMA; uint128 internal longEMA; // total volume in current block uint128 internal currentBlockVolume; uint128 internal lastTradeBlock; event UpdateEMA(uint256 shortEMA, uint256 longEMA, uint128 lastBlockVolume, uint256 skipBlock); constructor(uint128 _emaInit) public { shortEMA = _emaInit; longEMA = _emaInit; lastTradeBlock = safeUint128(block.number); } function getVolumeTrendData() external view returns ( uint128 _shortEMA, uint128 _longEMA, uint128 _currentBlockVolume, uint128 _lastTradeBlock ) { _shortEMA = shortEMA; _longEMA = longEMA; _currentBlockVolume = currentBlockVolume; _lastTradeBlock = lastTradeBlock; } /// @dev records a new trade, update ema and returns current rFactor for this trade /// @return rFactor in Precision for this trade function recordNewUpdatedVolume(uint256 blockNumber, uint256 value) internal returns (uint256) { // this can not be underflow because block.number always increases uint256 skipBlock = blockNumber - lastTradeBlock; if (skipBlock == 0) { currentBlockVolume = safeUint128( uint256(currentBlockVolume).add(value), "volume exceeds valid range" ); return calculateRFactor(uint256(shortEMA), uint256(longEMA)); } uint128 _currentBlockVolume = currentBlockVolume; uint256 _shortEMA = newEMA(shortEMA, SHORT_ALPHA, currentBlockVolume); uint256 _longEMA = newEMA(longEMA, LONG_ALPHA, currentBlockVolume); // ema = ema * (1-aplha) ^(skipBlock -1) _shortEMA = _shortEMA.mulInPrecision( (PRECISION - SHORT_ALPHA).unsafePowInPrecision(skipBlock - 1) ); _longEMA = _longEMA.mulInPrecision( (PRECISION - LONG_ALPHA).unsafePowInPrecision(skipBlock - 1) ); shortEMA = safeUint128(_shortEMA); longEMA = safeUint128(_longEMA); currentBlockVolume = safeUint128(value); lastTradeBlock = safeUint128(blockNumber); emit UpdateEMA(_shortEMA, _longEMA, _currentBlockVolume, skipBlock); return calculateRFactor(_shortEMA, _longEMA); } /// @return rFactor in Precision for this trade function getRFactor(uint256 blockNumber) internal view returns (uint256) { // this can not be underflow because block.number always increases uint256 skipBlock = blockNumber - lastTradeBlock; if (skipBlock == 0) { return calculateRFactor(shortEMA, longEMA); } uint256 _shortEMA = newEMA(shortEMA, SHORT_ALPHA, currentBlockVolume); uint256 _longEMA = newEMA(longEMA, LONG_ALPHA, currentBlockVolume); _shortEMA = _shortEMA.mulInPrecision( (PRECISION - SHORT_ALPHA).unsafePowInPrecision(skipBlock - 1) ); _longEMA = _longEMA.mulInPrecision( (PRECISION - LONG_ALPHA).unsafePowInPrecision(skipBlock - 1) ); return calculateRFactor(_shortEMA, _longEMA); } function calculateRFactor(uint256 _shortEMA, uint256 _longEMA) internal pure returns (uint256) { if (_longEMA == 0) { return 0; } return (_shortEMA * MathExt.PRECISION) / _longEMA; } /// @dev return newEMA value /// @param ema previous ema value in wei /// @param alpha in Precicion (required < Precision) /// @param value current value to update ema /// @dev ema and value is uint128 and alpha < Percison /// @dev so this function can not overflow and returned ema is not overflow uint128 function newEMA( uint128 ema, uint256 alpha, uint128 value ) internal pure returns (uint256) { assert(alpha < PRECISION); return ((PRECISION - alpha) * uint256(ema) + alpha * uint256(value)) / PRECISION; } function safeUint128(uint256 v) internal pure returns (uint128) { require(v <= MAX_UINT128, "overflow uint128"); return uint128(v); } function safeUint128(uint256 v, string memory errorMessage) internal pure returns (uint128) { require(v <= MAX_UINT128, errorMessage); return uint128(v); } } // File: contracts/DMMPool.sol pragma solidity 0.6.12; contract DMMPool is IDMMPool, ERC20Permit, ReentrancyGuard, VolumeTrendRecorder { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 internal constant MAX_UINT112 = 2**112 - 1; uint256 internal constant BPS = 10000; struct ReserveData { uint256 reserve0; uint256 reserve1; uint256 vReserve0; uint256 vReserve1; // only used when isAmpPool = true } uint256 public constant MINIMUM_LIQUIDITY = 10**3; /// @dev To make etherscan auto-verify new pool, these variables are not immutable IDMMFactory public override factory; IERC20 public override token0; IERC20 public override token1; /// @dev uses single storage slot, accessible via getReservesData uint112 internal reserve0; uint112 internal reserve1; uint32 public override ampBps; /// @dev addition param only when amplification factor > 1 uint112 internal vReserve0; uint112 internal vReserve1; /// @dev vReserve0 * vReserve1, as of immediately after the most recent liquidity event uint256 public override kLast; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to, uint256 feeInPrecision ); event Sync(uint256 vReserve0, uint256 vReserve1, uint256 reserve0, uint256 reserve1); constructor() public ERC20Permit("KyberDMM LP", "DMM-LP", "1") VolumeTrendRecorder(0) { factory = IDMMFactory(msg.sender); } // called once by the factory at time of deployment function initialize( IERC20 _token0, IERC20 _token1, uint32 _ampBps ) external { require(msg.sender == address(factory), "DMM: FORBIDDEN"); token0 = _token0; token1 = _token1; ampBps = _ampBps; } /// @dev this low-level function should be called from a contract /// which performs important safety checks function mint(address to) external override nonReentrant returns (uint256 liquidity) { (bool isAmpPool, ReserveData memory data) = getReservesData(); ReserveData memory _data; _data.reserve0 = token0.balanceOf(address(this)); _data.reserve1 = token1.balanceOf(address(this)); uint256 amount0 = _data.reserve0.sub(data.reserve0); uint256 amount1 = _data.reserve1.sub(data.reserve1); bool feeOn = _mintFee(isAmpPool, data); uint256 _totalSupply = totalSupply(); // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { if (isAmpPool) { uint32 _ampBps = ampBps; _data.vReserve0 = _data.reserve0.mul(_ampBps) / BPS; _data.vReserve1 = _data.reserve1.mul(_ampBps) / BPS; } liquidity = MathExt.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(-1), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min( amount0.mul(_totalSupply) / data.reserve0, amount1.mul(_totalSupply) / data.reserve1 ); if (isAmpPool) { uint256 b = liquidity.add(_totalSupply); _data.vReserve0 = Math.max(data.vReserve0.mul(b) / _totalSupply, _data.reserve0); _data.vReserve1 = Math.max(data.vReserve1.mul(b) / _totalSupply, _data.reserve1); } } require(liquidity > 0, "DMM: INSUFFICIENT_LIQUIDITY_MINTED"); _mint(to, liquidity); _update(isAmpPool, _data); if (feeOn) kLast = getK(isAmpPool, _data); emit Mint(msg.sender, amount0, amount1); } /// @dev this low-level function should be called from a contract /// @dev which performs important safety checks /// @dev user must transfer LP token to this contract before call burn function burn(address to) external override nonReentrant returns (uint256 amount0, uint256 amount1) { (bool isAmpPool, ReserveData memory data) = getReservesData(); // gas savings IERC20 _token0 = token0; // gas savings IERC20 _token1 = token1; // gas savings uint256 balance0 = _token0.balanceOf(address(this)); uint256 balance1 = _token1.balanceOf(address(this)); require(balance0 >= data.reserve0 && balance1 >= data.reserve1, "DMM: UNSYNC_RESERVES"); uint256 liquidity = balanceOf(address(this)); bool feeOn = _mintFee(isAmpPool, data); uint256 _totalSupply = totalSupply(); // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, "DMM: INSUFFICIENT_LIQUIDITY_BURNED"); _burn(address(this), liquidity); _token0.safeTransfer(to, amount0); _token1.safeTransfer(to, amount1); ReserveData memory _data; _data.reserve0 = _token0.balanceOf(address(this)); _data.reserve1 = _token1.balanceOf(address(this)); if (isAmpPool) { uint256 b = Math.min( _data.reserve0.mul(_totalSupply) / data.reserve0, _data.reserve1.mul(_totalSupply) / data.reserve1 ); _data.vReserve0 = Math.max(data.vReserve0.mul(b) / _totalSupply, _data.reserve0); _data.vReserve1 = Math.max(data.vReserve1.mul(b) / _totalSupply, _data.reserve1); } _update(isAmpPool, _data); if (feeOn) kLast = getK(isAmpPool, _data); // data are up-to-date emit Burn(msg.sender, amount0, amount1, to); } /// @dev this low-level function should be called from a contract /// @dev which performs important safety checks function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata callbackData ) external override nonReentrant { require(amount0Out > 0 || amount1Out > 0, "DMM: INSUFFICIENT_OUTPUT_AMOUNT"); (bool isAmpPool, ReserveData memory data) = getReservesData(); // gas savings require( amount0Out < data.reserve0 && amount1Out < data.reserve1, "DMM: INSUFFICIENT_LIQUIDITY" ); ReserveData memory newData; { // scope for _token{0,1}, avoids stack too deep errors IERC20 _token0 = token0; IERC20 _token1 = token1; require(to != address(_token0) && to != address(_token1), "DMM: INVALID_TO"); if (amount0Out > 0) _token0.safeTransfer(to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _token1.safeTransfer(to, amount1Out); // optimistically transfer tokens if (callbackData.length > 0) IDMMCallee(to).dmmSwapCall(msg.sender, amount0Out, amount1Out, callbackData); newData.reserve0 = _token0.balanceOf(address(this)); newData.reserve1 = _token1.balanceOf(address(this)); if (isAmpPool) { newData.vReserve0 = data.vReserve0.add(newData.reserve0).sub(data.reserve0); newData.vReserve1 = data.vReserve1.add(newData.reserve1).sub(data.reserve1); } } uint256 amount0In = newData.reserve0 > data.reserve0 - amount0Out ? newData.reserve0 - (data.reserve0 - amount0Out) : 0; uint256 amount1In = newData.reserve1 > data.reserve1 - amount1Out ? newData.reserve1 - (data.reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, "DMM: INSUFFICIENT_INPUT_AMOUNT"); uint256 feeInPrecision = verifyBalanceAndUpdateEma( amount0In, amount1In, isAmpPool ? data.vReserve0 : data.reserve0, isAmpPool ? data.vReserve1 : data.reserve1, isAmpPool ? newData.vReserve0 : newData.reserve0, isAmpPool ? newData.vReserve1 : newData.reserve1 ); _update(isAmpPool, newData); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to, feeInPrecision); } /// @dev force balances to match reserves function skim(address to) external nonReentrant { token0.safeTransfer(to, token0.balanceOf(address(this)).sub(reserve0)); token1.safeTransfer(to, token1.balanceOf(address(this)).sub(reserve1)); } /// @dev force reserves to match balances function sync() external override nonReentrant { (bool isAmpPool, ReserveData memory data) = getReservesData(); bool feeOn = _mintFee(isAmpPool, data); ReserveData memory newData; newData.reserve0 = IERC20(token0).balanceOf(address(this)); newData.reserve1 = IERC20(token1).balanceOf(address(this)); // update virtual reserves if this is amp pool if (isAmpPool) { uint256 _totalSupply = totalSupply(); uint256 b = Math.min( newData.reserve0.mul(_totalSupply) / data.reserve0, newData.reserve1.mul(_totalSupply) / data.reserve1 ); newData.vReserve0 = Math.max(data.vReserve0.mul(b) / _totalSupply, newData.reserve0); newData.vReserve1 = Math.max(data.vReserve1.mul(b) / _totalSupply, newData.reserve1); } _update(isAmpPool, newData); if (feeOn) kLast = getK(isAmpPool, newData); } /// @dev returns data to calculate amountIn, amountOut function getTradeInfo() external virtual override view returns ( uint112 _reserve0, uint112 _reserve1, uint112 _vReserve0, uint112 _vReserve1, uint256 feeInPrecision ) { // gas saving to read reserve data _reserve0 = reserve0; _reserve1 = reserve1; uint32 _ampBps = ampBps; _vReserve0 = vReserve0; _vReserve1 = vReserve1; if (_ampBps == BPS) { _vReserve0 = _reserve0; _vReserve1 = _reserve1; } uint256 rFactorInPrecision = getRFactor(block.number); feeInPrecision = getFinalFee(FeeFomula.getFee(rFactorInPrecision), _ampBps); } /// @dev returns reserve data to calculate amount to add liquidity function getReserves() external override view returns (uint112 _reserve0, uint112 _reserve1) { _reserve0 = reserve0; _reserve1 = reserve1; } function name() public override view returns (string memory) { IERC20Metadata _token0 = IERC20Metadata(address(token0)); IERC20Metadata _token1 = IERC20Metadata(address(token1)); return string(abi.encodePacked("KyberDMM LP ", _token0.symbol(), "-", _token1.symbol())); } function symbol() public override view returns (string memory) { IERC20Metadata _token0 = IERC20Metadata(address(token0)); IERC20Metadata _token1 = IERC20Metadata(address(token1)); return string(abi.encodePacked("DMM-LP ", _token0.symbol(), "-", _token1.symbol())); } function verifyBalanceAndUpdateEma( uint256 amount0In, uint256 amount1In, uint256 beforeReserve0, uint256 beforeReserve1, uint256 afterReserve0, uint256 afterReserve1 ) internal virtual returns (uint256 feeInPrecision) { // volume = beforeReserve0 * amount1In / beforeReserve1 + amount0In (normalized into amount in token 0) uint256 volume = beforeReserve0.mul(amount1In).div(beforeReserve1).add(amount0In); uint256 rFactorInPrecision = recordNewUpdatedVolume(block.number, volume); feeInPrecision = getFinalFee(FeeFomula.getFee(rFactorInPrecision), ampBps); // verify balance update matches with fomula uint256 balance0Adjusted = afterReserve0.mul(PRECISION); balance0Adjusted = balance0Adjusted.sub(amount0In.mul(feeInPrecision)); balance0Adjusted = balance0Adjusted / PRECISION; uint256 balance1Adjusted = afterReserve1.mul(PRECISION); balance1Adjusted = balance1Adjusted.sub(amount1In.mul(feeInPrecision)); balance1Adjusted = balance1Adjusted / PRECISION; require( balance0Adjusted.mul(balance1Adjusted) >= beforeReserve0.mul(beforeReserve1), "DMM: K" ); } /// @dev update reserves function _update(bool isAmpPool, ReserveData memory data) internal { reserve0 = safeUint112(data.reserve0); reserve1 = safeUint112(data.reserve1); if (isAmpPool) { assert(data.vReserve0 >= data.reserve0 && data.vReserve1 >= data.reserve1); // never happen vReserve0 = safeUint112(data.vReserve0); vReserve1 = safeUint112(data.vReserve1); } emit Sync(data.vReserve0, data.vReserve1, data.reserve0, data.reserve1); } /// @dev if fee is on, mint liquidity equivalent to configured fee of the growth in sqrt(k) function _mintFee(bool isAmpPool, ReserveData memory data) internal returns (bool feeOn) { (address feeTo, uint16 governmentFeeBps) = factory.getFeeConfiguration(); feeOn = feeTo != address(0); uint256 _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint256 rootK = MathExt.sqrt(getK(isAmpPool, data)); uint256 rootKLast = MathExt.sqrt(_kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply().mul(rootK.sub(rootKLast)).mul( governmentFeeBps ); uint256 denominator = rootK.add(rootKLast).mul(5000); uint256 liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } /// @dev gas saving to read reserve data function getReservesData() internal view returns (bool isAmpPool, ReserveData memory data) { data.reserve0 = reserve0; data.reserve1 = reserve1; isAmpPool = ampBps != BPS; if (isAmpPool) { data.vReserve0 = vReserve0; data.vReserve1 = vReserve1; } } function getFinalFee(uint256 feeInPrecision, uint32 _ampBps) internal pure returns (uint256) { if (_ampBps <= 20000) { return feeInPrecision; } else if (_ampBps <= 50000) { return (feeInPrecision * 20) / 30; } else if (_ampBps <= 200000) { return (feeInPrecision * 10) / 30; } else { return (feeInPrecision * 4) / 30; } } function getK(bool isAmpPool, ReserveData memory data) internal pure returns (uint256) { return isAmpPool ? data.vReserve0 * data.vReserve1 : data.reserve0 * data.reserve1; } function safeUint112(uint256 x) internal pure returns (uint112) { require(x <= MAX_UINT112, "DMM: OVERFLOW"); return uint112(x); } } // File: contracts/DMMFactory.sol pragma solidity 0.6.12; contract DMMFactory is IDMMFactory { using EnumerableSet for EnumerableSet.AddressSet; uint256 internal constant BPS = 10000; address private feeTo; uint16 private governmentFeeBps; address public override feeToSetter; mapping(IERC20 => mapping(IERC20 => EnumerableSet.AddressSet)) internal tokenPools; mapping(IERC20 => mapping(IERC20 => address)) public override getUnamplifiedPool; address[] public override allPools; event PoolCreated( IERC20 indexed token0, IERC20 indexed token1, address pool, uint32 ampBps, uint256 totalPool ); event SetFeeConfiguration(address feeTo, uint16 governmentFeeBps); event SetFeeToSetter(address feeToSetter); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; } function createPool( IERC20 tokenA, IERC20 tokenB, uint32 ampBps ) external override returns (address pool) { require(tokenA != tokenB, "DMM: IDENTICAL_ADDRESSES"); (IERC20 token0, IERC20 token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(address(token0) != address(0), "DMM: ZERO_ADDRESS"); require(ampBps >= BPS, "DMM: INVALID_BPS"); // only exist 1 unamplified pool of a pool. require( ampBps != BPS || getUnamplifiedPool[token0][token1] == address(0), "DMM: UNAMPLIFIED_POOL_EXISTS" ); pool = address(new DMMPool()); DMMPool(pool).initialize(token0, token1, ampBps); // populate mapping in the reverse direction tokenPools[token0][token1].add(pool); tokenPools[token1][token0].add(pool); if (ampBps == BPS) { getUnamplifiedPool[token0][token1] = pool; getUnamplifiedPool[token1][token0] = pool; } allPools.push(pool); emit PoolCreated(token0, token1, pool, ampBps, allPools.length); } function setFeeConfiguration(address _feeTo, uint16 _governmentFeeBps) external override { require(msg.sender == feeToSetter, "DMM: FORBIDDEN"); require(_governmentFeeBps > 0 && _governmentFeeBps < 2000, "DMM: INVALID FEE"); feeTo = _feeTo; governmentFeeBps = _governmentFeeBps; emit SetFeeConfiguration(_feeTo, _governmentFeeBps); } function setFeeToSetter(address _feeToSetter) external override { require(msg.sender == feeToSetter, "DMM: FORBIDDEN"); feeToSetter = _feeToSetter; emit SetFeeToSetter(_feeToSetter); } function getFeeConfiguration() external override view returns (address _feeTo, uint16 _governmentFeeBps) { _feeTo = feeTo; _governmentFeeBps = governmentFeeBps; } function allPoolsLength() external override view returns (uint256) { return allPools.length; } function getPools(IERC20 token0, IERC20 token1) external override view returns (address[] memory _tokenPools) { uint256 length = tokenPools[token0][token1].length(); _tokenPools = new address[](length); for (uint256 i = 0; i < length; i++) { _tokenPools[i] = tokenPools[token0][token1].at(i); } } function getPoolsLength(IERC20 token0, IERC20 token1) external view returns (uint256) { return tokenPools[token0][token1].length(); } function getPoolAtIndex( IERC20 token0, IERC20 token1, uint256 index ) external view returns (address pool) { return tokenPools[token0][token1].at(index); } function isPool( IERC20 token0, IERC20 token1, address pool ) external override view returns (bool) { return tokenPools[token0][token1].contains(pool); } }
returns reserve data to calculate amount to add liquidity
function getReserves() external override view returns (uint112 _reserve0, uint112 _reserve1) { _reserve0 = reserve0; _reserve1 = reserve1; }
2,135,931
// The Withdraw pattern was originally inspired by King of the Ether. // https://www.kingoftheether.com/thrones/kingoftheether/index.html // Example was modified from: // https://solidity.readthedocs.io/en/develop/common-patterns.html#withdrawal-pattern pragma solidity ^0.4.23; import "./SafeMath.sol"; contract Withdraw { using SafeMath for uint256; address public richest; uint256 public mostSent; uint256 public startAt; mapping (address => uint) public pendingWithdrawals; constructor(uint256 start) public payable { richest = msg.sender; mostSent = msg.value; startAt = start; } function stop() public { // 以太坊時間是以 unix time (seconds) 表示,並以uint256儲存 // 注意: 非一般 milliseconds // 支援的時間單位: // 1 == 1 seconds // 1 minutes == 60 seconds // 1 hours == 60 minutes // 1 days == 24 hours // 1 weeks == 7 days // 1 years == 365 days require( // 使用 '// solium-disable-next-line' 避免編譯器警告 // solium-disable-next-line security/no-block-members now >= (startAt + 30 days), "每次以太王活動必須至少舉行30天" ); require( msg.sender == richest, "只有以太王能結束活動" ); // 以太王收割韭菜 msg.sender.transfer(address(this).balance); } // 多載 (overloading) function stop(address beneficiary) public { require( beneficiary != address(0), "帳號不得為0x0" ); require( // 使用 '// solium-disable-next-line' 避免編譯器警告 // solium-disable-next-line security/no-block-members now >= (startAt + 30 days), "每次以太王活動必須至少舉行30天" ); require( msg.sender == richest, "只有以太王能結束活動" ); // 以太王收割韭菜 beneficiary.transfer(address(this).balance); } function becomeRichest() public payable returns (bool) { // wei 是以太坊最小貨幣單位,合約中大多透過wei作為貨幣計算單位 // 以太坊貨幣單位: wei, szabo, finney, ether (皆可在合約內直接使用) // 1 ether = 1e+18 wei // 1 ether = 1e+6 szabo // 1 ether = 1000 finney // 每次最少增加 1 ether if (msg.value.sub(mostSent) >= 1 ether) { pendingWithdrawals[richest] = ( pendingWithdrawals[richest].add(msg.value) ); richest = msg.sender; mostSent = msg.value; return true; } else { return false; } } function withdraw() public { uint amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } }
wei 是以太坊最小貨幣單位,合約中大多透過wei作為貨幣計算單位 以太坊貨幣單位: wei, szabo, finney, ether (皆可在合約內直接使用) 1 ether = 1e+18 wei 1 ether = 1e+6 szabo 1 ether = 1000 finney 每次最少增加 1 ether
function becomeRichest() public payable returns (bool) { if (msg.value.sub(mostSent) >= 1 ether) { pendingWithdrawals[richest] = ( pendingWithdrawals[richest].add(msg.value) ); richest = msg.sender; mostSent = msg.value; return true; return false; } }
12,698,482
./full_match/80001/0x50b4cB2C152322760a8fA59105A46745CE2B7Eac/sources/src/Libraries/LibAsset.sol
Transfers tokens from a sender to a given recipient assetId Token address to transfer from Address of sender/owner to Address of recipient/spender amount Amount to transfer from owner to spender
function transferFromERC20( address assetId, address from, address to, uint256 amount ) internal { if (assetId == NATIVE_ASSETID) revert NullAddrIsNotAnERC20Token(); if (to == NULL_ADDRESS) revert NoTransferToNullAddress(); IERC20 asset = IERC20(assetId); uint256 prevBalance = asset.balanceOf(to); SafeERC20.safeTransferFrom(asset, from, to, amount); if (asset.balanceOf(to) - prevBalance != amount) revert InvalidAmount(); }
9,508,313
./full_match/1/0xf01A54634266950fb7C2Fd1Cc288045AAfecbF0f/sources/contracts/DividendPayingToken.sol
Distributes ether to token holders as dividends. It reverts if the total supply of tokens is 0. It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. About undistributed ether: In each distribution, there is a small amount of ether not distributed, the magnified amount of which is `(msg.value magnitude) % totalSupply()`. With a well-chosen `magnitude`, the amount of undistributed ether (de-magnified) in a distribution can be less than 1 wei. We can actually keep track of the undistributed ether in a distribution and try to distribute it in the next distribution, but keeping track of such data on-chain costs much more than the saved ether, so we don't do that.
function distributeDividends() public override payable { require(totalSupply() > 0); if (msg.value > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add( (msg.value).mul(magnitude) / totalSupply() ); emit DividendsDistributed(msg.sender, msg.value); totalDividendsDistributed = totalDividendsDistributed.add(msg.value); } }
17,029,124
// SPDX-License-Identifier: Unlicense pragma solidity ^0.8.11; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./base/Errors.sol"; import "./interfaces/IWhitelist.sol"; import "./interfaces/transmuter/ITransmuterV2.sol"; import "./interfaces/transmuter/ITransmuterBuffer.sol"; import "./libraries/FixedPointMath.sol"; import "./libraries/LiquidityMath.sol"; import "./libraries/SafeCast.sol"; import "./libraries/Tick.sol"; import "./libraries/TokenUtils.sol"; /// @title TransmuterV2 /// /// @notice A contract which facilitates the exchange of synthetic assets for their underlying // asset. This contract guarantees that synthetic assets are exchanged exactly 1:1 // for the underlying asset. contract TransmuterV2 is ITransmuterV2, Initializable, ReentrancyGuardUpgradeable, AccessControlUpgradeable { using FixedPointMath for FixedPointMath.Number; using Tick for Tick.Cache; struct Account { // The total number of unexchanged tokens that an account has deposited into the system uint256 unexchangedBalance; // The total number of exchanged tokens that an account has had credited uint256 exchangedBalance; // The tick that the account has had their deposit associated in uint256 occupiedTick; } struct UpdateAccountParams { // The owner address whose account will be modified address owner; // The amount to change the account's unexchanged balance by int256 unexchangedDelta; // The amount to change the account's exchanged balance by int256 exchangedDelta; } struct ExchangeCache { // The total number of unexchanged tokens that exist at the start of the exchange call uint256 totalUnexchanged; // The tick which has been satisfied up to at the start of the exchange call uint256 satisfiedTick; // The head of the active ticks queue at the start of the exchange call uint256 ticksHead; } struct ExchangeState { // The position in the buffer of current tick which is being examined uint256 examineTick; // The total number of unexchanged tokens that currently exist in the system for the current distribution step uint256 totalUnexchanged; // The tick which has been satisfied up to, inclusive uint256 satisfiedTick; // The amount of tokens to distribute for the current step uint256 distributeAmount; // The accumulated weight to write at the new tick after the exchange is completed FixedPointMath.Number accumulatedWeight; // Reserved for the maximum weight of the current distribution step FixedPointMath.Number maximumWeight; // Reserved for the dusted weight of the current distribution step FixedPointMath.Number dustedWeight; } struct UpdateAccountCache { // The total number of unexchanged tokens that the account held at the start of the update call uint256 unexchangedBalance; // The total number of exchanged tokens that the account held at the start of the update call uint256 exchangedBalance; // The tick that the account's deposit occupies at the start of the update call uint256 occupiedTick; // The total number of unexchanged tokens that exist at the start of the update call uint256 totalUnexchanged; // The current tick that is being written to uint256 currentTick; } struct UpdateAccountState { // The updated unexchanged balance of the account being updated uint256 unexchangedBalance; // The updated exchanged balance of the account being updated uint256 exchangedBalance; // The updated total unexchanged balance uint256 totalUnexchanged; } address public constant ZERO_ADDRESS = address(0); /// @dev The identifier of the role which maintains other roles. bytes32 public constant ADMIN = keccak256("ADMIN"); /// @dev The identitifer of the sentinel role bytes32 public constant SENTINEL = keccak256("SENTINEL"); /// @inheritdoc ITransmuterV2 string public constant override version = "2.2.0"; /// @dev the synthetic token to be transmuted address public syntheticToken; /// @dev the underlying token to be received address public override underlyingToken; /// @dev The total amount of unexchanged tokens which are held by all accounts. uint256 public totalUnexchanged; /// @dev The total amount of tokens which are in the auxiliary buffer. uint256 public totalBuffered; /// @dev A mapping specifying all of the accounts. mapping(address => Account) private accounts; // @dev The tick buffer which stores all of the tick information along with the tick that is // currently being written to. The "current" tick is the tick at the buffer write position. Tick.Cache private ticks; // The tick which has been satisfied up to, inclusive. uint256 private satisfiedTick; /// @dev contract pause state bool public isPaused; /// @dev the source of the exchanged collateral address public buffer; /// @dev The address of the external whitelist contract. address public override whitelist; /// @dev The amount of decimal places needed to normalize collateral to debtToken uint256 public override conversionFactor; constructor() initializer {} function initialize( address _syntheticToken, address _underlyingToken, address _buffer, address _whitelist ) external initializer { _setupRole(ADMIN, msg.sender); _setRoleAdmin(ADMIN, ADMIN); _setRoleAdmin(SENTINEL, ADMIN); syntheticToken = _syntheticToken; underlyingToken = _underlyingToken; uint8 debtTokenDecimals = TokenUtils.expectDecimals(syntheticToken); uint8 underlyingTokenDecimals = TokenUtils.expectDecimals(underlyingToken); conversionFactor = 10**(debtTokenDecimals - underlyingTokenDecimals); buffer = _buffer; // Push a blank tick to function as a sentinel value in the active ticks queue. ticks.next(); isPaused = false; whitelist = _whitelist; } /// @dev A modifier which checks if caller is an alchemist. modifier onlyBuffer() { if (msg.sender != buffer) { revert Unauthorized(); } _; } /// @dev A modifier which checks if caller is a sentinel or admin. modifier onlySentinelOrAdmin() { if (!hasRole(SENTINEL, msg.sender) && !hasRole(ADMIN, msg.sender)) { revert Unauthorized(); } _; } /// @dev A modifier which checks if caller is a sentinel. modifier notPaused() { if (isPaused) { revert IllegalState(); } _; } function _onlyAdmin() internal view { if (!hasRole(ADMIN, msg.sender)) { revert Unauthorized(); } } function setCollateralSource(address _newCollateralSource) external { _onlyAdmin(); buffer = _newCollateralSource; } function setPause(bool pauseState) external onlySentinelOrAdmin { isPaused = pauseState; emit Paused(isPaused); } /// @inheritdoc ITransmuterV2 function deposit(uint256 amount, address owner) external override nonReentrant { _onlyWhitelisted(); _updateAccount( UpdateAccountParams({ owner: owner, unexchangedDelta: SafeCast.toInt256(amount), exchangedDelta: 0 }) ); TokenUtils.safeTransferFrom(syntheticToken, msg.sender, address(this), amount); emit Deposit(msg.sender, owner, amount); } /// @inheritdoc ITransmuterV2 function withdraw(uint256 amount, address recipient) external override nonReentrant { _onlyWhitelisted(); _updateAccount( UpdateAccountParams({ owner: msg.sender, unexchangedDelta: -SafeCast.toInt256(amount), exchangedDelta: 0 }) ); TokenUtils.safeTransfer(syntheticToken, recipient, amount); emit Withdraw(msg.sender, recipient, amount); } /// @inheritdoc ITransmuterV2 function claim(uint256 amount, address recipient) external override nonReentrant { _onlyWhitelisted(); _updateAccount( UpdateAccountParams({ owner: msg.sender, unexchangedDelta: 0, exchangedDelta: -SafeCast.toInt256(_normalizeUnderlyingTokensToDebt(amount)) }) ); TokenUtils.safeBurn(syntheticToken, _normalizeUnderlyingTokensToDebt(amount)); ITransmuterBuffer(buffer).withdraw(underlyingToken, amount, msg.sender); emit Claim(msg.sender, recipient, amount); } /// @inheritdoc ITransmuterV2 function exchange(uint256 amount) external override nonReentrant onlyBuffer notPaused { uint256 normaizedAmount = _normalizeUnderlyingTokensToDebt(amount); if (totalUnexchanged == 0) { totalBuffered += normaizedAmount; emit Exchange(msg.sender, amount); return; } // Push a storage reference to the current tick. Tick.Info storage current = ticks.current(); ExchangeCache memory cache = ExchangeCache({ totalUnexchanged: totalUnexchanged, satisfiedTick: satisfiedTick, ticksHead: ticks.head }); ExchangeState memory state = ExchangeState({ examineTick: cache.ticksHead, totalUnexchanged: cache.totalUnexchanged, satisfiedTick: cache.satisfiedTick, distributeAmount: normaizedAmount, accumulatedWeight: current.accumulatedWeight, maximumWeight: FixedPointMath.encode(0), dustedWeight: FixedPointMath.encode(0) }); // Distribute the buffered tokens as part of the exchange. state.distributeAmount += totalBuffered; totalBuffered = 0; // Push a storage reference to the next tick to write to. Tick.Info storage next = ticks.next(); // Only iterate through the active ticks queue when it is not empty. while (state.examineTick != 0) { // Check if there is anything left to distribute. if (state.distributeAmount == 0) { break; } Tick.Info storage examineTickData = ticks.get(state.examineTick); // Add the weight for the distribution step to the accumulated weight. state.accumulatedWeight = state.accumulatedWeight.add( FixedPointMath.rational(state.distributeAmount, state.totalUnexchanged) ); // Clear the distribute amount. state.distributeAmount = 0; // Calculate the current maximum weight in the system. state.maximumWeight = state.accumulatedWeight.sub(examineTickData.accumulatedWeight); // Check if there exists at least one account which is completely satisfied.. if (state.maximumWeight.n < FixedPointMath.ONE) { break; } // Calculate how much weight of the distributed weight is dust. state.dustedWeight = FixedPointMath.Number(state.maximumWeight.n - FixedPointMath.ONE); // Calculate how many tokens to distribute in the next step. These are tokens from any tokens which // were over allocated to accounts occupying the tick with the maximum weight. state.distributeAmount = LiquidityMath.calculateProduct(examineTickData.totalBalance, state.dustedWeight); // Remove the tokens which were completely exchanged from the total unexchanged balance. state.totalUnexchanged -= examineTickData.totalBalance; // Write that all ticks up to and including the examined tick have been satisfied. state.satisfiedTick = state.examineTick; // Visit the next active tick. This is equivalent to popping the head of the active ticks queue. state.examineTick = examineTickData.next; } // Write the accumulated weight to the next tick. next.accumulatedWeight = state.accumulatedWeight; if (cache.totalUnexchanged != state.totalUnexchanged) { totalUnexchanged = state.totalUnexchanged; } if (cache.satisfiedTick != state.satisfiedTick) { satisfiedTick = state.satisfiedTick; } if (cache.ticksHead != state.examineTick) { ticks.head = state.examineTick; } if (state.distributeAmount > 0) { totalBuffered += state.distributeAmount; } emit Exchange(msg.sender, amount); } /// @inheritdoc ITransmuterV2 function getUnexchangedBalance(address owner) external view override returns (uint256 unexchangedBalance) { Account storage account = accounts[owner]; if (account.occupiedTick <= satisfiedTick) { return 0; } unexchangedBalance = account.unexchangedBalance; uint256 exchanged = LiquidityMath.calculateProduct( unexchangedBalance, ticks.getWeight(account.occupiedTick, ticks.position) ); unexchangedBalance -= exchanged; return unexchangedBalance; } /// @inheritdoc ITransmuterV2 function getExchangedBalance(address owner) external view override returns (uint256 exchangedBalance) { return _getExchangedBalance(owner); } function getClaimableBalance(address owner) external view override returns (uint256 claimableBalance) { return _normalizeDebtTokensToUnderlying(_getExchangedBalance(owner)); } /// @dev Updates an account. /// /// @param params The call parameters. function _updateAccount(UpdateAccountParams memory params) internal { Account storage account = accounts[params.owner]; UpdateAccountCache memory cache = UpdateAccountCache({ unexchangedBalance: account.unexchangedBalance, exchangedBalance: account.exchangedBalance, occupiedTick: account.occupiedTick, totalUnexchanged: totalUnexchanged, currentTick: ticks.position }); UpdateAccountState memory state = UpdateAccountState({ unexchangedBalance: cache.unexchangedBalance, exchangedBalance: cache.exchangedBalance, totalUnexchanged: cache.totalUnexchanged }); // Updating an account is broken down into five steps: // 1). Synchronize the account if it previously occupied a satisfied tick // 2). Update the account balances to account for exchanged tokens, if any // 3). Apply the deltas to the account balances // 4). Update the previously occupied and or current tick's liquidity // 5). Commit changes to the account and global state when needed // Step one: // --------- // Check if the tick that the account was occupying previously was satisfied. If it was, we acknowledge // that all of the tokens were exchanged. if (state.unexchangedBalance > 0 && satisfiedTick >= cache.occupiedTick) { state.unexchangedBalance = 0; state.exchangedBalance += cache.unexchangedBalance; } // Step Two: // --------- // Calculate how many tokens were exchanged since the last update. if (state.unexchangedBalance > 0) { uint256 exchanged = LiquidityMath.calculateProduct( state.unexchangedBalance, ticks.getWeight(cache.occupiedTick, cache.currentTick) ); state.totalUnexchanged -= exchanged; state.unexchangedBalance -= exchanged; state.exchangedBalance += exchanged; } // Step Three: // ----------- // Apply the unexchanged and exchanged deltas to the state. state.totalUnexchanged = LiquidityMath.addDelta(state.totalUnexchanged, params.unexchangedDelta); state.unexchangedBalance = LiquidityMath.addDelta(state.unexchangedBalance, params.unexchangedDelta); state.exchangedBalance = LiquidityMath.addDelta(state.exchangedBalance, params.exchangedDelta); // Step Four: // ---------- // The following is a truth table relating various values which in combinations specify which logic branches // need to be executed in order to update liquidity in the previously occupied and or current tick. // // Some states are not obtainable and are just discarded by setting all the branches to false. // // | P | C | M | Modify Liquidity | Add Liquidity | Subtract Liquidity | // |---|---|---|------------------|---------------|--------------------| // | F | F | F | F | F | F | // | F | F | T | F | F | F | // | F | T | F | F | T | F | // | F | T | T | F | T | F | // | T | F | F | F | F | T | // | T | F | T | F | F | T | // | T | T | F | T | F | F | // | T | T | T | F | T | T | // // | Branch | Reduction | // |--------------------|-----------| // | Modify Liquidity | PCM' | // | Add Liquidity | P'C + CM | // | Subtract Liquidity | PC' + PM | bool previouslyActive = cache.unexchangedBalance > 0; bool currentlyActive = state.unexchangedBalance > 0; bool migrate = cache.occupiedTick != cache.currentTick; bool modifyLiquidity = previouslyActive && currentlyActive && !migrate; if (modifyLiquidity) { Tick.Info storage tick = ticks.get(cache.occupiedTick); // Consolidate writes to save gas. uint256 totalBalance = tick.totalBalance; totalBalance -= cache.unexchangedBalance; totalBalance += state.unexchangedBalance; tick.totalBalance = totalBalance; } else { bool addLiquidity = (!previouslyActive && currentlyActive) || (currentlyActive && migrate); bool subLiquidity = (previouslyActive && !currentlyActive) || (previouslyActive && migrate); if (addLiquidity) { Tick.Info storage tick = ticks.get(cache.currentTick); if (tick.totalBalance == 0) { ticks.addLast(cache.currentTick); } tick.totalBalance += state.unexchangedBalance; } if (subLiquidity) { Tick.Info storage tick = ticks.get(cache.occupiedTick); tick.totalBalance -= cache.unexchangedBalance; if (tick.totalBalance == 0) { ticks.remove(cache.occupiedTick); } } } // Step Five: // ---------- // Commit the changes to the account. if (cache.unexchangedBalance != state.unexchangedBalance) { account.unexchangedBalance = state.unexchangedBalance; } if (cache.exchangedBalance != state.exchangedBalance) { account.exchangedBalance = state.exchangedBalance; } if (cache.totalUnexchanged != state.totalUnexchanged) { totalUnexchanged = state.totalUnexchanged; } if (cache.occupiedTick != cache.currentTick) { account.occupiedTick = cache.currentTick; } } /// @dev Checks the whitelist for msg.sender. /// /// @notice Reverts if msg.sender is not in the whitelist. function _onlyWhitelisted() internal view { // Check if the message sender is an EOA. In the future, this potentially may break. It is important that // functions which rely on the whitelist not be explicitly vulnerable in the situation where this no longer // holds true. if (tx.origin != msg.sender) { // Only check the whitelist for calls from contracts. if (!IWhitelist(whitelist).isWhitelisted(msg.sender)) { revert Unauthorized(); } } } /// @dev Normalize `amount` of `underlyingToken` to a value which is comparable to units of the debt token. /// /// @param amount The amount of the debt token. /// /// @return The normalized amount. function _normalizeUnderlyingTokensToDebt(uint256 amount) internal view returns (uint256) { return amount * conversionFactor; } /// @dev Normalize `amount` of the debt token to a value which is comparable to units of `underlyingToken`. /// /// @dev This operation will result in truncation of some of the least significant digits of `amount`. This /// truncation amount will be the least significant N digits where N is the difference in decimals between /// the debt token and the underlying token. /// /// @param amount The amount of the debt token. /// /// @return The normalized amount. function _normalizeDebtTokensToUnderlying(uint256 amount) internal view returns (uint256) { return amount / conversionFactor; } function _getExchangedBalance(address owner) internal view returns (uint256 exchangedBalance) { Account storage account = accounts[owner]; if (account.occupiedTick <= satisfiedTick) { exchangedBalance = account.exchangedBalance; exchangedBalance += account.unexchangedBalance; return exchangedBalance; } exchangedBalance = account.exchangedBalance; uint256 exchanged = LiquidityMath.calculateProduct( account.unexchangedBalance, ticks.getWeight(account.occupiedTick, ticks.position) ); exchangedBalance += exchanged; return exchangedBalance; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } pragma solidity ^0.8.11; /// @notice An error used to indicate that an action could not be completed because either the `msg.sender` or /// `msg.origin` is not authorized. error Unauthorized(); /// @notice An error used to indicate that an action could not be completed because the contract either already existed /// or entered an illegal condition which is not recoverable from. error IllegalState(); /// @notice An error used to indicate that an action could not be completed because of an illegal argument was passed /// to the function. error IllegalArgument(); pragma solidity ^0.8.11; import "../base/Errors.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../libraries/Sets.sol"; /// @title Whitelist /// @author Alchemix Finance interface IWhitelist { /// @dev Emitted when a contract is added to the whitelist. /// /// @param account The account that was added to the whitelist. event AccountAdded(address account); /// @dev Emitted when a contract is removed from the whitelist. /// /// @param account The account that was removed from the whitelist. event AccountRemoved(address account); /// @dev Emitted when the whitelist is deactivated. event WhitelistDisabled(); /// @dev Returns the list of addresses that are whitelisted for the given contract address. /// /// @return addresses The addresses that are whitelisted to interact with the given contract. function getAddresses() external view returns (address[] memory addresses); /// @dev Returns the disabled status of a given whitelist. /// /// @return disabled A flag denoting if the given whitelist is disabled. function disabled() external view returns (bool); /// @dev Adds an contract to the whitelist. /// /// @param caller The address to add to the whitelist. function add(address caller) external; /// @dev Adds a contract to the whitelist. /// /// @param caller The address to remove from the whitelist. function remove(address caller) external; /// @dev Disables the whitelist of the target whitelisted contract. /// /// This can only occur once. Once the whitelist is disabled, then it cannot be reenabled. function disable() external; /// @dev Checks that the `msg.sender` is whitelisted when it is not an EOA. /// /// @param account The account to check. /// /// @return whitelisted A flag denoting if the given account is whitelisted. function isWhitelisted(address account) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; /// @title ITransmuterV2 /// @author Alchemix Finance interface ITransmuterV2 { /// @notice Emitted when the admin address is updated. /// /// @param admin The new admin address. event AdminUpdated(address admin); /// @notice Emitted when the pending admin address is updated. /// /// @param pendingAdmin The new pending admin address. event PendingAdminUpdated(address pendingAdmin); /// @notice Emitted when the system is paused or unpaused. /// /// @param flag `true` if the system has been paused, `false` otherwise. event Paused(bool flag); /// @dev Emitted when a deposit is performed. /// /// @param sender The address of the depositor. /// @param owner The address of the account that received the deposit. /// @param amount The amount of tokens deposited. event Deposit( address indexed sender, address indexed owner, uint256 amount ); /// @dev Emitted when a withdraw is performed. /// /// @param sender The address of the `msg.sender` executing the withdraw. /// @param recipient The address of the account that received the withdrawn tokens. /// @param amount The amount of tokens withdrawn. event Withdraw( address indexed sender, address indexed recipient, uint256 amount ); /// @dev Emitted when a claim is performed. /// /// @param sender The address of the claimer / account owner. /// @param recipient The address of the account that received the claimed tokens. /// @param amount The amount of tokens claimed. event Claim( address indexed sender, address indexed recipient, uint256 amount ); /// @dev Emitted when an exchange is performed. /// /// @param sender The address that called `exchange()`. /// @param amount The amount of tokens exchanged. event Exchange( address indexed sender, uint256 amount ); /// @notice Gets the version. /// /// @return The version. function version() external view returns (string memory); /// @dev Gets the supported underlying token. /// /// @return The underlying token. function underlyingToken() external view returns (address); /// @notice Gets the address of the whitelist contract. /// /// @return whitelist The address of the whitelist contract. function whitelist() external view returns (address whitelist); /// @dev Gets the unexchanged balance of an account. /// /// @param owner The address of the account owner. /// /// @return The unexchanged balance. function getUnexchangedBalance(address owner) external view returns (uint256); /// @dev Gets the exchanged balance of an account, in units of `debtToken`. /// /// @param owner The address of the account owner. /// /// @return The exchanged balance. function getExchangedBalance(address owner) external view returns (uint256); /// @dev Gets the claimable balance of an account, in units of `underlyingToken`. /// /// @param owner The address of the account owner. /// /// @return The claimable balance. function getClaimableBalance(address owner) external view returns (uint256); /// @dev The conversion factor used to convert between underlying token amounts and debt token amounts. /// /// @return The coversion factor. function conversionFactor() external view returns (uint256); /// @dev Deposits tokens to be exchanged into an account. /// /// @param amount The amount of tokens to deposit. /// @param owner The owner of the account to deposit the tokens into. function deposit(uint256 amount, address owner) external; /// @dev Withdraws tokens from the caller's account that were previously deposited to be exchanged. /// /// @param amount The amount of tokens to withdraw. /// @param recipient The address which will receive the withdrawn tokens. function withdraw(uint256 amount, address recipient) external; /// @dev Claims exchanged tokens. /// /// @param amount The amount of tokens to claim. /// @param recipient The address which will receive the claimed tokens. function claim(uint256 amount, address recipient) external; /// @dev Exchanges `amount` underlying tokens for `amount` synthetic tokens staked in the system. /// /// @param amount The amount of tokens to exchange. function exchange(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./ITransmuterV2.sol"; import "../IAlchemistV2.sol"; import "../IERC20TokenReceiver.sol"; /// @title ITransmuterBuffer /// @author Alchemix Finance interface ITransmuterBuffer is IERC20TokenReceiver { /// @notice Parameters used to define a given weighting schema. /// /// Weighting schemas can be used to generally weight assets in relation to an action or actions that will be taken. /// In the TransmuterBuffer, there are 2 actions that require weighting schemas: `burnCredit` and `depositFunds`. /// /// `burnCredit` uses a weighting schema that determines which yield-tokens are targeted when burning credit from /// the `Account` controlled by the TransmuterBuffer, via the `Alchemist.donate` function. /// /// `depositFunds` uses a weighting schema that determines which yield-tokens are targeted when depositing /// underlying-tokens into the Alchemist. struct Weighting { // The weights of the tokens used by the schema. mapping(address => uint256) weights; // The tokens used by the schema. address[] tokens; // The total weight of the schema (sum of the token weights). uint256 totalWeight; } /// @notice Emitted when the alchemist is set. /// /// @param alchemist The address of the alchemist. event SetAlchemist(address alchemist); /// @notice Emitted when an underlying token is registered. /// /// @param underlyingToken The address of the underlying token. /// @param transmuter The address of the transmuter for the underlying token. event RegisterAsset(address underlyingToken, address transmuter); /// @notice Emitted when an underlying token's flow rate is updated. /// /// @param underlyingToken The underlying token. /// @param flowRate The flow rate for the underlying token. event SetFlowRate(address underlyingToken, uint256 flowRate); /// @notice Emitted when the strategies are refreshed. event RefreshStrategies(); /// @notice Emitted when a source is set. event SetSource(address source, bool flag); /// @notice Emitted when a transmuter is updated. event SetTransmuter(address underlyingToken, address transmuter); /// @notice Gets the current version. /// /// @return The version. function version() external view returns (string memory); /// @notice Gets the total credit held by the TransmuterBuffer. /// /// @return The total credit. function getTotalCredit() external view returns (uint256); /// @notice Gets the total amount of underlying token that the TransmuterBuffer controls in the Alchemist. /// /// @param underlyingToken The underlying token to query. /// /// @return totalBuffered The total buffered. function getTotalUnderlyingBuffered(address underlyingToken) external view returns (uint256 totalBuffered); /// @notice Gets the total available flow for the underlying token /// /// The total available flow will be the lesser of `flowAvailable[token]` and `getTotalUnderlyingBuffered`. /// /// @param underlyingToken The underlying token to query. /// /// @return availableFlow The available flow. function getAvailableFlow(address underlyingToken) external view returns (uint256 availableFlow); /// @notice Gets the weight of the given weight type and token /// /// @param weightToken The type of weight to query. /// @param token The weighted token. /// /// @return weight The weight of the token for the given weight type. function getWeight(address weightToken, address token) external view returns (uint256 weight); /// @notice Set a source of funds. /// /// @param source The target source. /// @param flag The status to set for the target source. function setSource(address source, bool flag) external; /// @notice Set transmuter by admin. /// /// This function reverts if the caller is not the current admin. /// /// @param underlyingToken The target underlying token to update. /// @param newTransmuter The new transmuter for the target `underlyingToken`. function setTransmuter(address underlyingToken, address newTransmuter) external; /// @notice Set alchemist by admin. /// /// This function reverts if the caller is not the current admin. /// /// @param alchemist The new alchemist whose funds we are handling. function setAlchemist(address alchemist) external; /// @notice Refresh the yield-tokens in the TransmuterBuffer. /// /// This requires a call anytime governance adds a new yield token to the alchemist. function refreshStrategies() external; /// @notice Registers an underlying-token. /// /// This function reverts if the caller is not the current admin. /// /// @param underlyingToken The underlying-token being registered. /// @param transmuter The transmuter for the underlying-token. function registerAsset(address underlyingToken, address transmuter) external; /// @notice Set flow rate of an underlying token. /// /// This function reverts if the caller is not the current admin. /// /// @param underlyingToken The underlying-token getting the flow rate set. /// @param flowRate The new flow rate. function setFlowRate(address underlyingToken, uint256 flowRate) external; /// @notice Sets up a weighting schema. /// /// @param weightToken The name of the weighting schema. /// @param tokens The yield-tokens to weight. /// @param weights The weights of the yield tokens. function setWeights(address weightToken, address[] memory tokens, uint256[] memory weights) external; /// @notice Exchanges any available flow into the Transmuter. /// /// This function is a way for the keeper to force funds to be exchanged into the Transmuter. /// /// This function will revert if called by any account that is not a keeper. If there is not enough local balance of /// `underlyingToken` held by the TransmuterBuffer any additional funds will be withdrawn from the Alchemist by /// unwrapping `yieldToken`. /// /// @param underlyingToken The address of the underlying token to exchange. function exchange(address underlyingToken) external; /// @notice Burns available credit in the alchemist. function burnCredit() external; /// @notice Deposits local collateral into the alchemist /// /// @param underlyingToken The collateral to deposit. /// @param amount The amount to deposit. function depositFunds(address underlyingToken, uint256 amount) external; /// @notice Withdraws collateral from the alchemist /// /// This function reverts if: /// - The caller is not the transmuter. /// - There is not enough flow available to fulfill the request. /// - There is not enough underlying collateral in the alchemist controlled by the buffer to fulfil the request. /// /// @param underlyingToken The underlying token to withdraw. /// @param amount The amount to withdraw. /// @param recipient The account receiving the withdrawn funds. function withdraw( address underlyingToken, uint256 amount, address recipient ) external; /// @notice Withdraws collateral from the alchemist /// /// @param yieldToken The yield token to withdraw. /// @param shares The amount of Alchemist shares to withdraw. /// @param minimumAmountOut The minimum amount of underlying tokens needed to be recieved as a result of unwrapping the yield tokens. function withdrawFromAlchemist( address yieldToken, uint256 shares, uint256 minimumAmountOut ) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.11; /** * @notice A library which implements fixed point decimal math. */ library FixedPointMath { /** @dev This will give approximately 60 bits of precision */ uint256 public constant DECIMALS = 18; uint256 public constant ONE = 10**DECIMALS; /** * @notice A struct representing a fixed point decimal. */ struct Number { uint256 n; } /** * @notice Encodes a unsigned 256-bit integer into a fixed point decimal. * * @param value The value to encode. * @return The fixed point decimal representation. */ function encode(uint256 value) internal pure returns (Number memory) { return Number(FixedPointMath.encodeRaw(value)); } /** * @notice Encodes a unsigned 256-bit integer into a uint256 representation of a * fixed point decimal. * * @param value The value to encode. * @return The fixed point decimal representation. */ function encodeRaw(uint256 value) internal pure returns (uint256) { return value * ONE; } /** * @notice Encodes a uint256 MAX VALUE into a uint256 representation of a * fixed point decimal. * * @return The uint256 MAX VALUE fixed point decimal representation. */ function max() internal pure returns (Number memory) { return Number(type(uint256).max); } /** * @notice Creates a rational fraction as a Number from 2 uint256 values * * @param n The numerator. * @param d The denominator. * @return The fixed point decimal representation. */ function rational(uint256 n, uint256 d) internal pure returns (Number memory) { Number memory numerator = encode(n); return FixedPointMath.div(numerator, d); } /** * @notice Adds two fixed point decimal numbers together. * * @param self The left hand operand. * @param value The right hand operand. * @return The result. */ function add(Number memory self, Number memory value) internal pure returns (Number memory) { return Number(self.n + value.n); } /** * @notice Adds a fixed point number to a unsigned 256-bit integer. * * @param self The left hand operand. * @param value The right hand operand. This will be converted to a fixed point decimal. * @return The result. */ function add(Number memory self, uint256 value) internal pure returns (Number memory) { return add(self, FixedPointMath.encode(value)); } /** * @notice Subtract a fixed point decimal from another. * * @param self The left hand operand. * @param value The right hand operand. * @return The result. */ function sub(Number memory self, Number memory value) internal pure returns (Number memory) { return Number(self.n - value.n); } /** * @notice Subtract a unsigned 256-bit integer from a fixed point decimal. * * @param self The left hand operand. * @param value The right hand operand. This will be converted to a fixed point decimal. * @return The result. */ function sub(Number memory self, uint256 value) internal pure returns (Number memory) { return sub(self, FixedPointMath.encode(value)); } /** * @notice Multiplies a fixed point decimal by another fixed point decimal. * * @param self The fixed point decimal to multiply. * @param number The fixed point decimal to multiply by. * @return The result. */ function mul(Number memory self, Number memory number) internal pure returns (Number memory) { return Number((self.n * number.n) / ONE); } /** * @notice Multiplies a fixed point decimal by an unsigned 256-bit integer. * * @param self The fixed point decimal to multiply. * @param value The unsigned 256-bit integer to multiply by. * @return The result. */ function mul(Number memory self, uint256 value) internal pure returns (Number memory) { return Number(self.n * value); } /** * @notice Divides a fixed point decimal by an unsigned 256-bit integer. * * @param self The fixed point decimal to multiply by. * @param value The unsigned 256-bit integer to divide by. * @return The result. */ function div(Number memory self, uint256 value) internal pure returns (Number memory) { return Number(self.n / value); } /** * @notice Compares two fixed point decimals. * * @param self The left hand number to compare. * @param value The right hand number to compare. * @return When the left hand number is less than the right hand number this returns -1, * when the left hand number is greater than the right hand number this returns 1, * when they are equal this returns 0. */ function cmp(Number memory self, Number memory value) internal pure returns (int256) { if (self.n < value.n) { return -1; } if (self.n > value.n) { return 1; } return 0; } /** * @notice Gets if two fixed point numbers are equal. * * @param self the first fixed point number. * @param value the second fixed point number. * * @return if they are equal. */ function equals(Number memory self, Number memory value) internal pure returns (bool) { return self.n == value.n; } /** * @notice Truncates a fixed point decimal into an unsigned 256-bit integer. * * @return The integer portion of the fixed point decimal. */ function truncate(Number memory self) internal pure returns (uint256) { return self.n / ONE; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; import { IllegalArgument } from "../base/Errors.sol"; import { FixedPointMath } from "./FixedPointMath.sol"; /// @title LiquidityMath /// @author Alchemix Finance library LiquidityMath { using FixedPointMath for FixedPointMath.Number; /// @dev Adds a signed delta to an unsigned integer. /// /// @param x The unsigned value to add the delta to. /// @param y The signed delta value to add. /// @return z The result. function addDelta(uint256 x, int256 y) internal pure returns (uint256 z) { if (y < 0) { if ((z = x - uint256(-y)) >= x) { revert IllegalArgument(); } } else { if ((z = x + uint256(y)) < x) { revert IllegalArgument(); } } } /// @dev Calculate a uint256 representation of x * y using FixedPointMath /// /// @param x The first factor /// @param y The second factor (fixed point) /// @return z The resulting product, after truncation function calculateProduct(uint256 x, FixedPointMath.Number memory y) internal pure returns (uint256 z) { z = y.mul(x).truncate(); } /// @notice normalises non 18 digit token values to 18 digits. function normalizeValue(uint256 input, uint256 decimals) internal pure returns (uint256) { return (input * (10**18)) / (10**decimals); } /// @notice denormalizes 18 digits back to a token's digits function deNormalizeValue(uint256 input, uint256 decimals) internal pure returns (uint256) { return (input * (10**decimals)) / (10**18); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import {IllegalArgument} from "../base/Errors.sol"; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { if (y >= 2**255) { revert IllegalArgument(); } z = int256(y); } /// @notice Cast a int256 to a uint256, revert on underflow /// @param y The int256 to be casted /// @return z The casted integer, now type uint256 function toUint256(int256 y) internal pure returns (uint256 z) { if (y < 0) { revert IllegalArgument(); } z = uint256(y); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; import {FixedPointMath} from "./FixedPointMath.sol"; library Tick { using FixedPointMath for FixedPointMath.Number; struct Info { // The total number of unexchanged tokens that have been associated with this tick uint256 totalBalance; // The accumulated weight of the tick which is the sum of the previous ticks accumulated weight plus the weight // that added at the time that this tick was created FixedPointMath.Number accumulatedWeight; // The previous active node. When this value is zero then there is no predecessor uint256 prev; // The next active node. When this value is zero then there is no successor uint256 next; } struct Cache { // The mapping which specifies the ticks in the buffer mapping(uint256 => Info) values; // The current tick which is being written to uint256 position; // The first tick which will be examined when iterating through the queue uint256 head; // The last tick which new nodes will be appended after uint256 tail; } /// @dev Gets the next tick in the buffer. /// /// This increments the position in the buffer. /// /// @return The next tick. function next(Tick.Cache storage self) internal returns (Tick.Info storage) { self.position++; return self.values[self.position]; } /// @dev Gets the current tick being written to. /// /// @return The current tick. function current(Tick.Cache storage self) internal view returns (Tick.Info storage) { return self.values[self.position]; } /// @dev Gets the nth tick in the buffer. /// /// @param self The reference to the buffer. /// @param n The nth tick to get. function get(Tick.Cache storage self, uint256 n) internal view returns (Tick.Info storage) { return self.values[n]; } function getWeight( Tick.Cache storage self, uint256 from, uint256 to ) internal view returns (FixedPointMath.Number memory) { Tick.Info storage startingTick = self.values[from]; Tick.Info storage endingTick = self.values[to]; FixedPointMath.Number memory startingAccumulatedWeight = startingTick.accumulatedWeight; FixedPointMath.Number memory endingAccumulatedWeight = endingTick.accumulatedWeight; return endingAccumulatedWeight.sub(startingAccumulatedWeight); } function addLast(Tick.Cache storage self, uint256 id) internal { if (self.head == 0) { self.head = self.tail = id; return; } // Don't add the tick if it is already the tail. This has to occur after the check if the head // is null since the tail may not be updated once the queue is made empty. if (self.tail == id) { return; } Tick.Info storage tick = self.values[id]; Tick.Info storage tail = self.values[self.tail]; tick.prev = self.tail; tail.next = id; self.tail = id; } function remove(Tick.Cache storage self, uint256 id) internal { Tick.Info storage tick = self.values[id]; // Update the head if it is the tick we are removing. if (self.head == id) { self.head = tick.next; } // Update the tail if it is the tick we are removing. if (self.tail == id) { self.tail = tick.prev; } // Unlink the previously occupied tick from the next tick in the list. if (tick.prev != 0) { self.values[tick.prev].next = tick.next; } // Unlink the previously occupied tick from the next tick in the list. if (tick.next != 0) { self.values[tick.next].prev = tick.prev; } // Zero out the pointers. // NOTE(nomad): This fixes the bug where the current accrued weight would get erased. self.values[id].next = 0; self.values[id].prev = 0; } } pragma solidity ^0.8.11; import "../interfaces/IERC20Burnable.sol"; import "../interfaces/IERC20Metadata.sol"; import "../interfaces/IERC20Minimal.sol"; import "../interfaces/IERC20Mintable.sol"; /// @title TokenUtils /// @author Alchemix Finance library TokenUtils { /// @notice An error used to indicate that a call to an ERC20 contract failed. /// /// @param target The target address. /// @param success If the call to the token was a success. /// @param data The resulting data from the call. This is error data when the call was not a success. Otherwise, /// this is malformed data when the call was a success. error ERC20CallFailed(address target, bool success, bytes data); /// @dev A safe function to get the decimals of an ERC20 token. /// /// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value. /// /// @param token The target token. /// /// @return The amount of decimals of the token. function expectDecimals(address token) internal view returns (uint8) { (bool success, bytes memory data) = token.staticcall( abi.encodeWithSelector(IERC20Metadata.decimals.selector) ); if (!success || data.length < 32) { revert ERC20CallFailed(token, success, data); } return abi.decode(data, (uint8)); } /// @dev Gets the balance of tokens held by an account. /// /// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value. /// /// @param token The token to check the balance of. /// @param account The address of the token holder. /// /// @return The balance of the tokens held by an account. function safeBalanceOf(address token, address account) internal view returns (uint256) { (bool success, bytes memory data) = token.staticcall( abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, account) ); if (!success || data.length < 32) { revert ERC20CallFailed(token, success, data); } return abi.decode(data, (uint256)); } /// @dev Transfers tokens to another address. /// /// @dev Reverts with a {CallFailed} error if execution of the transfer failed or returns an unexpected value. /// /// @param token The token to transfer. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to transfer. function safeTransfer(address token, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.transfer.selector, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Approves tokens for the smart contract. /// /// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an unexpected value. /// /// @param token The token to approve. /// @param spender The contract to spend the tokens. /// @param value The amount of tokens to approve. function safeApprove(address token, address spender, uint256 value) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, value) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Transfer tokens from one address to another address. /// /// @dev Reverts with a {CallFailed} error if execution of the transfer fails or returns an unexpected value. /// /// @param token The token to transfer. /// @param owner The address of the owner. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to transfer. function safeTransferFrom(address token, address owner, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.transferFrom.selector, owner, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Mints tokens to an address. /// /// @dev Reverts with a {CallFailed} error if execution of the mint fails or returns an unexpected value. /// /// @param token The token to mint. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to mint. function safeMint(address token, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Mintable.mint.selector, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Burns tokens. /// /// Reverts with a `CallFailed` error if execution of the burn fails or returns an unexpected value. /// /// @param token The token to burn. /// @param amount The amount of tokens to burn. function safeBurn(address token, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Burnable.burn.selector, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Burns tokens from its total supply. /// /// @dev Reverts with a {CallFailed} error if execution of the burn fails or returns an unexpected value. /// /// @param token The token to burn. /// @param owner The owner of the tokens. /// @param amount The amount of tokens to burn. function safeBurnFrom(address token, address owner, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Burnable.burnFrom.selector, owner, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // 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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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); } } pragma solidity ^0.8.11; /// @title Sets /// @author Alchemix Finance library Sets { using Sets for AddressSet; /// @notice A data structure holding an array of values with an index mapping for O(1) lookup. struct AddressSet { address[] values; mapping(address => uint256) indexes; } /// @dev Add a value to a Set /// /// @param self The Set. /// @param value The value to add. /// /// @return Whether the operation was successful (unsuccessful if the value is already contained in the Set) function add(AddressSet storage self, address value) internal returns (bool) { if (self.contains(value)) { return false; } self.values.push(value); self.indexes[value] = self.values.length; return true; } /// @dev Remove a value from a Set /// /// @param self The Set. /// @param value The value to remove. /// /// @return Whether the operation was successful (unsuccessful if the value was not contained in the Set) function remove(AddressSet storage self, address value) internal returns (bool) { uint256 index = self.indexes[value]; if (index == 0) { return false; } // Normalize the index since we know that the element is in the set. index--; uint256 lastIndex = self.values.length - 1; if (index != lastIndex) { address lastValue = self.values[lastIndex]; self.values[index] = lastValue; self.indexes[lastValue] = index + 1; } self.values.pop(); delete self.indexes[value]; return true; } /// @dev Returns true if the value exists in the Set /// /// @param self The Set. /// @param value The value to check. /// /// @return True if the value is contained in the Set, False if it is not. function contains(AddressSet storage self, address value) internal view returns (bool) { return self.indexes[value] != 0; } } // 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 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity >=0.5.0; import "./alchemist/IAlchemistV2Actions.sol"; import "./alchemist/IAlchemistV2AdminActions.sol"; import "./alchemist/IAlchemistV2Errors.sol"; import "./alchemist/IAlchemistV2Immutables.sol"; import "./alchemist/IAlchemistV2Events.sol"; import "./alchemist/IAlchemistV2State.sol"; /// @title IAlchemistV2 /// @author Alchemix Finance interface IAlchemistV2 is IAlchemistV2Actions, IAlchemistV2AdminActions, IAlchemistV2Errors, IAlchemistV2Immutables, IAlchemistV2Events, IAlchemistV2State { } pragma solidity >=0.5.0; /// @title IERC20TokenReceiver /// @author Alchemix Finance interface IERC20TokenReceiver { /// @notice Informs implementors of this interface that an ERC20 token has been transferred. /// /// @param token The token that was transferred. /// @param value The amount of the token that was transferred. function onERC20Received(address token, uint256 value) external; } pragma solidity >=0.5.0; /// @title IAlchemistV2Actions /// @author Alchemix Finance /// /// @notice Specifies user actions. interface IAlchemistV2Actions { /// @notice Approve `spender` to mint `amount` debt tokens. /// /// **_NOTE:_** This function is WHITELISTED. /// /// @param spender The address that will be approved to mint. /// @param amount The amount of tokens that `spender` will be allowed to mint. function approveMint(address spender, uint256 amount) external; /// @notice Approve `spender` to withdraw `amount` shares of `yieldToken`. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @param spender The address that will be approved to withdraw. /// @param yieldToken The address of the yield token that `spender` will be allowed to withdraw. /// @param shares The amount of shares that `spender` will be allowed to withdraw. function approveWithdraw( address spender, address yieldToken, uint256 shares ) external; /// @notice Synchronizes the state of the account owned by `owner`. /// /// @param owner The owner of the account to synchronize. function poke(address owner) external; /// @notice Deposit a yield token into a user's account. /// /// @notice An approval must be set for `yieldToken` which is greater than `amount`. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error. /// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error. /// /// @notice Emits a {Deposit} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **yieldToken** being deposited. This can be done via the standard `ERC20.approve()` method. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 amount = 50000; /// @notice IERC20(ydai).approve(alchemistAddress, amount); /// @notice AlchemistV2(alchemistAddress).deposit(ydai, amount, msg.sender); /// @notice ``` /// /// @param yieldToken The yield-token to deposit. /// @param amount The amount of yield tokens to deposit. /// @param recipient The owner of the account that will receive the resulting shares. /// /// @return sharesIssued The number of shares issued to `recipient`. function deposit( address yieldToken, uint256 amount, address recipient ) external returns (uint256 sharesIssued); /// @notice Deposit an underlying token into the account of `recipient` as `yieldToken`. /// /// @notice An approval must be set for the underlying token of `yieldToken` which is greater than `amount`. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error. /// /// @notice Emits a {Deposit} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **underlyingToken** being deposited. This can be done via the standard `ERC20.approve()` method. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 amount = 50000; /// @notice AlchemistV2(alchemistAddress).depositUnderlying(ydai, amount, msg.sender, 1); /// @notice ``` /// /// @param yieldToken The address of the yield token to wrap the underlying tokens into. /// @param amount The amount of the underlying token to deposit. /// @param recipient The address of the recipient. /// @param minimumAmountOut The minimum amount of yield tokens that are expected to be deposited to `recipient`. /// /// @return sharesIssued The number of shares issued to `recipient`. function depositUnderlying( address yieldToken, uint256 amount, address recipient, uint256 minimumAmountOut ) external returns (uint256 sharesIssued); /// @notice Withdraw yield tokens to `recipient` by burning `share` shares. The number of yield tokens withdrawn to `recipient` will depend on the value of shares for that yield token at the time of the call. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// /// @notice Emits a {Withdraw} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai); /// @notice uint256 amtYieldTokens = 5000; /// @notice AlchemistV2(alchemistAddress).withdraw(ydai, amtYieldTokens / pps, msg.sender); /// @notice ``` /// /// @param yieldToken The address of the yield token to withdraw. /// @param shares The number of shares to burn. /// @param recipient The address of the recipient. /// /// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`. function withdraw( address yieldToken, uint256 shares, address recipient ) external returns (uint256 amountWithdrawn); /// @notice Withdraw yield tokens to `recipient` by burning `share` shares from the account of `owner` /// /// @notice `owner` must have an withdrawal allowance which is greater than `amount` for this call to succeed. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// /// @notice Emits a {Withdraw} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai); /// @notice uint256 amtYieldTokens = 5000; /// @notice AlchemistV2(alchemistAddress).withdrawFrom(msg.sender, ydai, amtYieldTokens / pps, msg.sender); /// @notice ``` /// /// @param owner The address of the account owner to withdraw from. /// @param yieldToken The address of the yield token to withdraw. /// @param shares The number of shares to burn. /// @param recipient The address of the recipient. /// /// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`. function withdrawFrom( address owner, address yieldToken, uint256 shares, address recipient ) external returns (uint256 amountWithdrawn); /// @notice Withdraw underlying tokens to `recipient` by burning `share` shares and unwrapping the yield tokens that the shares were redeemed for. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error. /// /// @notice Emits a {Withdraw} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai); /// @notice uint256 amountUnderlyingTokens = 5000; /// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(ydai, amountUnderlyingTokens / pps, msg.sender, 1); /// @notice ``` /// /// @param yieldToken The address of the yield token to withdraw. /// @param shares The number of shares to burn. /// @param recipient The address of the recipient. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`. /// /// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`. function withdrawUnderlying( address yieldToken, uint256 shares, address recipient, uint256 minimumAmountOut ) external returns (uint256 amountWithdrawn); /// @notice Withdraw underlying tokens to `recipient` by burning `share` shares from the account of `owner` and unwrapping the yield tokens that the shares were redeemed for. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error. /// /// @notice Emits a {Withdraw} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai); /// @notice uint256 amtUnderlyingTokens = 5000 * 10**ydai.decimals(); /// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(msg.sender, ydai, amtUnderlyingTokens / pps, msg.sender, 1); /// @notice ``` /// /// @param owner The address of the account owner to withdraw from. /// @param yieldToken The address of the yield token to withdraw. /// @param shares The number of shares to burn. /// @param recipient The address of the recipient. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`. /// /// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`. function withdrawUnderlyingFrom( address owner, address yieldToken, uint256 shares, address recipient, uint256 minimumAmountOut ) external returns (uint256 amountWithdrawn); /// @notice Mint `amount` debt tokens. /// /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// /// @notice Emits a {Mint} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice uint256 amtDebt = 5000; /// @notice AlchemistV2(alchemistAddress).mint(amtDebt, msg.sender); /// @notice ``` /// /// @param amount The amount of tokens to mint. /// @param recipient The address of the recipient. function mint(uint256 amount, address recipient) external; /// @notice Mint `amount` debt tokens from the account owned by `owner` to `recipient`. /// /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// /// @notice Emits a {Mint} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// @notice **_NOTE:_** The caller of `mintFrom()` must have **mintAllowance()** to mint debt from the `Account` controlled by **owner** for at least the amount of **yieldTokens** that **shares** will be converted to. This can be done via the `approveMint()` or `permitMint()` methods. /// /// @notice **Example:** /// @notice ``` /// @notice uint256 amtDebt = 5000; /// @notice AlchemistV2(alchemistAddress).mintFrom(msg.sender, amtDebt, msg.sender); /// @notice ``` /// /// @param owner The address of the owner of the account to mint from. /// @param amount The amount of tokens to mint. /// @param recipient The address of the recipient. function mintFrom( address owner, uint256 amount, address recipient ) external; /// @notice Burn `amount` debt tokens to credit the account owned by `recipient`. /// /// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds. /// /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// @notice `recipient` must have non-zero debt or this call will revert with an {IllegalState} error. /// /// @notice Emits a {Burn} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice uint256 amtBurn = 5000; /// @notice AlchemistV2(alchemistAddress).burn(amtBurn, msg.sender); /// @notice ``` /// /// @param amount The amount of tokens to burn. /// @param recipient The address of the recipient. /// /// @return amountBurned The amount of tokens that were burned. function burn(uint256 amount, address recipient) external returns (uint256 amountBurned); /// @notice Repay `amount` debt using `underlyingToken` to credit the account owned by `recipient`. /// /// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds. /// /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `underlyingToken` must be enabled or this call will revert with a {TokenDisabled} error. /// @notice `amount` must be less than or equal to the current available repay limit or this call will revert with a {ReplayLimitExceeded} error. /// /// @notice Emits a {Repay} event. /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address dai = 0x6b175474e89094c44da98b954eedeac495271d0f; /// @notice uint256 amtRepay = 5000; /// @notice AlchemistV2(alchemistAddress).repay(dai, amtRepay, msg.sender); /// @notice ``` /// /// @param underlyingToken The address of the underlying token to repay. /// @param amount The amount of the underlying token to repay. /// @param recipient The address of the recipient which will receive credit. /// /// @return amountRepaid The amount of tokens that were repaid. function repay( address underlyingToken, uint256 amount, address recipient ) external returns (uint256 amountRepaid); /// @notice /// /// @notice `shares` will be limited up to an equal amount of debt that `recipient` currently holds. /// /// @notice `shares` must be greater than zero or this call will revert with a {IllegalArgument} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error. /// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error. /// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error. /// @notice `amount` must be less than or equal to the current available liquidation limit or this call will revert with a {LiquidationLimitExceeded} error. /// /// @notice Emits a {Liquidate} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 amtSharesLiquidate = 5000 * 10**ydai.decimals(); /// @notice AlchemistV2(alchemistAddress).liquidate(ydai, amtSharesLiquidate, 1); /// @notice ``` /// /// @param yieldToken The address of the yield token to liquidate. /// @param shares The number of shares to burn for credit. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be liquidated. /// /// @return sharesLiquidated The amount of shares that were liquidated. function liquidate( address yieldToken, uint256 shares, uint256 minimumAmountOut ) external returns (uint256 sharesLiquidated); /// @notice Burns `amount` debt tokens to credit accounts which have deposited `yieldToken`. /// /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits a {Donate} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 amtSharesLiquidate = 5000; /// @notice AlchemistV2(alchemistAddress).liquidate(dai, amtSharesLiquidate, 1); /// @notice ``` /// /// @param yieldToken The address of the yield token to credit accounts for. /// @param amount The amount of debt tokens to burn. function donate(address yieldToken, uint256 amount) external; /// @notice Harvests outstanding yield that a yield token has accumulated and distributes it as credit to holders. /// /// @notice `msg.sender` must be a keeper or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice The amount being harvested must be greater than zero or else this call will revert with an {IllegalState} error. /// /// @notice Emits a {Harvest} event. /// /// @param yieldToken The address of the yield token to harvest. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`. function harvest(address yieldToken, uint256 minimumAmountOut) external; } pragma solidity >=0.5.0; /// @title IAlchemistV2AdminActions /// @author Alchemix Finance /// /// @notice Specifies admin and or sentinel actions. interface IAlchemistV2AdminActions { /// @notice Contract initialization parameters. struct InitializationParams { // The initial admin account. address admin; // The ERC20 token used to represent debt. address debtToken; // The initial transmuter or transmuter buffer. address transmuter; // The minimum collateralization ratio that an account must maintain. uint256 minimumCollateralization; // The percentage fee taken from each harvest measured in units of basis points. uint256 protocolFee; // The address that receives protocol fees. address protocolFeeReceiver; // A limit used to prevent administrators from making minting functionality inoperable. uint256 mintingLimitMinimum; // The maximum number of tokens that can be minted per period of time. uint256 mintingLimitMaximum; // The number of blocks that it takes for the minting limit to be refreshed. uint256 mintingLimitBlocks; // The address of the whitelist. address whitelist; } /// @notice Configuration parameters for an underlying token. struct UnderlyingTokenConfig { // A limit used to prevent administrators from making repayment functionality inoperable. uint256 repayLimitMinimum; // The maximum number of underlying tokens that can be repaid per period of time. uint256 repayLimitMaximum; // The number of blocks that it takes for the repayment limit to be refreshed. uint256 repayLimitBlocks; // A limit used to prevent administrators from making liquidation functionality inoperable. uint256 liquidationLimitMinimum; // The maximum number of underlying tokens that can be liquidated per period of time. uint256 liquidationLimitMaximum; // The number of blocks that it takes for the liquidation limit to be refreshed. uint256 liquidationLimitBlocks; } /// @notice Configuration parameters of a yield token. struct YieldTokenConfig { // The adapter used by the system to interop with the token. address adapter; // The maximum percent loss in expected value that can occur before certain actions are disabled measured in // units of basis points. uint256 maximumLoss; // The maximum value that can be held by the system before certain actions are disabled measured in the // underlying token. uint256 maximumExpectedValue; // The number of blocks that credit will be distributed over to depositors. uint256 creditUnlockBlocks; } /// @notice Initialize the contract. /// /// @notice `params.protocolFee` must be in range or this call will with an {IllegalArgument} error. /// @notice The minting growth limiter parameters must be valid or this will revert with an {IllegalArgument} error. For more information, see the {Limiters} library. /// /// @notice Emits an {AdminUpdated} event. /// @notice Emits a {TransmuterUpdated} event. /// @notice Emits a {MinimumCollateralizationUpdated} event. /// @notice Emits a {ProtocolFeeUpdated} event. /// @notice Emits a {ProtocolFeeReceiverUpdated} event. /// @notice Emits a {MintingLimitUpdated} event. /// /// @param params The contract initialization parameters. function initialize(InitializationParams memory params) external; /// @notice Sets the pending administrator. /// /// @notice `msg.sender` must be the admin or this call will will revert with an {Unauthorized} error. /// /// @notice Emits a {PendingAdminUpdated} event. /// /// @dev This is the first step in the two-step process of setting a new administrator. After this function is called, the pending administrator will then need to call {acceptAdmin} to complete the process. /// /// @param value the address to set the pending admin to. function setPendingAdmin(address value) external; /// @notice Allows for `msg.sender` to accepts the role of administrator. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice The current pending administrator must be non-zero or this call will revert with an {IllegalState} error. /// /// @dev This is the second step in the two-step process of setting a new administrator. After this function is successfully called, this pending administrator will be reset and the new administrator will be set. /// /// @notice Emits a {AdminUpdated} event. /// @notice Emits a {PendingAdminUpdated} event. function acceptAdmin() external; /// @notice Sets an address as a sentinel. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @param sentinel The address to set or unset as a sentinel. /// @param flag A flag indicating of the address should be set or unset as a sentinel. function setSentinel(address sentinel, bool flag) external; /// @notice Sets an address as a keeper. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @param keeper The address to set or unset as a keeper. /// @param flag A flag indicating of the address should be set or unset as a keeper. function setKeeper(address keeper, bool flag) external; /// @notice Adds an underlying token to the system. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @param underlyingToken The address of the underlying token to add. /// @param config The initial underlying token configuration. function addUnderlyingToken( address underlyingToken, UnderlyingTokenConfig calldata config ) external; /// @notice Adds a yield token to the system. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @notice Emits a {AddYieldToken} event. /// @notice Emits a {TokenAdapterUpdated} event. /// @notice Emits a {MaximumLossUpdated} event. /// /// @param yieldToken The address of the yield token to add. /// @param config The initial yield token configuration. function addYieldToken(address yieldToken, YieldTokenConfig calldata config) external; /// @notice Sets an underlying token as either enabled or disabled. /// /// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error. /// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits an {UnderlyingTokenEnabled} event. /// /// @param underlyingToken The address of the underlying token to enable or disable. /// @param enabled If the underlying token should be enabled or disabled. function setUnderlyingTokenEnabled(address underlyingToken, bool enabled) external; /// @notice Sets a yield token as either enabled or disabled. /// /// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits a {YieldTokenEnabled} event. /// /// @param yieldToken The address of the yield token to enable or disable. /// @param enabled If the underlying token should be enabled or disabled. function setYieldTokenEnabled(address yieldToken, bool enabled) external; /// @notice Configures the the repay limit of `underlyingToken`. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits a {ReplayLimitUpdated} event. /// /// @param underlyingToken The address of the underlying token to configure the repay limit of. /// @param maximum The maximum repay limit. /// @param blocks The number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted. function configureRepayLimit( address underlyingToken, uint256 maximum, uint256 blocks ) external; /// @notice Configure the liquidation limiter of `underlyingToken`. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits a {LiquidationLimitUpdated} event. /// /// @param underlyingToken The address of the underlying token to configure the liquidation limit of. /// @param maximum The maximum liquidation limit. /// @param blocks The number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted. function configureLiquidationLimit( address underlyingToken, uint256 maximum, uint256 blocks ) external; /// @notice Set the address of the transmuter. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error. /// /// @notice Emits a {TransmuterUpdated} event. /// /// @param value The address of the transmuter. function setTransmuter(address value) external; /// @notice Set the minimum collateralization ratio. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @notice Emits a {MinimumCollateralizationUpdated} event. /// /// @param value The new minimum collateralization ratio. function setMinimumCollateralization(uint256 value) external; /// @notice Sets the fee that the protocol will take from harvests. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `value` must be in range or this call will with an {IllegalArgument} error. /// /// @notice Emits a {ProtocolFeeUpdated} event. /// /// @param value The value to set the protocol fee to measured in basis points. function setProtocolFee(uint256 value) external; /// @notice Sets the address which will receive protocol fees. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error. /// /// @notice Emits a {ProtocolFeeReceiverUpdated} event. /// /// @param value The address to set the protocol fee receiver to. function setProtocolFeeReceiver(address value) external; /// @notice Configures the minting limiter. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @notice Emits a {MintingLimitUpdated} event. /// /// @param maximum The maximum minting limit. /// @param blocks The number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted. function configureMintingLimit(uint256 maximum, uint256 blocks) external; /// @notice Sets the rate at which credit will be completely available to depositors after it is harvested. /// /// @notice Emits a {CreditUnlockRateUpdated} event. /// /// @param yieldToken The address of the yield token to set the credit unlock rate for. /// @param blocks The number of blocks that it will take before the credit will be unlocked. function configureCreditUnlockRate(address yieldToken, uint256 blocks) external; /// @notice Sets the token adapter of a yield token. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice The token that `adapter` supports must be `yieldToken` or this call will revert with a {IllegalState} error. /// /// @notice Emits a {TokenAdapterUpdated} event. /// /// @param yieldToken The address of the yield token to set the adapter for. /// @param adapter The address to set the token adapter to. function setTokenAdapter(address yieldToken, address adapter) external; /// @notice Sets the maximum expected value of a yield token that the system can hold. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @param yieldToken The address of the yield token to set the maximum expected value for. /// @param value The maximum expected value of the yield token denoted measured in its underlying token. function setMaximumExpectedValue(address yieldToken, uint256 value) external; /// @notice Sets the maximum loss that a yield bearing token will permit before restricting certain actions. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @dev There are two types of loss of value for yield bearing assets: temporary or permanent. The system will automatically restrict actions which are sensitive to both forms of loss when detected. For example, deposits must be restricted when an excessive loss is encountered to prevent users from having their collateral harvested from them. While the user would receive credit, which then could be exchanged for value equal to the collateral that was harvested from them, it is seen as a negative user experience because the value of their collateral should have been higher than what was originally recorded when they made their deposit. /// /// @param yieldToken The address of the yield bearing token to set the maximum loss for. /// @param value The value to set the maximum loss to. This is in units of basis points. function setMaximumLoss(address yieldToken, uint256 value) external; /// @notice Snap the expected value `yieldToken` to the current value. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @dev This function should only be used in the event of a loss in the target yield-token. For example, say a third-party protocol experiences a fifty percent loss. The expected value (amount of underlying tokens) of the yield tokens being held by the system would be two times the real value that those yield tokens could be redeemed for. This function gives governance a way to realize those losses so that users can continue using the token as normal. /// /// @param yieldToken The address of the yield token to snap. function snap(address yieldToken) external; } pragma solidity >=0.5.0; /// @title IAlchemistV2Errors /// @author Alchemix Finance /// /// @notice Specifies errors. interface IAlchemistV2Errors { /// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that the system did not recognize. /// /// @param token The address of the token. error UnsupportedToken(address token); /// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that has been disabled. /// /// @param token The address of the token. error TokenDisabled(address token); /// @notice An error which is used to indicate that an operation failed because an account became undercollateralized. error Undercollateralized(); /// @notice An error which is used to indicate that an operation failed because the expected value of a yield token in the system exceeds the maximum value permitted. /// /// @param yieldToken The address of the yield token. /// @param expectedValue The expected value measured in units of the underlying token. /// @param maximumExpectedValue The maximum expected value permitted measured in units of the underlying token. error ExpectedValueExceeded(address yieldToken, uint256 expectedValue, uint256 maximumExpectedValue); /// @notice An error which is used to indicate that an operation failed because the loss that a yield token in the system exceeds the maximum value permitted. /// /// @param yieldToken The address of the yield token. /// @param loss The amount of loss measured in basis points. /// @param maximumLoss The maximum amount of loss permitted measured in basis points. error LossExceeded(address yieldToken, uint256 loss, uint256 maximumLoss); /// @notice An error which is used to indicate that a minting operation failed because the minting limit has been exceeded. /// /// @param amount The amount of debt tokens that were requested to be minted. /// @param available The amount of debt tokens which are available to mint. error MintingLimitExceeded(uint256 amount, uint256 available); /// @notice An error which is used to indicate that an repay operation failed because the repay limit for an underlying token has been exceeded. /// /// @param underlyingToken The address of the underlying token. /// @param amount The amount of underlying tokens that were requested to be repaid. /// @param available The amount of underlying tokens that are available to be repaid. error RepayLimitExceeded(address underlyingToken, uint256 amount, uint256 available); /// @notice An error which is used to indicate that an repay operation failed because the liquidation limit for an underlying token has been exceeded. /// /// @param underlyingToken The address of the underlying token. /// @param amount The amount of underlying tokens that were requested to be liquidated. /// @param available The amount of underlying tokens that are available to be liquidated. error LiquidationLimitExceeded(address underlyingToken, uint256 amount, uint256 available); /// @notice An error which is used to indicate that the slippage of a wrap or unwrap operation was exceeded. /// /// @param amount The amount of underlying or yield tokens returned by the operation. /// @param minimumAmountOut The minimum amount of the underlying or yield token that was expected when performing /// the operation. error SlippageExceeded(uint256 amount, uint256 minimumAmountOut); } pragma solidity >=0.5.0; /// @title IAlchemistV2Immutables /// @author Alchemix Finance interface IAlchemistV2Immutables { /// @notice Returns the version of the alchemist. /// /// @return The version. function version() external view returns (string memory); /// @notice Returns the address of the debt token used by the system. /// /// @return The address of the debt token. function debtToken() external view returns (address); } pragma solidity >=0.5.0; /// @title IAlchemistV2Events /// @author Alchemix Finance interface IAlchemistV2Events { /// @notice Emitted when the pending admin is updated. /// /// @param pendingAdmin The address of the pending admin. event PendingAdminUpdated(address pendingAdmin); /// @notice Emitted when the administrator is updated. /// /// @param admin The address of the administrator. event AdminUpdated(address admin); /// @notice Emitted when an address is set or unset as a sentinel. /// /// @param sentinel The address of the sentinel. /// @param flag A flag indicating if `sentinel` was set or unset as a sentinel. event SentinelSet(address sentinel, bool flag); /// @notice Emitted when an address is set or unset as a keeper. /// /// @param sentinel The address of the keeper. /// @param flag A flag indicating if `keeper` was set or unset as a sentinel. event KeeperSet(address sentinel, bool flag); /// @notice Emitted when an underlying token is added. /// /// @param underlyingToken The address of the underlying token that was added. event AddUnderlyingToken(address indexed underlyingToken); /// @notice Emitted when a yield token is added. /// /// @param yieldToken The address of the yield token that was added. event AddYieldToken(address indexed yieldToken); /// @notice Emitted when an underlying token is enabled or disabled. /// /// @param underlyingToken The address of the underlying token that was enabled or disabled. /// @param enabled A flag indicating if the underlying token was enabled or disabled. event UnderlyingTokenEnabled(address indexed underlyingToken, bool enabled); /// @notice Emitted when an yield token is enabled or disabled. /// /// @param yieldToken The address of the yield token that was enabled or disabled. /// @param enabled A flag indicating if the yield token was enabled or disabled. event YieldTokenEnabled(address indexed yieldToken, bool enabled); /// @notice Emitted when the repay limit of an underlying token is updated. /// /// @param underlyingToken The address of the underlying token. /// @param maximum The updated maximum repay limit. /// @param blocks The updated number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted. event RepayLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks); /// @notice Emitted when the liquidation limit of an underlying token is updated. /// /// @param underlyingToken The address of the underlying token. /// @param maximum The updated maximum liquidation limit. /// @param blocks The updated number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted. event LiquidationLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks); /// @notice Emitted when the transmuter is updated. /// /// @param transmuter The updated address of the transmuter. event TransmuterUpdated(address transmuter); /// @notice Emitted when the minimum collateralization is updated. /// /// @param minimumCollateralization The updated minimum collateralization. event MinimumCollateralizationUpdated(uint256 minimumCollateralization); /// @notice Emitted when the protocol fee is updated. /// /// @param protocolFee The updated protocol fee. event ProtocolFeeUpdated(uint256 protocolFee); /// @notice Emitted when the protocol fee receiver is updated. /// /// @param protocolFeeReceiver The updated address of the protocol fee receiver. event ProtocolFeeReceiverUpdated(address protocolFeeReceiver); /// @notice Emitted when the minting limit is updated. /// /// @param maximum The updated maximum minting limit. /// @param blocks The updated number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted. event MintingLimitUpdated(uint256 maximum, uint256 blocks); /// @notice Emitted when the credit unlock rate is updated. /// /// @param yieldToken The address of the yield token. /// @param blocks The number of blocks that distributed credit will unlock over. event CreditUnlockRateUpdated(address yieldToken, uint256 blocks); /// @notice Emitted when the adapter of a yield token is updated. /// /// @param yieldToken The address of the yield token. /// @param tokenAdapter The updated address of the token adapter. event TokenAdapterUpdated(address yieldToken, address tokenAdapter); /// @notice Emitted when the maximum expected value of a yield token is updated. /// /// @param yieldToken The address of the yield token. /// @param maximumExpectedValue The updated maximum expected value. event MaximumExpectedValueUpdated(address indexed yieldToken, uint256 maximumExpectedValue); /// @notice Emitted when the maximum loss of a yield token is updated. /// /// @param yieldToken The address of the yield token. /// @param maximumLoss The updated maximum loss. event MaximumLossUpdated(address indexed yieldToken, uint256 maximumLoss); /// @notice Emitted when the expected value of a yield token is snapped to its current value. /// /// @param yieldToken The address of the yield token. /// @param expectedValue The updated expected value measured in the yield token's underlying token. event Snap(address indexed yieldToken, uint256 expectedValue); /// @notice Emitted when `owner` grants `spender` the ability to mint debt tokens on its behalf. /// /// @param owner The address of the account owner. /// @param spender The address which is being permitted to mint tokens on the behalf of `owner`. /// @param amount The amount of debt tokens that `spender` is allowed to mint. event ApproveMint(address indexed owner, address indexed spender, uint256 amount); /// @notice Emitted when `owner` grants `spender` the ability to withdraw `yieldToken` from its account. /// /// @param owner The address of the account owner. /// @param spender The address which is being permitted to mint tokens on the behalf of `owner`. /// @param yieldToken The address of the yield token that `spender` is allowed to withdraw. /// @param amount The amount of shares of `yieldToken` that `spender` is allowed to withdraw. event ApproveWithdraw(address indexed owner, address indexed spender, address indexed yieldToken, uint256 amount); /// @notice Emitted when a user deposits `amount of `yieldToken` to `recipient`. /// /// @notice This event does not imply that `sender` directly deposited yield tokens. It is possible that the /// underlying tokens were wrapped. /// /// @param sender The address of the user which deposited funds. /// @param yieldToken The address of the yield token that was deposited. /// @param amount The amount of yield tokens that were deposited. /// @param recipient The address that received the deposited funds. event Deposit(address indexed sender, address indexed yieldToken, uint256 amount, address recipient); /// @notice Emitted when `shares` shares of `yieldToken` are burned to withdraw `yieldToken` from the account owned /// by `owner` to `recipient`. /// /// @notice This event does not imply that `recipient` received yield tokens. It is possible that the yield tokens /// were unwrapped. /// /// @param owner The address of the account owner. /// @param yieldToken The address of the yield token that was withdrawn. /// @param shares The amount of shares that were burned. /// @param recipient The address that received the withdrawn funds. event Withdraw(address indexed owner, address indexed yieldToken, uint256 shares, address recipient); /// @notice Emitted when `amount` debt tokens are minted to `recipient` using the account owned by `owner`. /// /// @param owner The address of the account owner. /// @param amount The amount of tokens that were minted. /// @param recipient The recipient of the minted tokens. event Mint(address indexed owner, uint256 amount, address recipient); /// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to `recipient`. /// /// @param sender The address which is burning tokens. /// @param amount The amount of tokens that were burned. /// @param recipient The address that received credit for the burned tokens. event Burn(address indexed sender, uint256 amount, address recipient); /// @notice Emitted when `amount` of `underlyingToken` are repaid to grant credit to `recipient`. /// /// @param sender The address which is repaying tokens. /// @param underlyingToken The address of the underlying token that was used to repay debt. /// @param amount The amount of the underlying token that was used to repay debt. /// @param recipient The address that received credit for the repaid tokens. event Repay(address indexed sender, address indexed underlyingToken, uint256 amount, address recipient); /// @notice Emitted when `sender` liquidates `share` shares of `yieldToken`. /// /// @param owner The address of the account owner liquidating shares. /// @param yieldToken The address of the yield token. /// @param underlyingToken The address of the underlying token. /// @param shares The amount of the shares of `yieldToken` that were liquidated. event Liquidate(address indexed owner, address indexed yieldToken, address indexed underlyingToken, uint256 shares); /// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to users who have deposited `yieldToken`. /// /// @param sender The address which burned debt tokens. /// @param yieldToken The address of the yield token. /// @param amount The amount of debt tokens which were burned. event Donate(address indexed sender, address indexed yieldToken, uint256 amount); /// @notice Emitted when `yieldToken` is harvested. /// /// @param yieldToken The address of the yield token that was harvested. /// @param minimumAmountOut The maximum amount of loss that is acceptable when unwrapping the underlying tokens into yield tokens, measured in basis points. /// @param totalHarvested The total amount of underlying tokens harvested. event Harvest(address indexed yieldToken, uint256 minimumAmountOut, uint256 totalHarvested); } pragma solidity >=0.5.0; /// @title IAlchemistV2State /// @author Alchemix Finance interface IAlchemistV2State { /// @notice Defines underlying token parameters. struct UnderlyingTokenParams { // The number of decimals the token has. This value is cached once upon registering the token so it is important // that the decimals of the token are immutable or the system will begin to have computation errors. uint8 decimals; // A coefficient used to normalize the token to a value comparable to the debt token. For example, if the // underlying token is 8 decimals and the debt token is 18 decimals then the conversion factor will be // 10^10. One unit of the underlying token will be comparably equal to one unit of the debt token. uint256 conversionFactor; // A flag to indicate if the token is enabled. bool enabled; } /// @notice Defines yield token parameters. struct YieldTokenParams { // The number of decimals the token has. This value is cached once upon registering the token so it is important // that the decimals of the token are immutable or the system will begin to have computation errors. uint8 decimals; // The associated underlying token that can be redeemed for the yield-token. address underlyingToken; // The adapter used by the system to wrap, unwrap, and lookup the conversion rate of this token into its // underlying token. address adapter; // The maximum percentage loss that is acceptable before disabling certain actions. uint256 maximumLoss; // The maximum value of yield tokens that the system can hold, measured in units of the underlying token. uint256 maximumExpectedValue; // The percent of credit that will be unlocked per block. The representation of this value is a 18 decimal // fixed point integer. uint256 creditUnlockRate; // The current balance of yield tokens which are held by users. uint256 activeBalance; // The current balance of yield tokens which are earmarked to be harvested by the system at a later time. uint256 harvestableBalance; // The total number of shares that have been minted for this token. uint256 totalShares; // The expected value of the tokens measured in underlying tokens. This value controls how much of the token // can be harvested. When users deposit yield tokens, it increases the expected value by how much the tokens // are exchangeable for in the underlying token. When users withdraw yield tokens, it decreases the expected // value by how much the tokens are exchangeable for in the underlying token. uint256 expectedValue; // The current amount of credit which is will be distributed over time to depositors. uint256 pendingCredit; // The amount of the pending credit that has been distributed. uint256 distributedCredit; // The block number which the last credit distribution occurred. uint256 lastDistributionBlock; // The total accrued weight. This is used to calculate how much credit a user has been granted over time. The // representation of this value is a 18 decimal fixed point integer. uint256 accruedWeight; // A flag to indicate if the token is enabled. bool enabled; } /// @notice Gets the address of the admin. /// /// @return admin The admin address. function admin() external view returns (address admin); /// @notice Gets the address of the pending administrator. /// /// @return pendingAdmin The pending administrator address. function pendingAdmin() external view returns (address pendingAdmin); /// @notice Gets if an address is a sentinel. /// /// @param sentinel The address to check. /// /// @return isSentinel If the address is a sentinel. function sentinels(address sentinel) external view returns (bool isSentinel); /// @notice Gets if an address is a keeper. /// /// @param keeper The address to check. /// /// @return isKeeper If the address is a keeper function keepers(address keeper) external view returns (bool isKeeper); /// @notice Gets the address of the transmuter. /// /// @return transmuter The transmuter address. function transmuter() external view returns (address transmuter); /// @notice Gets the minimum collateralization. /// /// @notice Collateralization is determined by taking the total value of collateral that a user has deposited into their account and dividing it their debt. /// /// @dev The value returned is a 18 decimal fixed point integer. /// /// @return minimumCollateralization The minimum collateralization. function minimumCollateralization() external view returns (uint256 minimumCollateralization); /// @notice Gets the protocol fee. /// /// @return protocolFee The protocol fee. function protocolFee() external view returns (uint256 protocolFee); /// @notice Gets the protocol fee receiver. /// /// @return protocolFeeReceiver The protocol fee receiver. function protocolFeeReceiver() external view returns (address protocolFeeReceiver); /// @notice Gets the address of the whitelist contract. /// /// @return whitelist The address of the whitelist contract. function whitelist() external view returns (address whitelist); /// @notice Gets the conversion rate of underlying tokens per share. /// /// @param yieldToken The address of the yield token to get the conversion rate for. /// /// @return rate The rate of underlying tokens per share. function getUnderlyingTokensPerShare(address yieldToken) external view returns (uint256 rate); /// @notice Gets the conversion rate of yield tokens per share. /// /// @param yieldToken The address of the yield token to get the conversion rate for. /// /// @return rate The rate of yield tokens per share. function getYieldTokensPerShare(address yieldToken) external view returns (uint256 rate); /// @notice Gets the supported underlying tokens. /// /// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls. /// /// @return tokens The supported underlying tokens. function getSupportedUnderlyingTokens() external view returns (address[] memory tokens); /// @notice Gets the supported yield tokens. /// /// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls. /// /// @return tokens The supported yield tokens. function getSupportedYieldTokens() external view returns (address[] memory tokens); /// @notice Gets if an underlying token is supported. /// /// @param underlyingToken The address of the underlying token to check. /// /// @return isSupported If the underlying token is supported. function isSupportedUnderlyingToken(address underlyingToken) external view returns (bool isSupported); /// @notice Gets if a yield token is supported. /// /// @param yieldToken The address of the yield token to check. /// /// @return isSupported If the yield token is supported. function isSupportedYieldToken(address yieldToken) external view returns (bool isSupported); /// @notice Gets information about the account owned by `owner`. /// /// @param owner The address that owns the account. /// /// @return debt The unrealized amount of debt that the account had incurred. /// @return depositedTokens The yield tokens that the owner has deposited. function accounts(address owner) external view returns (int256 debt, address[] memory depositedTokens); /// @notice Gets information about a yield token position for the account owned by `owner`. /// /// @param owner The address that owns the account. /// @param yieldToken The address of the yield token to get the position of. /// /// @return shares The amount of shares of that `owner` owns of the yield token. /// @return lastAccruedWeight The last recorded accrued weight of the yield token. function positions(address owner, address yieldToken) external view returns ( uint256 shares, uint256 lastAccruedWeight ); /// @notice Gets the amount of debt tokens `spender` is allowed to mint on behalf of `owner`. /// /// @param owner The owner of the account. /// @param spender The address which is allowed to mint on behalf of `owner`. /// /// @return allowance The amount of debt tokens that `spender` can mint on behalf of `owner`. function mintAllowance(address owner, address spender) external view returns (uint256 allowance); /// @notice Gets the amount of shares of `yieldToken` that `spender` is allowed to withdraw on behalf of `owner`. /// /// @param owner The owner of the account. /// @param spender The address which is allowed to withdraw on behalf of `owner`. /// @param yieldToken The address of the yield token. /// /// @return allowance The amount of shares that `spender` can withdraw on behalf of `owner`. function withdrawAllowance(address owner, address spender, address yieldToken) external view returns (uint256 allowance); /// @notice Gets the parameters of an underlying token. /// /// @param underlyingToken The address of the underlying token. /// /// @return params The underlying token parameters. function getUnderlyingTokenParameters(address underlyingToken) external view returns (UnderlyingTokenParams memory params); /// @notice Get the parameters and state of a yield-token. /// /// @param yieldToken The address of the yield token. /// /// @return params The yield token parameters. function getYieldTokenParameters(address yieldToken) external view returns (YieldTokenParams memory params); /// @notice Gets current limit, maximum, and rate of the minting limiter. /// /// @return currentLimit The current amount of debt tokens that can be minted. /// @return rate The maximum possible amount of tokens that can be liquidated at a time. /// @return maximum The highest possible maximum amount of debt tokens that can be minted at a time. function getMintLimitInfo() external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); /// @notice Gets current limit, maximum, and rate of a repay limiter for `underlyingToken`. /// /// @param underlyingToken The address of the underlying token. /// /// @return currentLimit The current amount of underlying tokens that can be repaid. /// @return rate The rate at which the the current limit increases back to its maximum in tokens per block. /// @return maximum The maximum possible amount of tokens that can be repaid at a time. function getRepayLimitInfo(address underlyingToken) external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); /// @notice Gets current limit, maximum, and rate of the liquidation limiter for `underlyingToken`. /// /// @param underlyingToken The address of the underlying token. /// /// @return currentLimit The current amount of underlying tokens that can be liquidated. /// @return rate The rate at which the function increases back to its maximum limit (tokens / block). /// @return maximum The highest possible maximum amount of debt tokens that can be liquidated at a time. function getLiquidationLimitInfo(address underlyingToken) external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); } pragma solidity >=0.5.0; import "./IERC20Minimal.sol"; /// @title IERC20Burnable /// @author Alchemix Finance interface IERC20Burnable is IERC20Minimal { /// @notice Burns `amount` tokens from the balance of `msg.sender`. /// /// @param amount The amount of tokens to burn. /// /// @return If burning the tokens was successful. function burn(uint256 amount) external returns (bool); /// @notice Burns `amount` tokens from `owner`'s balance. /// /// @param owner The address to burn tokens from. /// @param amount The amount of tokens to burn. /// /// @return If burning the tokens was successful. function burnFrom(address owner, uint256 amount) external returns (bool); } pragma solidity >=0.5.0; /// @title IERC20Metadata /// @author Alchemix Finance interface IERC20Metadata { /// @notice Gets the name of the token. /// /// @return The name. function name() external view returns (string memory); /// @notice Gets the symbol of the token. /// /// @return The symbol. function symbol() external view returns (string memory); /// @notice Gets the number of decimals that the token has. /// /// @return The number of decimals. function decimals() external view returns (uint8); } pragma solidity >=0.5.0; /// @title IERC20Minimal /// @author Alchemix Finance interface IERC20Minimal { /// @notice An event which is emitted when tokens are transferred between two parties. /// /// @param owner The owner of the tokens from which the tokens were transferred. /// @param recipient The recipient of the tokens to which the tokens were transferred. /// @param amount The amount of tokens which were transferred. event Transfer(address indexed owner, address indexed recipient, uint256 amount); /// @notice An event which is emitted when an approval is made. /// /// @param owner The address which made the approval. /// @param spender The address which is allowed to transfer tokens on behalf of `owner`. /// @param amount The amount of tokens that `spender` is allowed to transfer. event Approval(address indexed owner, address indexed spender, uint256 amount); /// @notice Gets the current total supply of tokens. /// /// @return The total supply. function totalSupply() external view returns (uint256); /// @notice Gets the balance of tokens that an account holds. /// /// @param account The account address. /// /// @return The balance of the account. function balanceOf(address account) external view returns (uint256); /// @notice Gets the allowance that an owner has allotted for a spender. /// /// @param owner The owner address. /// @param spender The spender address. /// /// @return The number of tokens that `spender` is allowed to transfer on behalf of `owner`. function allowance(address owner, address spender) external view returns (uint256); /// @notice Transfers `amount` tokens from `msg.sender` to `recipient`. /// /// @notice Emits a {Transfer} event. /// /// @param recipient The address which will receive the tokens. /// @param amount The amount of tokens to transfer. /// /// @return If the transfer was successful. function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Approves `spender` to transfer `amount` tokens on behalf of `msg.sender`. /// /// @notice Emits a {Approval} event. /// /// @param spender The address which is allowed to transfer tokens on behalf of `msg.sender`. /// @param amount The amount of tokens that `spender` is allowed to transfer. /// /// @return If the approval was successful. function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `owner` to `recipient` using an approval that `owner` gave to `msg.sender`. /// /// @notice Emits a {Approval} event. /// @notice Emits a {Transfer} event. /// /// @param owner The address to transfer tokens from. /// @param recipient The address that will receive the tokens. /// @param amount The amount of tokens to transfer. /// /// @return If the transfer was successful. function transferFrom(address owner, address recipient, uint256 amount) external returns (bool); } pragma solidity >=0.5.0; import "./IERC20Minimal.sol"; /// @title IERC20Mintable /// @author Alchemix Finance interface IERC20Mintable is IERC20Minimal { /// @notice Mints `amount` tokens to `recipient`. /// /// @param recipient The address which will receive the minted tokens. /// @param amount The amount of tokens to mint. /// /// @return If minting the tokens was successful. function mint(address recipient, uint256 amount) external returns (bool); }
Burns tokens from its total supply. Reverts with a {CallFailed} error if execution of the burn fails or returns an unexpected value. token The token to burn. owner The owner of the tokens. amount The amount of tokens to burn.
function safeBurnFrom(address token, address owner, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Burnable.burnFrom.selector, owner, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } }
157,697
./full_match/3/0xA81Ef0cEacfA5263c989C306886207D6dCc0a038/sources/browser/PoolPortal.sol
helper for sell pool in Bancor network _poolToken address of bancor relay _amount amount of bancor relay/ transfer pool from fund get Bancor Converter address liquidate relay get connectors transfer connectors back to fund tarnsfer ETH transfer ERC20
function sellPoolViaBancor(IERC20 _poolToken, uint256 _amount) private returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount, uint256 poolAmountSent ) { _poolToken.transferFrom(msg.sender, address(this), _amount); address converterAddress = getBacorConverterAddressByRelay(address(_poolToken)); BancorConverterInterface(converterAddress).liquidate(_amount); poolAmountSent = _amount; (connectorsAddress) = getBancorConnectorsByRelay(address(_poolToken)); connectorsAmount = new uint256[](connectorsAddress.length); uint256 received = 0; for(uint8 i = 0; i < connectorsAddress.length; i++){ if(connectorsAddress[i] == address(ETH_TOKEN_ADDRESS)){ received = address(this).balance; (msg.sender).transfer(received); connectorsAmount[i] = received; received = IERC20(connectorsAddress[i]).balanceOf(address(this)); IERC20(connectorsAddress[i]).transfer(msg.sender, received); connectorsAmount[i] = received; } } }
8,151,637
// Written by Jesse Busman ([email protected]) in january 2018 and june 2018 and december 2018 and january 2019 and february 2019 // This is the back end of https://etherprime.jesbus.com/ pragma solidity 0.5.4; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- interface ERC20 { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); } 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 pure returns (bool); } /// @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 /*is ERC165*/ { /// @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 returns (bool); /// @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 returns (bool); /// @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 returns (bool); /// @notice Set or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// @dev 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 returns (bool); /// @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 returns (bool); /// @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); } interface ERC721Enumerable { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) external 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 */ interface ERC721Metadata { function name() external pure returns (string memory _name); function symbol() external pure returns (string memory _symbol); function tokenURI(uint256 _tokenId) external view returns (string memory _uri); } 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. Return /// of other than the magic value MUST result in the transaction being reverted. /// @notice 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)"))` /// unless throwing function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4); } interface ERC223 { function balanceOf(address who) external view returns (uint256); function name() external pure returns (string memory _name); function symbol() external pure returns (string memory _symbol); function decimals() external pure returns (uint8 _decimals); function totalSupply() external view returns (uint256 _supply); function transfer(address to, uint value) external returns (bool ok); function transfer(address to, uint value, bytes calldata data) external returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } interface ERC223Receiver { function tokenFallback(address _from, uint256 _value, bytes calldata _data) external; } interface ERC777TokensRecipient { function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; } interface ERC777TokensSender { function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; } contract EtherPrime is ERC20, ERC721, ERC721Enumerable, ERC721Metadata, ERC165, ERC223 { //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// State variables //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Array of definite prime numbers uint256[] public definitePrimes; // Array of probable primes uint256[] public probablePrimes; // Allowances mapping(uint256 => address) public primeToAllowedAddress; // Allowed operators mapping(address => mapping(address => bool)) private ownerToOperators; // Ownership of primes mapping(address => uint256[]) private ownerToPrimes; // Number data contains: // - Index of prime in ownerToPrimes array // - Index of prime in definitePrimes or probablePrimes array // - NumberType // - Owner of prime mapping(uint256 => bytes32) private numberToNumberdata; // Store known non-2 divisors of non-primes mapping(uint256 => uint256) private numberToNonTwoDivisor; // List of all participants address[] public participants; mapping(address => uint256) private addressToParticipantsArrayIndex; // Statistics mapping(address => uint256) public addressToGasSpent; mapping(address => uint256) public addressToEtherSpent; mapping(address => uint256) public addressToProbablePrimesClaimed; mapping(address => uint256) public addressToProbablePrimesDisprovenBy; mapping(address => uint256) public addressToProbablePrimesDisprovenFrom; // Prime calculator state uint256 public numberBeingTested; uint256 public divisorIndexBeingTested; // Prime trading mapping(address => uint256) public addressToEtherBalance; mapping(uint256 => uint256) public primeToSellOrderPrice; mapping(uint256 => BuyOrder[]) private primeToBuyOrders; //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Events //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Prime generation event DefinitePrimeDiscovered(uint256 indexed prime, address indexed discoverer, uint256 indexed definitePrimesArrayIndex); event ProbablePrimeDiscovered(uint256 indexed prime, address indexed discoverer, uint256 indexed probablePrimesArrayIndex); event ProbablePrimeDisproven(uint256 indexed prime, uint256 divisor, address indexed owner, address indexed disprover, uint256 probablePrimesArrayIndex); // Token event Transfer(address indexed from, address indexed to, uint256 prime); event Approval(address indexed owner, address indexed spender, uint256 prime); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); // Trading event BuyOrderCreated(address indexed buyer, uint256 indexed prime, uint256 indexed buyOrdersArrayIndex, uint256 bid); event BuyOrderDestroyed(address indexed buyer, uint256 indexed prime, uint256 indexed buyOrdersArrayIndex); event SellPriceSet(address indexed seller, uint256 indexed prime, uint256 price); event PrimeTraded(address indexed seller, address indexed buyer, uint256 indexed prime, uint256 buyOrdersArrayIndex, uint256 price); event EtherDeposited(address indexed depositer, uint256 amount); event EtherWithdrawn(address indexed withdrawer, uint256 amount); //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Internal functions that write to //////////// //////////// state variables //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// function _addParticipant(address _newParticipant) private { // Add the participant to the list, but only if they are not 0x0 and they are not already in the list. if (_newParticipant != address(0x0) && addressToParticipantsArrayIndex[_newParticipant] == 0) { addressToParticipantsArrayIndex[_newParticipant] = participants.length; participants.push(_newParticipant); } } //////////////////////////////////// //////// Internal functions to change ownership of a prime function _removePrimeFromOwnerPrimesArray(uint256 _prime) private { bytes32 numberdata = numberToNumberdata[_prime]; uint256[] storage ownerPrimes = ownerToPrimes[numberdataToOwner(numberdata)]; uint256 primeIndex = numberdataToOwnerPrimesIndex(numberdata); // Move the last one backwards into the freed slot uint256 otherPrimeBeingMoved = ownerPrimes[ownerPrimes.length-1]; ownerPrimes[primeIndex] = otherPrimeBeingMoved; _numberdataSetOwnerPrimesIndex(otherPrimeBeingMoved, uint40(primeIndex)); // Refund gas by setting the now unused array slot to 0 // Advantage: Current transaction gets a gas refund of 15000 // Disadvantage: Next transaction that gives a prime to this owner will cost 15000 more gas ownerPrimes[ownerPrimes.length-1] = 0; // Refund some gas // Decrease the length of the array ownerPrimes.length--; } function _setOwner(uint256 _prime, address _newOwner) private { _setOwner(_prime, _newOwner, "", address(0x0), ""); } function _setOwner(uint256 _prime, address _newOwner, bytes memory _data, address _operator, bytes memory _operatorData) private { // getOwner does not throw, so previousOwner can be 0x0 address previousOwner = getOwner(_prime); if (_operator == address(0x0)) { _operator = previousOwner; } // Shortcut in case we don't need to do anything if (previousOwner == _newOwner) { return; } // Delete _prime from ownerToPrimes[previousOwner] if (previousOwner != address(0x0)) { _removePrimeFromOwnerPrimesArray(_prime); } // Store the new ownerPrimes array index and the new owner in the numberdata _numberdataSetOwnerAndOwnerPrimesIndex(_prime, _newOwner, uint40(ownerToPrimes[_newOwner].length)); // Add _prime to ownerToPrimes[_newOwner] ownerToPrimes[_newOwner].push(_prime); // Delete any existing allowance if (primeToAllowedAddress[_prime] != address(0x0)) { primeToAllowedAddress[_prime] = address(0x0); } // Delete any existing sell order if (primeToSellOrderPrice[_prime] != 0) { primeToSellOrderPrice[_prime] = 0; emit SellPriceSet(_newOwner, _prime, 0); } // Add the new owner to the list of EtherPrime participants _addParticipant(_newOwner); // If the new owner is a contract, try to notify them of the received token. if (isContract(_newOwner)) { bool success; bytes32 returnValue; // Try to call onERC721Received (as per ERC721) (success, returnValue) = _tryCall(_newOwner, abi.encodeWithSelector(ERC721TokenReceiver(_newOwner).onERC721Received.selector, _operator, previousOwner, _prime, _data)); if (!success || returnValue != bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))) { // If ERC721::onERC721Received failed, try to call tokenFallback (as per ERC223) (success, returnValue) = _tryCall(_newOwner, abi.encodeWithSelector(ERC223Receiver(_newOwner).tokenFallback.selector, previousOwner, _prime, 0x0)); if (!success) { // If ERC223::tokenFallback failed, try to call tokensReceived (as per ERC777) (success, returnValue) = _tryCall(_newOwner, abi.encodeWithSelector(ERC777TokensRecipient(_newOwner).tokensReceived.selector, _operator, previousOwner, _newOwner, _prime, _data, _operatorData)); if (!success) { // If all token fallback calls failed, give up and just give them their token. return; } } } } emit Transfer(previousOwner, _newOwner, _prime); } function _createPrime(uint256 _prime, address _owner, bool _isDefinitePrime) private { // Create the prime _numberdataSetAllPrimesIndexAndNumberType( _prime, uint48(_isDefinitePrime ? definitePrimes.length : probablePrimes.length), _isDefinitePrime ? NumberType.DEFINITE_PRIME : NumberType.PROBABLE_PRIME ); if (_isDefinitePrime) { emit DefinitePrimeDiscovered(_prime, msg.sender, definitePrimes.length); definitePrimes.push(_prime); } else { emit ProbablePrimeDiscovered(_prime, msg.sender, probablePrimes.length); probablePrimes.push(_prime); } // Give it to its new owner _setOwner(_prime, _owner); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Bitwise stuff on numberdata //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// enum NumberType { NOT_PRIME_IF_PASSED, NOT_PRIME, PROBABLE_PRIME, DEFINITE_PRIME } // Number data format: // MSB LSB // [ 40 bits for owner primes array index ] [ 48 bits for all primes array index ] [ 8 bits for number type ] [ 160 bits for owner address ] // ^ ^ ^ ^ // ^ the index in ownerToPrimes array ^ index in definitePrimes or probablePrimes ^ a NumberType value ^ owner of the number uint256 private constant NUMBERDATA_OWNER_PRIME_INDEX_SIZE = 40; uint256 private constant NUMBERDATA_OWNER_PRIME_INDEX_SHIFT = NUMBERDATA_ALL_PRIME_INDEX_SHIFT + NUMBERDATA_ALL_PRIME_INDEX_SIZE; bytes32 private constant NUMBERDATA_OWNER_PRIME_INDEX_MASK = bytes32(uint256(~uint40(0)) << NUMBERDATA_OWNER_PRIME_INDEX_SHIFT); uint256 private constant NUMBERDATA_ALL_PRIME_INDEX_SIZE = 48; uint256 private constant NUMBERDATA_ALL_PRIME_INDEX_SHIFT = NUMBERDATA_NUMBER_TYPE_SHIFT + NUMBERDATA_NUMBER_TYPE_SIZE; bytes32 private constant NUMBERDATA_ALL_PRIME_INDEX_MASK = bytes32(uint256(~uint48(0)) << NUMBERDATA_ALL_PRIME_INDEX_SHIFT); uint256 private constant NUMBERDATA_NUMBER_TYPE_SIZE = 8; uint256 private constant NUMBERDATA_NUMBER_TYPE_SHIFT = NUMBERDATA_OWNER_ADDRESS_SHIFT + NUMBERDATA_OWNER_ADDRESS_SIZE; bytes32 private constant NUMBERDATA_NUMBER_TYPE_MASK = bytes32(uint256(~uint8(0)) << NUMBERDATA_NUMBER_TYPE_SHIFT); uint256 private constant NUMBERDATA_OWNER_ADDRESS_SIZE = 160; uint256 private constant NUMBERDATA_OWNER_ADDRESS_SHIFT = 0; bytes32 private constant NUMBERDATA_OWNER_ADDRESS_MASK = bytes32(uint256(~uint160(0)) << NUMBERDATA_OWNER_ADDRESS_SHIFT); function numberdataToOwnerPrimesIndex(bytes32 _numberdata) private pure returns (uint40) { return uint40(uint256(_numberdata & NUMBERDATA_OWNER_PRIME_INDEX_MASK) >> NUMBERDATA_OWNER_PRIME_INDEX_SHIFT); } function numberdataToAllPrimesIndex(bytes32 _numberdata) private pure returns (uint48) { return uint48(uint256(_numberdata & NUMBERDATA_ALL_PRIME_INDEX_MASK) >> NUMBERDATA_ALL_PRIME_INDEX_SHIFT); } function numberdataToNumberType(bytes32 _numberdata) private pure returns (NumberType) { return NumberType(uint256(_numberdata & NUMBERDATA_NUMBER_TYPE_MASK) >> NUMBERDATA_NUMBER_TYPE_SHIFT); } function numberdataToOwner(bytes32 _numberdata) private pure returns (address) { return address(uint160(uint256(_numberdata & NUMBERDATA_OWNER_ADDRESS_MASK) >> NUMBERDATA_OWNER_ADDRESS_SHIFT)); } function ownerPrimesIndex_allPrimesIndex_numberType_owner__toNumberdata(uint40 _ownerPrimesIndex, uint48 _allPrimesIndex, NumberType _numberType, address _owner) private pure returns (bytes32) { return bytes32( (uint256(_ownerPrimesIndex) << NUMBERDATA_OWNER_PRIME_INDEX_SHIFT) | (uint256(_allPrimesIndex) << NUMBERDATA_ALL_PRIME_INDEX_SHIFT) | (uint256(uint8(_numberType)) << NUMBERDATA_NUMBER_TYPE_SHIFT) | (uint256(uint160(_owner)) << NUMBERDATA_OWNER_ADDRESS_SHIFT) ); } function _numberdataSetOwnerPrimesIndex(uint256 _number, uint40 _ownerPrimesIndex) private { bytes32 numberdata = numberToNumberdata[_number]; numberdata &= ~NUMBERDATA_OWNER_PRIME_INDEX_MASK; numberdata |= bytes32(uint256(_ownerPrimesIndex)) << NUMBERDATA_OWNER_PRIME_INDEX_SHIFT; numberToNumberdata[_number] = numberdata; } function _numberdataSetAllPrimesIndex(uint256 _number, uint48 _allPrimesIndex) private { bytes32 numberdata = numberToNumberdata[_number]; numberdata &= ~NUMBERDATA_ALL_PRIME_INDEX_MASK; numberdata |= bytes32(uint256(_allPrimesIndex)) << NUMBERDATA_ALL_PRIME_INDEX_SHIFT; numberToNumberdata[_number] = numberdata; } function _numberdataSetNumberType(uint256 _number, NumberType _numberType) private { bytes32 numberdata = numberToNumberdata[_number]; numberdata &= ~NUMBERDATA_NUMBER_TYPE_MASK; numberdata |= bytes32(uint256(uint8(_numberType))) << NUMBERDATA_NUMBER_TYPE_SHIFT; numberToNumberdata[_number] = numberdata; } /*function _numberdataSetOwner(uint256 _number, address _owner) private { bytes32 numberdata = numberToNumberdata[_number]; numberdata &= ~NUMBERDATA_OWNER_ADDRESS_MASK; numberdata |= bytes32(uint256(uint160(_owner))) << NUMBERDATA_OWNER_ADDRESS_SHIFT; numberToNumberdata[_number] = numberdata; }*/ function _numberdataSetOwnerAndOwnerPrimesIndex(uint256 _number, address _owner, uint40 _ownerPrimesIndex) private { bytes32 numberdata = numberToNumberdata[_number]; numberdata &= ~NUMBERDATA_OWNER_ADDRESS_MASK; numberdata |= bytes32(uint256(uint160(_owner))) << NUMBERDATA_OWNER_ADDRESS_SHIFT; numberdata &= ~NUMBERDATA_OWNER_PRIME_INDEX_MASK; numberdata |= bytes32(uint256(_ownerPrimesIndex)) << NUMBERDATA_OWNER_PRIME_INDEX_SHIFT; numberToNumberdata[_number] = bytes32(numberdata); } function _numberdataSetAllPrimesIndexAndNumberType(uint256 _number, uint48 _allPrimesIndex, NumberType _numberType) private { bytes32 numberdata = numberToNumberdata[_number]; numberdata &= ~NUMBERDATA_ALL_PRIME_INDEX_MASK; numberdata |= bytes32(uint256(_allPrimesIndex)) << NUMBERDATA_ALL_PRIME_INDEX_SHIFT; numberdata &= ~NUMBERDATA_NUMBER_TYPE_MASK; numberdata |= bytes32(uint256(uint8(_numberType))) << NUMBERDATA_NUMBER_TYPE_SHIFT; numberToNumberdata[_number] = bytes32(numberdata); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Utility functions for //////////// //////////// ERC721 implementation //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// function isValidNFT(uint256 _prime) private view returns (bool) { NumberType numberType = numberdataToNumberType(numberToNumberdata[_prime]); return numberType == NumberType.PROBABLE_PRIME || numberType == NumberType.DEFINITE_PRIME; } function isApprovedFor(address _operator, uint256 _prime) private view returns (bool) { address owner = getOwner(_prime); return (owner == _operator) || (primeToAllowedAddress[_prime] == _operator) || (ownerToOperators[owner][_operator] == true); } function isContract(address _addr) private view returns (bool) { uint256 addrCodesize; assembly { addrCodesize := extcodesize(_addr) } return addrCodesize != 0; } function _tryCall(address _contract, bytes memory _selectorAndArguments) private returns (bool _success, bytes32 _returnData) { bytes32[1] memory returnDataArray; uint256 dataLengthBytes = _selectorAndArguments.length; assembly { // call(gas, address, value, arg_ptr, arg_size, return_ptr, return_max_size) _success := call(gas(), _contract, 0, _selectorAndArguments, dataLengthBytes, returnDataArray, 32) } _returnData = returnDataArray[0]; } // Does not throw if prime does not exist or has no owner function getOwner(uint256 _prime) public view returns (address) { return numberdataToOwner(numberToNumberdata[_prime]); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Token implementation //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// function name() external pure returns (string memory) { return "Prime number"; } function symbol() external pure returns (string memory) { return "PRIME"; } function decimals() external pure returns (uint8) { return 0; } function tokenURI(uint256 _tokenId) external view returns (string memory _uri) { require(isValidNFT(_tokenId)); _uri = "https://etherprime.jesbus.com/#search:"; uint256 baseURIlen = bytes(_uri).length; // Count the amount of digits required to represent the prime number uint256 digits = 0; uint256 _currentNum = _tokenId; while (_currentNum != 0) { _currentNum /= 10; digits++; } uint256 divisor = 10 ** (digits-1); _currentNum = _tokenId; for (uint256 i=0; i<digits; i++) { uint8 digit = 0x30 + uint8(_currentNum / divisor); assembly { mstore8(add(add(_uri, 0x20), add(baseURIlen, i)), digit) } _currentNum %= divisor; divisor /= 10; } assembly { mstore(_uri, add(baseURIlen, digits)) } } function totalSupply() external view returns (uint256) { return definitePrimes.length + probablePrimes.length; } function balanceOf(address _owner) external view returns (uint256) { // According to ERC721 we should throw on queries about the 0x0 address require(_owner != address(0x0), "balanceOf error: owner may not be 0x0"); return ownerToPrimes[_owner].length; } function addressPrimeCount(address _owner) external view returns (uint256) { return ownerToPrimes[_owner].length; } function allowance(address _owner, address _spender) external view returns (uint256) { uint256 total = 0; uint256[] storage primes = ownerToPrimes[_owner]; uint256 primesLength = primes.length; for (uint256 i=0; i<primesLength; i++) { uint256 prime = primes[i]; if (primeToAllowedAddress[prime] == _spender) { total += prime; } } return total; } // Throws if prime has no owner or does not exist function ownerOf(uint256 _prime) external view returns (address) { address owner = getOwner(_prime); require(owner != address(0x0), "ownerOf error: owner is set to 0x0"); return owner; } function safeTransferFrom(address _from, address _to, uint256 _prime, bytes memory _data) public returns (bool) { require(getOwner(_prime) == _from, "safeTransferFrom error: from address does not own that prime"); require(isApprovedFor(msg.sender, _prime), "safeTransferFrom error: you do not have approval from the owner of that prime"); _setOwner(_prime, _to, _data, msg.sender, ""); return true; } function safeTransferFrom(address _from, address _to, uint256 _prime) external returns (bool) { return safeTransferFrom(_from, _to, _prime, ""); } function transferFrom(address _from, address _to, uint256 _prime) external returns (bool) { return safeTransferFrom(_from, _to, _prime, ""); } function approve(address _to, uint256 _prime) external returns (bool) { require(isApprovedFor(msg.sender, _prime), "approve error: you do not have approval from the owner of that prime"); primeToAllowedAddress[_prime] = _to; emit Approval(msg.sender, _to, _prime); return true; } function setApprovalForAll(address _operator, bool _allowed) external returns (bool) { ownerToOperators[msg.sender][_operator] = _allowed; emit ApprovalForAll(msg.sender, _operator, _allowed); return true; } function getApproved(uint256 _prime) external view returns (address) { require(isValidNFT(_prime), "getApproved error: prime does not exist"); return primeToAllowedAddress[_prime]; } function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return ownerToOperators[_owner][_operator]; } function takeOwnership(uint256 _prime) external returns (bool) { require(isApprovedFor(msg.sender, _prime), "takeOwnership error: you do not have approval from the owner of that prime"); _setOwner(_prime, msg.sender); return true; } function transfer(address _to, uint256 _prime) external returns (bool) { require(isApprovedFor(msg.sender, _prime), "transfer error: you do not have approval from the owner of that prime"); _setOwner(_prime, _to); return true; } function transfer(address _to, uint _prime, bytes calldata _data) external returns (bool ok) { require(isApprovedFor(msg.sender, _prime), "transfer error: you do not have approval from the owner of that prime"); _setOwner(_prime, _to, _data, msg.sender, ""); return true; } function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { uint256[] storage ownerPrimes = ownerToPrimes[_owner]; require(_index < ownerPrimes.length, "tokenOfOwnerByIndex: index out of bounds"); return ownerPrimes[_index]; } function tokenByIndex(uint256 _index) external view returns (uint256) { if (_index < definitePrimes.length) return definitePrimes[_index]; else if (_index < definitePrimes.length + probablePrimes.length) return probablePrimes[_index - definitePrimes.length]; else revert("tokenByIndex error: index out of bounds"); } function tokensOf(address _owner) external view returns (uint256[] memory) { return ownerToPrimes[_owner]; } function implementsERC721() external pure returns (bool) { return true; } function supportsInterface(bytes4 _interfaceID) external pure returns (bool) { if (_interfaceID == 0x01ffc9a7) return true; // ERC165 if (_interfaceID == 0x80ac58cd) return true; // ERC721 if (_interfaceID == 0x5b5e139f) return true; // ERC721Metadata if (_interfaceID == 0x780e9d63) return true; // ERC721Enumerable return false; } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// View functions //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // numberToDivisor returns 0 if no divisor was found function numberToDivisor(uint256 _number) public view returns (uint256) { if (_number == 0) return 0; else if ((_number & 1) == 0) return 2; else return numberToNonTwoDivisor[_number]; } function isPrime(uint256 _number) public view returns (Booly) { NumberType numberType = numberdataToNumberType(numberToNumberdata[_number]); if (numberType == NumberType.DEFINITE_PRIME) return DEFINITELY; else if (numberType == NumberType.PROBABLE_PRIME) return PROBABLY; else if (numberType == NumberType.NOT_PRIME_IF_PASSED) { if (_number < numberBeingTested) { return DEFINITELY_NOT; } else { return UNKNOWN; } } else if (numberType == NumberType.NOT_PRIME) return DEFINITELY_NOT; else revert(); } function getPrimeFactors(uint256 _number) external view returns (bool _success, uint256[] memory _primeFactors) { _primeFactors = new uint256[](0); if (_number == 0) { _success = false; return (_success, _primeFactors); } // Track length of primeFactors array uint256 amount = 0; uint256 currentNumber = _number; while (true) { // If we've divided to 1, we're done :) if (currentNumber == 1) { _success = true; return (_success, _primeFactors); } uint256 divisor = numberToDivisor(currentNumber); if (divisor == 0) { if (isPrime(currentNumber) == DEFINITELY) { // If we couldn't find a divisor and the current number is a definite prime, // then the current prime is itself the divisor. // It will be added to primeFactors, currentNumber will go to one, // and we will exit successfully on the next iteration. divisor = currentNumber; } else { // If we don't know a divisor and we don't know for sure that the // current number is a definite prime, exit with failure. _success = false; return (_success, _primeFactors); } } else { while (isPrime(divisor) != DEFINITELY) { divisor = numberToDivisor(divisor); if (divisor == 0) { _success = false; return (_success, _primeFactors); } } } currentNumber /= divisor; // This in effect does: primeFactors.push(primeFactor) { amount++; assembly { mstore(0x40, add(mload(0x40), 0x20)) // dirty: extend usable memory mstore(_primeFactors, amount) // dirty: set memory array size } _primeFactors[amount-1] = divisor; } } } /*function isKnownNotPrime(uint256 _number) external view returns (bool) { return numberdataToNumberType(numberToNumberdata[_number]) == NumberType.NOT_PRIME; } function isKnownDefinitePrime(uint256 _number) public view returns (bool) { return numberdataToNumberType(numberToNumberdata[_number]) == NumberType.DEFINITE_PRIME; } function isKnownProbablePrime(uint256 _number) public view returns (bool) { return numberdataToNumberType(numberToNumberdata[_number]) == NumberType.PROBABLE_PRIME; }*/ function amountOfParticipants() external view returns (uint256) { return participants.length; } function amountOfPrimesOwnedByOwner(address owner) external view returns (uint256) { return ownerToPrimes[owner].length; } function amountOfPrimesFound() external view returns (uint256) { return definitePrimes.length + probablePrimes.length; } function amountOfDefinitePrimesFound() external view returns (uint256) { return definitePrimes.length; } function amountOfProbablePrimesFound() external view returns (uint256) { return probablePrimes.length; } function largestDefinitePrimeFound() public view returns (uint256) { return definitePrimes[definitePrimes.length-1]; } function getInsecureRandomDefinitePrime() external view returns (uint256) { return definitePrimes[insecureRand()%definitePrimes.length]; } function getInsecureRandomProbablePrime() external view returns (uint256) { return probablePrimes[insecureRand()%probablePrimes.length]; } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Constructor //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// constructor() public { participants.push(address(0x0)); // Let's start with 2. _createPrime(2, msg.sender, true); // The next one up for prime checking will be 3. numberBeingTested = 3; divisorIndexBeingTested = 0; new EtherPrimeChat(this); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Definite prime generation //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Call these function to help calculate prime numbers. // The reward shall be your immortalized glory. uint256 private constant DEFAULT_PRIMES_TO_MEMORIZE = 0; uint256 private constant DEFAULT_LOW_LEVEL_GAS = 200000; function () external { computeWithParams(definitePrimes.length/2, DEFAULT_LOW_LEVEL_GAS, msg.sender); } function compute() external { computeWithParams(definitePrimes.length/2, DEFAULT_LOW_LEVEL_GAS, msg.sender); } function computeAndGiveTo(address _recipient) external { computeWithParams(definitePrimes.length/2, DEFAULT_LOW_LEVEL_GAS, _recipient); } function computeWithPrimesToMemorize(uint256 _primesToMemorize) external { computeWithParams(_primesToMemorize, DEFAULT_LOW_LEVEL_GAS, msg.sender); } function computeWithPrimesToMemorizeAndLowLevelGas(uint256 _primesToMemorize, uint256 _lowLevelGas) external { computeWithParams(_primesToMemorize, _lowLevelGas, msg.sender); } function computeWithParams(uint256 _primesToMemorize, uint256 _lowLevelGas, address _recipient) public { require(_primesToMemorize <= definitePrimes.length, "computeWithParams error: _primesToMemorize out of bounds"); uint256 startGas = gasleft(); // We need to continue where we stopped last time. uint256 number = numberBeingTested; uint256 divisorIndex = divisorIndexBeingTested; // Read this in advance so we don't have to keep SLOAD'ing it uint256 totalPrimes = definitePrimes.length; // Load some discovered definite primes into memory uint256[] memory definitePrimesCache = new uint256[](_primesToMemorize); for (uint256 i=0; i<_primesToMemorize; i++) { definitePrimesCache[i] = definitePrimes[i]; } for (; ; number += 2) { // Save state and stop if remaining gas is too low if (gasleft() < _lowLevelGas) { numberBeingTested = number; divisorIndexBeingTested = divisorIndex; uint256 gasSpent = startGas - gasleft(); addressToGasSpent[msg.sender] += gasSpent; addressToEtherSpent[msg.sender] += gasSpent * tx.gasprice; return; } if (isPrime(number) != DEFINITELY_NOT) { uint256 sqrtNumberRoundedDown = sqrtRoundedDown(number); bool numberCanStillBePrime = true; uint256 divisor; for (; divisorIndex<totalPrimes; divisorIndex++) { // Save state and stop if remaining gas is too low if (gasleft() < _lowLevelGas) { numberBeingTested = number; divisorIndexBeingTested = divisorIndex; uint256 gasSpent = startGas - gasleft(); addressToGasSpent[msg.sender] += gasSpent; addressToEtherSpent[msg.sender] += gasSpent * tx.gasprice; return; } if (divisorIndex < definitePrimesCache.length) divisor = definitePrimesCache[divisorIndex]; else divisor = definitePrimes[divisorIndex]; if (number % divisor == 0) { numberCanStillBePrime = false; break; } // We don't have to try to divide by numbers higher than the // square root of the number. Why? Well, suppose you're testing // if 29 is prime. You've already tried dividing by 2, 3, 4, 5 // and found that you couldn't, so now you move on to 6. // Trying to divide it by 6 is futile, because if 29 were // divisible by 6, it would logically also be divisible by 29/6 // which you should already have found at that point, because // 29/6 < 6, because 6 > sqrt(29) if (divisor > sqrtNumberRoundedDown) { break; } } if (numberCanStillBePrime) { _createPrime(number, _recipient, true); totalPrimes++; } else { numberToNonTwoDivisor[number] = divisor; } // Start trying to divide by 3. // We skip all the even numbers so we don't have to bother dividing by 2. divisorIndex = 1; } } // This point should be unreachable. revert("computeWithParams error: This point should never be reached."); } // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method function sqrtRoundedDown(uint256 x) private pure returns (uint256 y) { if (x == ~uint256(0)) return 340282366920938463463374607431768211455; uint256 z = (x + 1) >> 1; y = x; while (z < y) { y = z; z = ((x / z) + z) >> 1; } return y; } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Prime classes //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Balanced primes are exactly in the middle between the two surrounding primes function isBalancedPrime(uint256 _prime) external view returns (Booly result, uint256 lowerPrime, uint256 higherPrime) { Booly primality = isPrime(_prime); if (primality == DEFINITELY_NOT) { return (DEFINITELY_NOT, 0, 0); } else if (primality == PROBABLY_NOT) { return (PROBABLY_NOT, 0, 0); } else if (primality == UNKNOWN) { return (UNKNOWN, 0, 0); } else if (primality == PROBABLY) { return (UNKNOWN, 0, 0); } else if (primality == DEFINITELY) { uint256 index = numberdataToAllPrimesIndex(numberToNumberdata[_prime]); if (index == 0) { // 2 is not a balanced prime, because there is no prime before it return (DEFINITELY_NOT, 0, 0); } else if (index == definitePrimes.length-1) { // We cannot determine this property for the last prime we've found return (UNKNOWN, 0, 0); } else { uint256 primeBefore = definitePrimes[index-1]; uint256 primeAfter = definitePrimes[index+1]; if (_prime - primeBefore == primeAfter - _prime) return (DEFINITELY, primeBefore, primeAfter); else return (DEFINITELY_NOT, primeBefore, primeAfter); } } else { revert(); } } // NTuple mersenne primes: // n=0 => primes returns [] // n=1 => mersenne primes of form 2^p-1 returns [p] // n=2 => double mersenne primes of form 2^(2^p-1)-1 returns [2^p-1, p] // n=3 => triple mersenne primes of form 2^(2^(2^p-1)-1)-1 returns [2^(2^p-1)-1, 2^p-1, p] // etc.. function isNTupleMersennePrime(uint256 _number, uint256 _n) external view returns (Booly _result, uint256[] memory _powers) { _powers = new uint256[](_n); // Prevent overflow on _number+1 if (_number+1 < _number) return (UNKNOWN, _powers); _result = isPrime(_number); if (_result == DEFINITELY_NOT) { return (DEFINITELY_NOT, _powers); } uint256 currentNumber = _number; for (uint256 i=0; i<_n; i++) { Booly powerOf2ity = isPowerOf2(currentNumber+1) ? DEFINITELY : DEFINITELY_NOT; if (powerOf2ity == DEFINITELY_NOT) { return (DEFINITELY_NOT, _powers); } _powers[i] = currentNumber = log2ofPowerOf2(currentNumber+1); } return (_result, _powers); } // A good prime's square is greater than the product of all equally distant (by index) primes function isGoodPrime(uint256 _number) external view returns (Booly) { // 2 is defined not to be a good prime. if (_number == 2) return DEFINITELY_NOT; Booly primality = isPrime(_number); if (primality == DEFINITELY) { uint256 index = numberdataToAllPrimesIndex(numberToNumberdata[_number]); if (index*2 >= definitePrimes.length) { // We haven't found enough definite primes yet to determine this property return UNKNOWN; } else { uint256 squareOfInput; bool mulSuccess; (squareOfInput, mulSuccess) = TRY_MUL(_number, _number); if (!mulSuccess) return UNKNOWN; for (uint256 i=1; i<=index; i++) { uint256 square; (square, mulSuccess) = TRY_MUL(definitePrimes[index-i], definitePrimes[index+i]); if (!mulSuccess) return UNKNOWN; if (square >= squareOfInput) { return DEFINITELY_NOT; } } return DEFINITELY; } } else if (primality == PROBABLY || primality == UNKNOWN) { // We can't determine it return UNKNOWN; } else if (primality == DEFINITELY_NOT) { return DEFINITELY_NOT; } else if (primality == PROBABLY_NOT) { return PROBABLY_NOT; } else { // This should never happen revert(); } } // Factorial primes are of the form n!+delta where delta = +1 or delta = -1 function isFactorialPrime(uint256 _number) external view returns (Booly _result, uint256 _n, int256 _delta) { // Prevent underflow on _number-1 if (_number == 0) return (DEFINITELY_NOT, 0, 0); // Prevent overflow on _number+1 if (_number == ~uint256(0)) return (DEFINITELY_NOT, 0, 0); Booly primality = isPrime(_number); if (primality == DEFINITELY_NOT) return (DEFINITELY_NOT, 0, 0); bool factorialityOfPrimePlus1; uint256 primePlus1n; // Detect factorial primes of the form n!-1 (primePlus1n, factorialityOfPrimePlus1) = reverseFactorial(_number+1); if (factorialityOfPrimePlus1) return (AND(primality, factorialityOfPrimePlus1), primePlus1n, -1); bool factorialityOfPrimeMinus1; uint256 primeMinus1n; (primeMinus1n, factorialityOfPrimeMinus1) = reverseFactorial(_number-1); if (factorialityOfPrimeMinus1) return (AND(primality, factorialityOfPrimeMinus1), primeMinus1n, 1); return (DEFINITELY_NOT, 0, 0); } // Cullen primes are of the form n * 2^n + 1 function isCullenPrime(uint256 _number) external pure returns (Booly _result, uint256 _n) { // There are only two cullen primes that fit in a 256-bit integer if (_number == 3) // n = 1 { return (DEFINITELY, 1); } else if (_number == 393050634124102232869567034555427371542904833) // n = 141 { return (DEFINITELY, 141); } else { return (DEFINITELY_NOT, 0); } } // Fermat primes are of the form 2^(2^n)+1 // Conjecturally, 3, 5, 17, 257, 65537 are the only ones function isFermatPrime(uint256 _number) external view returns (Booly result, uint256 _2_pow_n, uint256 _n) { // Prevent underflow on _number-1 if (_number == 0) return (DEFINITELY_NOT, 0, 0); Booly primality = isPrime(_number); if (primality == DEFINITELY_NOT) return (DEFINITELY_NOT, 0, 0); bool is__2_pow_2_pow_n__powerOf2 = isPowerOf2(_number-1); if (!is__2_pow_2_pow_n__powerOf2) return (DEFINITELY_NOT, 0, 0); _2_pow_n = log2ofPowerOf2(_number-1); bool is__2_pow_n__powerOf2 = isPowerOf2(_2_pow_n); if (!is__2_pow_n__powerOf2) return (DEFINITELY_NOT, _2_pow_n, 0); _n = log2ofPowerOf2(_2_pow_n); } // Super-primes are primes with a prime index in the sequence of prime numbers. (indexed starting with 1) function isSuperPrime(uint256 _number) public view returns (Booly _result, uint256 _indexStartAtOne) { Booly primality = isPrime(_number); if (primality == DEFINITELY) { _indexStartAtOne = numberdataToAllPrimesIndex(numberToNumberdata[_number]) + 1; _result = isPrime(_indexStartAtOne); return (_result, _indexStartAtOne); } else if (primality == DEFINITELY_NOT) { return (DEFINITELY_NOT, 0); } else if (primality == UNKNOWN) { return (UNKNOWN, 0); } else if (primality == PROBABLY) { return (UNKNOWN, 0); } else if (primality == PROBABLY_NOT) { return (PROBABLY_NOT, 0); } else { revert(); } } function isFibonacciPrime(uint256 _number) public view returns (Booly _result) { return AND_F(isPrime, isFibonacciNumber, _number); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Number classes //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// function isFibonacciNumber(uint256 _number) public pure returns (Booly _result) { // If _number doesn't fit inside a uint126, we can't perform the computations necessary to check fibonaccality. // We need to be able to square it, multiply by 5 then add 4. // Adding 4 removes 1 bit of room: uint256 -> uint255 // Multiplying by 5 removes 3 bits of room: uint255 -> uint252 // Squaring removes 50% of room: uint252 -> uint126 // Rounding down to the nearest solidity type: uint126 -> uint120 if (uint256(uint120(_number)) != _number) return UNKNOWN; uint256 squareOfNumber = _number * _number; uint256 squareTimes5 = squareOfNumber * 5; uint256 squareTimes5plus4 = squareTimes5 + 4; bool squareTimes5plus4squarality; (squareTimes5plus4squarality, ) = isSquareNumber(squareTimes5plus4); if (squareTimes5plus4squarality) return DEFINITELY; uint256 squareTimes5minus4 = squareTimes5 - 4; bool squareTimes5minus4squarality; // Check underflow if (squareTimes5minus4 > squareTimes5) { squareTimes5minus4squarality = false; } else { (squareTimes5minus4squarality, ) = isSquareNumber(squareTimes5minus4); } return (squareTimes5plus4squarality || squareTimes5minus4squarality) ? DEFINITELY : DEFINITELY_NOT; } function isSquareNumber(uint256 _number) private pure returns (bool _result, uint256 _squareRoot) { uint256 rootRoundedDown = sqrtRoundedDown(_number); return (rootRoundedDown * rootRoundedDown == _number, rootRoundedDown); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Math functions //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// function reverseFactorial(uint256 _number) private pure returns (uint256 output, bool success) { // 0 = immediate failure if (_number == 0) return (0, false); uint256 divisor = 1; while (_number > 1) { divisor++; uint256 remainder = _number % divisor; if (remainder != 0) return (divisor, false); _number /= divisor; } return (divisor, true); } function isPowerOf2(uint256 _number) private pure returns (bool) { if (_number == 0) return false; else return ((_number-1) & _number) == 0; } // Performs a log2 on a power of 2. // This function will throw if the input was not a power of 2. function log2ofPowerOf2(uint256 _powerOf2) private pure returns (uint256) { require(_powerOf2 != 0, "log2ofPowerOf2 error: 0 is not a power of 2"); uint256 iterations = 0; while (true) { if (_powerOf2 == 1) return iterations; require((_powerOf2 & 1) == 0, "log2ofPowerOf2 error: argument is not a power of 2"); // The current number must be divisible by 2 _powerOf2 >>= 1; // Divide by 2 iterations++; } } // Generate a random number with low gas cost. // This RNG is not secure and can be influenced! function insecureRand() private view returns (uint256) { return uint256(keccak256(abi.encodePacked( largestDefinitePrimeFound(), probablePrimes.length, block.coinbase, block.timestamp, block.number, block.difficulty, tx.origin, tx.gasprice, msg.sender, now, gasleft() ))); } // TRY_POW_MOD function defines 0^0 % n = 1 function TRY_POW_MOD(uint256 _base, uint256 _power, uint256 _modulus) private pure returns (uint256 result, bool success) { if (_modulus == 0) return (0, false); bool mulSuccess; _base %= _modulus; result = 1; while (_power > 0) { if (_power & uint256(1) != 0) { (result, mulSuccess) = TRY_MUL(result, _base); if (!mulSuccess) return (0, false); result %= _modulus; } (_base, mulSuccess) = TRY_MUL(_base, _base); if (!mulSuccess) return (0, false); _base = _base % _modulus; _power >>= 1; } success = true; } function TRY_MUL(uint256 _i, uint256 _j) private pure returns (uint256 result, bool success) { if (_i == 0) { return (0, true); } uint256 ret = _i * _j; if (ret / _i == _j) return (ret, true); else return (ret, false); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Miller-rabin //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // This function runs one trial. It returns false if n is // definitely composite and true if n is probably prime. // d must be an odd number such that d*2^r = n-1 for some r >= 1 function probabilisticTest(uint256 d, uint256 _number, uint256 _random) private pure returns (bool result, bool success) { // Check d assert(d & 1 == 1); // d is odd assert((_number-1) % d == 0); // n-1 divisible by d uint256 nMinusOneOverD = (_number-1) / d; assert(isPowerOf2(nMinusOneOverD)); // (n-1)/d is power of 2 assert(nMinusOneOverD >= 1); // 2^r >= 2 therefore r >= 1 // Make sure we can subtract 4 from _number if (_number < 4) return (false, false); // Pick a random number in [2..n-2] uint256 a = 2 + _random % (_number - 4); // Compute a^d % n uint256 x; (x, success) = TRY_POW_MOD(a, d, _number); if (!success) return (false, false); if (x == 1 || x == _number-1) { return (true, true); } // Keep squaring x while one of the following doesn't // happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != _number-1) { (x, success) = TRY_MUL(x, x); if (!success) return (false, false); x %= _number; (d, success) = TRY_MUL(d, 2); if (!success) return (false, false); if (x == 1) return (false, true); if (x == _number-1) return (true, true); } // Return composite return (false, true); } // This functions runs multiple miller-rabin trials. // It returns false if _number is definitely composite and // true if _number is probably prime. function isPrime_probabilistic(uint256 _number) public view returns (Booly) { // 40 iterations is heuristically enough for extremely high certainty uint256 probabilistic_iterations = 40; // Corner cases if (_number == 0 || _number == 1 || _number == 4) return DEFINITELY_NOT; if (_number == 2 || _number == 3) return DEFINITELY; // Find d such that _number == 2^d * r + 1 for some r >= 1 uint256 d = _number - 1; while ((d & 1) == 0) { d >>= 1; } uint256 random = insecureRand(); // Run the probabilistic test many times with different randomness for (uint256 i = 0; i < probabilistic_iterations; i++) { bool result; bool success; (result, success) = probabilisticTest(d, _number, random); if (success == false) { return UNKNOWN; } if (result == false) { return DEFINITELY_NOT; } // Shuffle bits random *= 22777; random ^= (random >> 7); random *= 71879; random ^= (random >> 11); } return PROBABLY; } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Claim & disprove probable primes //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// function claimProbablePrime(uint256 _number) public { require(tryClaimProbablePrime(_number), "claimProbablePrime error: that number is not prime or has already been claimed"); } function tryClaimProbablePrime(uint256 _number) public returns (bool _success) { uint256 startGas = gasleft(); Booly primality = isPrime(_number); // If we already have knowledge about the provided number, cancel the claim attempt. if (primality != UNKNOWN) { _success = false; } else { primality = isPrime_probabilistic(_number); if (primality == DEFINITELY_NOT) { // If it's not prime, remember it as such _numberdataSetNumberType(_number, NumberType.NOT_PRIME); _success = false; } else if (primality == PROBABLY) { _createPrime(_number, msg.sender, false); addressToProbablePrimesClaimed[msg.sender]++; _success = true; } else { _success = false; } } uint256 gasSpent = startGas - gasleft(); addressToGasSpent[msg.sender] += gasSpent; addressToEtherSpent[msg.sender] += gasSpent * tx.gasprice; } function disproveProbablePrime(uint256 _prime, uint256 _divisor) external { require(_divisor > 1 && _divisor < _prime, "disproveProbablePrime error: divisor must be greater than 1 and smaller than prime"); bytes32 numberdata = numberToNumberdata[_prime]; // If _prime is a probable prime... require(numberdataToNumberType(numberdata) == NumberType.PROBABLE_PRIME, "disproveProbablePrime error: that prime is not a probable prime"); // ... and _prime is divisible by _divisor ... require((_prime % _divisor) == 0, "disproveProbablePrime error: that prime is not divisible by that divisor"); address owner = numberdataToOwner(numberdata); // Statistics addressToProbablePrimesDisprovenFrom[owner]++; addressToProbablePrimesDisprovenBy[msg.sender]++; _setOwner(_prime, address(0x0)); _numberdataSetNumberType(_prime, NumberType.NOT_PRIME); // Remove it from the probablePrimes array uint256 primeIndex = numberdataToAllPrimesIndex(numberdata); // If the prime we're removing is not the last one in the probablePrimes array... if (primeIndex < probablePrimes.length-1) { // ...move the last one back into its slot. uint256 otherPrimeBeingMoved = probablePrimes[probablePrimes.length-1]; _numberdataSetAllPrimesIndex(otherPrimeBeingMoved, uint48(primeIndex)); probablePrimes[primeIndex] = otherPrimeBeingMoved; } probablePrimes[probablePrimes.length-1] = 0; // Refund some gas probablePrimes.length--; // Broadcast event emit ProbablePrimeDisproven(_prime, _divisor, owner, msg.sender, primeIndex); // Store the divisor numberToNonTwoDivisor[_prime] = _divisor; } function claimProbablePrimeInRange(uint256 _start, uint256 _end) external returns (bool _success, uint256 _prime) { for (uint256 currentNumber = _start; currentNumber <= _end; currentNumber++) { if (tryClaimProbablePrime(currentNumber)) { return (true, currentNumber); } } return (false, 0); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Try to stop people from //////////// //////////// accidentally sending tokens //////////// //////////// to this contract //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// function onERC721Received(address, address, uint256, bytes calldata) external pure // ERC721 { revert("EtherPrime contract should not receive tokens"); } function tokenFallback(address, uint256, bytes calldata) external pure // ERC223 { revert("EtherPrime contract should not receive tokens"); } function tokensReceived(address, address, address, uint, bytes calldata, bytes calldata) external pure // ERC777 { revert("EtherPrime contract should not receive tokens"); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Booly stuff //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Penta-state logic implementation enum Booly { DEFINITELY_NOT, PROBABLY_NOT, UNKNOWN, PROBABLY, DEFINITELY } Booly public constant DEFINITELY_NOT = Booly.DEFINITELY_NOT; Booly public constant PROBABLY_NOT = Booly.PROBABLY_NOT; Booly public constant UNKNOWN = Booly.UNKNOWN; Booly public constant PROBABLY = Booly.PROBABLY; Booly public constant DEFINITELY = Booly.DEFINITELY; function OR(Booly a, Booly b) internal pure returns (Booly) { if (a == DEFINITELY || b == DEFINITELY) return DEFINITELY; else if (a == PROBABLY || b == PROBABLY) return PROBABLY; else if (a == UNKNOWN || b == UNKNOWN) return UNKNOWN; else if (a == PROBABLY_NOT || b == PROBABLY_NOT) return PROBABLY_NOT; else if (a == DEFINITELY_NOT && b == DEFINITELY_NOT) return DEFINITELY_NOT; else revert(); } function NOT(Booly a) internal pure returns (Booly) { if (a == DEFINITELY_NOT) return DEFINITELY; else if (a == PROBABLY_NOT) return PROBABLY; else if (a == UNKNOWN) return UNKNOWN; else if (a == PROBABLY) return PROBABLY_NOT; else if (a == DEFINITELY) return DEFINITELY_NOT; else revert(); } function AND(Booly a, Booly b) internal pure returns (Booly) { if (a == DEFINITELY_NOT || b == DEFINITELY_NOT) return DEFINITELY_NOT; else if (a == PROBABLY_NOT || b == PROBABLY_NOT) return PROBABLY_NOT; else if (a == UNKNOWN || b == UNKNOWN) return UNKNOWN; else if (a == PROBABLY || b == PROBABLY) return PROBABLY; else if (a == DEFINITELY && b == DEFINITELY) return DEFINITELY; else revert(); } function AND(Booly a, bool b) internal pure returns (Booly) { if (b == true) return a; else return DEFINITELY_NOT; } function XOR(Booly a, Booly b) internal pure returns (Booly) { return AND(OR(a, b), NOT(AND(a, b))); } function NAND(Booly a, Booly b) internal pure returns (Booly) { return NOT(AND(a, b)); } function NOR(Booly a, Booly b) internal pure returns (Booly) { return NOT(OR(a, b)); } function XNOR(Booly a, Booly b) internal pure returns (Booly) { return NOT(XOR(a, b)); } function AND_F(function(uint256)view returns(Booly) aFunc, function(uint256)view returns(Booly) bFunc, uint256 _arg) internal view returns (Booly) { Booly a = aFunc(_arg); if (a == DEFINITELY_NOT) return DEFINITELY_NOT; else { Booly b = bFunc(_arg); if (b == DEFINITELY_NOT) return DEFINITELY_NOT; else if (a == PROBABLY_NOT) return PROBABLY_NOT; else if (b == PROBABLY_NOT) return PROBABLY_NOT; else if (a == UNKNOWN || b == UNKNOWN) return UNKNOWN; else if (a == PROBABLY || b == PROBABLY) return PROBABLY; else if (a == DEFINITELY && b == DEFINITELY) return DEFINITELY; else revert(); } } function OR_F(function(uint256)view returns(Booly) aFunc, function(uint256)view returns(Booly) bFunc, uint256 _arg) internal view returns (Booly) { Booly a = aFunc(_arg); if (a == DEFINITELY) return DEFINITELY; else { Booly b = bFunc(_arg); if (b == DEFINITELY) return DEFINITELY; else if (a == PROBABLY || b == PROBABLY) return PROBABLY; else if (a == UNKNOWN || b == UNKNOWN) return UNKNOWN; else if (a == PROBABLY_NOT || b == PROBABLY_NOT) return PROBABLY_NOT; else if (a == DEFINITELY_NOT && b == DEFINITELY_NOT) return DEFINITELY_NOT; else revert(); } } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Trading stuff //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // depositEther() should only be called at the start of 'external payable' functions. function depositEther() public payable { addressToEtherBalance[msg.sender] += msg.value; emit EtherDeposited(msg.sender, msg.value); } function withdrawEther(uint256 _amount) public { require(addressToEtherBalance[msg.sender] >= _amount, "withdrawEther error: insufficient balance to withdraw that much ether"); addressToEtherBalance[msg.sender] -= _amount; msg.sender.transfer(_amount); emit EtherWithdrawn(msg.sender, _amount); } struct BuyOrder { address buyer; uint256 bid; } function depositEtherAndCreateBuyOrder(uint256 _prime, uint256 _bid, uint256 _indexHint) external payable { depositEther(); require(_bid > 0, "createBuyOrder error: bid must be greater than 0"); require(_prime >= 2, "createBuyOrder error: prime must be greater than or equal to 2"); BuyOrder[] storage buyOrders = primeToBuyOrders[_prime]; uint256 _index; if (_indexHint == buyOrders.length) { _index = _indexHint; } else if (_indexHint < buyOrders.length && buyOrders[_indexHint].buyer == address(0x0) && buyOrders[_indexHint].bid == 0) { _index = _indexHint; } else { _index = findFreeBuyOrderSlot(_prime); } if (_index == buyOrders.length) { buyOrders.length++; } BuyOrder storage buyOrder = buyOrders[_index]; buyOrder.buyer = msg.sender; buyOrder.bid = _bid; emit BuyOrderCreated(msg.sender, _prime, _index, _bid); tryMatchSellAndBuyOrdersRange(_prime, _index, _index); } function modifyBuyOrder(uint256 _prime, uint256 _index, uint256 _newBid) external { BuyOrder[] storage buyOrders = primeToBuyOrders[_prime]; require(_index < buyOrders.length, "modifyBuyOrder error: index out of bounds"); BuyOrder storage buyOrder = buyOrders[_index]; require(buyOrder.buyer == msg.sender, "modifyBuyOrder error: you do not own that buy order"); emit BuyOrderDestroyed(msg.sender, _prime, _index); buyOrder.bid = _newBid; emit BuyOrderCreated(msg.sender, _prime, _index, _newBid); } function tryCancelBuyOrders(uint256[] memory _primes, uint256[] memory _buyOrderIndices) public returns (uint256 _amountCancelled) { require(_primes.length == _buyOrderIndices.length, "tryCancelBuyOrders error: invalid input, arrays are not the same length"); _amountCancelled = 0; for (uint256 i=0; i<_primes.length; i++) { uint256 index = _buyOrderIndices[i]; uint256 prime = _primes[i]; BuyOrder[] storage buyOrders = primeToBuyOrders[prime]; if (index < buyOrders.length) { BuyOrder storage buyOrder = buyOrders[index]; if (buyOrder.buyer == msg.sender) { emit BuyOrderDestroyed(msg.sender, prime, index); buyOrder.buyer = address(0x0); buyOrder.bid = 0; _amountCancelled++; } } } } function setSellPrice(uint256 _prime, uint256 _price, uint256 _matchStartBuyOrderIndex, uint256 _matchEndBuyOrderIndex) external returns (bool _sold) { require(isApprovedFor(msg.sender, _prime), "createSellOrder error: you do not have ownership of or approval for that prime"); primeToSellOrderPrice[_prime] = _price; emit SellPriceSet(msg.sender, _prime, _price); if (_matchStartBuyOrderIndex != ~uint256(0)) { return tryMatchSellAndBuyOrdersRange(_prime, _matchStartBuyOrderIndex, _matchEndBuyOrderIndex); } else { return false; } } function tryMatchSellAndBuyOrdersRange(uint256 _prime, uint256 _startBuyOrderIndex, uint256 _endBuyOrderIndex) public returns (bool _sold) { uint256 sellOrderPrice = primeToSellOrderPrice[_prime]; address seller = getOwner(_prime); if (sellOrderPrice == 0 || seller == address(0x0)) { return false; } else { BuyOrder[] storage buyOrders = primeToBuyOrders[_prime]; uint256 buyOrders_length = buyOrders.length; if (_startBuyOrderIndex > _endBuyOrderIndex || _endBuyOrderIndex >= buyOrders.length) { return false; } else { for (uint256 i=_startBuyOrderIndex; i<=_endBuyOrderIndex && i<buyOrders_length; i++) { BuyOrder storage buyOrder = buyOrders[i]; address buyer = buyOrder.buyer; uint256 bid = buyOrder.bid; if (bid >= sellOrderPrice && addressToEtherBalance[buyer] >= bid) { addressToEtherBalance[buyer] -= bid; addressToEtherBalance[seller] += bid; _setOwner(_prime, buyer); // _setOwner sets primeToSellOrderPrice[_prime] = 0 emit BuyOrderDestroyed(buyer, _prime, i); emit PrimeTraded(seller, buyer, _prime, i, bid); buyOrder.buyer = address(0x0); buyOrder.bid = 0; return true; } } return false; } } } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Trading view functions //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// function countPrimeBuyOrders(uint256 _prime) external view returns (uint256 _amountOfBuyOrders) { _amountOfBuyOrders = 0; BuyOrder[] storage buyOrders = primeToBuyOrders[_prime]; for (uint256 i=0; i<buyOrders.length; i++) { if (buyOrders[i].buyer != address(0x0)) { _amountOfBuyOrders++; } } } function lengthOfPrimeBuyOrdersArray(uint256 _prime) external view returns (uint256 _lengthOfPrimeBuyOrdersArray) { return primeToBuyOrders[_prime].length; } function getPrimeBuyOrder(uint256 _prime, uint256 _index) external view returns (address _buyer, uint256 _bid, bool _buyerHasEnoughFunds) { BuyOrder storage buyOrder = primeToBuyOrders[_prime][_index]; _buyer = buyOrder.buyer; _bid = buyOrder.bid; require(_buyer != address(0x0) && _bid != 0); _buyerHasEnoughFunds = addressToEtherBalance[_buyer] >= _bid; } function findFreeBuyOrderSlot(uint256 _prime) public view returns (uint256 _buyOrderSlotIndex) { BuyOrder[] storage buyOrders = primeToBuyOrders[_prime]; uint256 len = buyOrders.length; for (uint256 i=0; i<len; i++) { if (buyOrders[i].buyer == address(0x0) && buyOrders[i].bid == 0) { return i; } } return len; } function findHighestBidBuyOrder(uint256 _prime) public view returns (bool _found, uint256 _buyOrderIndex, address _buyer, uint256 _bid) { BuyOrder[] storage buyOrders = primeToBuyOrders[_prime]; uint256 highestBidBuyOrderIndexFound = 0; uint256 highestBidFound = 0; address highestBidAddress = address(0x0); for (uint256 i=0; i<buyOrders.length; i++) { BuyOrder storage buyOrder = buyOrders[i]; if (buyOrder.bid > highestBidFound && addressToEtherBalance[buyOrder.buyer] >= buyOrder.bid) { highestBidBuyOrderIndexFound = i; highestBidFound = buyOrder.bid; highestBidAddress = buyOrder.buyer; } } if (highestBidFound == 0) { return (false, 0, address(0x0), 0); } else { return (true, highestBidBuyOrderIndexFound, highestBidAddress, highestBidFound); } } function findBuyOrdersOfUserOnPrime(address _user, uint256 _prime) external view returns (uint256[] memory _buyOrderIndices, uint256[] memory _bids) { BuyOrder[] storage buyOrders = primeToBuyOrders[_prime]; _buyOrderIndices = new uint256[](buyOrders.length); _bids = new uint256[](buyOrders.length); uint256 amountOfBuyOrdersFound = 0; for (uint256 i=0; i<buyOrders.length; i++) { BuyOrder storage buyOrder = buyOrders[i]; if (buyOrder.buyer == _user) { _buyOrderIndices[amountOfBuyOrdersFound] = i; _bids[amountOfBuyOrdersFound] = buyOrder.bid; amountOfBuyOrdersFound++; } } assembly { // _buyOrderIndices.length = amountOfBuyOrdersFound; mstore(_buyOrderIndices, amountOfBuyOrdersFound) // _bids.length = amountOfBuyOrdersFound; mstore(_bids, amountOfBuyOrdersFound) } } function findBuyOrdersOnUsersPrimes(address _user) external view returns (uint256[] memory _primes, uint256[] memory _buyOrderIndices, address[] memory _buyers, uint256[] memory _bids, bool[] memory _buyersHaveEnoughFunds) { uint256[] storage userPrimes = ownerToPrimes[_user]; _primes = new uint256[](userPrimes.length); _buyOrderIndices = new uint256[](userPrimes.length); _buyers = new address[](userPrimes.length); _bids = new uint256[](userPrimes.length); _buyersHaveEnoughFunds = new bool[](userPrimes.length); uint256 amountOfBuyOrdersFound = 0; for (uint256 i=0; i<userPrimes.length; i++) { uint256 prime = userPrimes[i]; bool found; uint256 buyOrderIndex; address buyer; uint256 bid; (found, buyOrderIndex, buyer, bid) = findHighestBidBuyOrder(prime); if (found == true) { _primes[amountOfBuyOrdersFound] = prime; _buyers[amountOfBuyOrdersFound] = buyer; _buyOrderIndices[amountOfBuyOrdersFound] = buyOrderIndex; _bids[amountOfBuyOrdersFound] = bid; _buyersHaveEnoughFunds[amountOfBuyOrdersFound] = addressToEtherBalance[buyer] >= bid; amountOfBuyOrdersFound++; } } assembly { // _primes.length = amountOfBuyOrdersFound; mstore(_primes, amountOfBuyOrdersFound) // _buyOrderIndices.length = amountOfBuyOrdersFound; mstore(_buyOrderIndices, amountOfBuyOrdersFound) // _buyers.length = amountOfBuyOrdersFound; mstore(_buyers, amountOfBuyOrdersFound) // _bids.length = amountOfBuyOrdersFound; mstore(_bids, amountOfBuyOrdersFound) // _buyersHaveEnoughFunds.length = amountOfBuyOrdersFound; mstore(_buyersHaveEnoughFunds, amountOfBuyOrdersFound) } } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////// //////////// //////////// Trading convenience functions //////////// //////////// //////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // These functions don't directly modify state variables. // They only serve as a wrapper for other functions. // They do not introduce new state transitions. /*function withdrawAllEther() external { withdrawEther(addressToEtherBalance[msg.sender]); }*/ /*function cancelBuyOrders(uint256[] calldata _primes, uint256[] calldata _buyOrderIndices) external { require(tryCancelBuyOrders(_primes, _buyOrderIndices) == _primes.length, "cancelBuyOrders error: not all buy orders could be cancelled"); }*/ function tryCancelBuyOrdersAndWithdrawEther(uint256[] calldata _primes, uint256[] calldata _buyOrderIndices, uint256 _amountToWithdraw) external returns (uint256 _amountCancelled) { withdrawEther(_amountToWithdraw); return tryCancelBuyOrders(_primes, _buyOrderIndices); } } contract EtherPrimeChat { EtherPrime etherPrime; constructor(EtherPrime _etherPrime) public { etherPrime = _etherPrime; } // Social mapping(address => bytes32) public addressToUsername; mapping(bytes32 => address) public usernameToAddress; mapping(address => uint256) public addressToGasUsedTowardsChatMessage; uint256 public constant GAS_PER_CHAT_MESSAGE = 1000000; address[] public chatMessageSenders; uint256[] public chatMessageReplyToIndices; string[] public chatMessages; event UsernameSet(address user, bytes32 username); event ChatMessageSent(address indexed sender, uint256 indexed index, uint256 indexed replyToIndex); function setUsername(bytes32 _username) external { require(_username[0] != 0x00); bool seen0x00 = false; for (uint256 i=0; i<32; i++) { if (_username[i] == 0x00) { seen0x00 = true; } // If there's a non-0x00 after an 0x00, this is not a valid string. else if (seen0x00) { revert("setUsername error: invalid string; character present after null terminator"); } } require(usernameToAddress[_username] == address(0x0), "setUsername error: that username already exists"); usernameToAddress[_username] = msg.sender; addressToUsername[msg.sender] = _username; emit UsernameSet(msg.sender, _username); } function amountOfChatMessages() external view returns (uint256) { return chatMessages.length; } function getChatMessage(uint256 _index) external view returns (address _sender, string memory _message, uint256 _replyToIndex) { require(_index < chatMessages.length, "getChatMessage error: index out of bounds"); _sender = chatMessageSenders[_index]; _message = chatMessages[_index]; _replyToIndex = chatMessageReplyToIndices[_replyToIndex]; } function sendChatMessage(string calldata _message, uint256 _replyToIndex) external { require(etherPrime.addressToGasSpent(msg.sender) - addressToGasUsedTowardsChatMessage[msg.sender] >= GAS_PER_CHAT_MESSAGE, "sendChatMessage error: you need to spend more gas on compute() to send a chat message"); require(_replyToIndex == ~uint256(0) || _replyToIndex < chatMessages.length, "sendChatMessage error: invalid reply index"); addressToGasUsedTowardsChatMessage[msg.sender] += GAS_PER_CHAT_MESSAGE; emit ChatMessageSent(msg.sender, chatMessages.length, _replyToIndex); chatMessageReplyToIndices.push(_replyToIndex); chatMessageSenders.push(msg.sender); chatMessages.push(_message); } }
Factorial primes are of the form n!+delta where delta = +1 or delta = -1 Prevent underflow on _number-1 Prevent overflow on _number+1 Detect factorial primes of the form n!-1
function isFactorialPrime(uint256 _number) external view returns (Booly _result, uint256 _n, int256 _delta) { if (_number == 0) return (DEFINITELY_NOT, 0, 0); if (_number == ~uint256(0)) return (DEFINITELY_NOT, 0, 0); Booly primality = isPrime(_number); if (primality == DEFINITELY_NOT) return (DEFINITELY_NOT, 0, 0); bool factorialityOfPrimePlus1; uint256 primePlus1n; (primePlus1n, factorialityOfPrimePlus1) = reverseFactorial(_number+1); if (factorialityOfPrimePlus1) return (AND(primality, factorialityOfPrimePlus1), primePlus1n, -1); bool factorialityOfPrimeMinus1; uint256 primeMinus1n; (primeMinus1n, factorialityOfPrimeMinus1) = reverseFactorial(_number-1); if (factorialityOfPrimeMinus1) return (AND(primality, factorialityOfPrimeMinus1), primeMinus1n, 1); return (DEFINITELY_NOT, 0, 0); }
1,052,735
./full_match/97/0xa650d5fB7002a35d9370Efdad2a0888Ecc252E98/sources/contracts/Darbi/UPMintDarbi.sol
Permissioned function to unpause UPaddress Controller
function unpause() public onlyAdmin { _unpause(); }
5,034,557
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'C4F' Coins4Favors contracts // // contracts for C4FEscrow and C4FToken Crowdsale // // (c) C4F Ltd Hongkong 2018 // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- 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); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // 'C4F' FavorEscrow contract // // Escrow contract for favor request // allows to reserve tokens till a favor is completed, cancelled or arbitrated // handles requester and provider interaction, payout, cancellation and // arbitration if needed. // // (c) C4F Ltd Hongkong 2018 // ---------------------------------------------------------------------------- contract C4FEscrow { using SafeMath for uint; address public owner; address public requester; address public provider; uint256 public startTime; uint256 public closeTime; uint256 public deadline; uint256 public C4FID; uint8 public status; bool public requesterLocked; bool public providerLocked; bool public providerCompleted; bool public requesterDisputed; bool public providerDisputed; uint8 public arbitrationCosts; event ownerChanged(address oldOwner, address newOwner); event deadlineChanged(uint256 oldDeadline, uint256 newDeadline); event favorDisputed(address disputer); event favorUndisputed(address undisputer); event providerSet(address provider); event providerLockSet(bool lockstat); event providerCompletedSet(bool completed_status); event requesterLockSet(bool lockstat); event favorCompleted(address provider, uint256 tokenspaid); event favorCancelled(uint256 tokensreturned); event tokenOfferChanged(uint256 oldValue, uint256 newValue); event escrowArbitrated(address provider, uint256 coinsreturned, uint256 fee); // ---------------------------------------------------------------------------- // modifiers used in this contract to restrict function calls // ---------------------------------------------------------------------------- modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyRequester { require(msg.sender == requester); _; } modifier onlyProvider { require(msg.sender == provider); _; } modifier onlyOwnerOrRequester { require((msg.sender == owner) || (msg.sender == requester)) ; _; } modifier onlyOwnerOrProvider { require((msg.sender == owner) || (msg.sender == provider)) ; _; } modifier onlyProviderOrRequester { require((msg.sender == requester) || (msg.sender == provider)) ; _; } // ---------------------------------------------------------------------------- // Constructor // ---------------------------------------------------------------------------- function C4FEscrow(address newOwner, uint256 ID, address req, uint256 deadl, uint8 arbCostPercent) public { owner = newOwner; // main contract C4FID = ID; requester = req; provider = address(0); startTime = now; deadline = deadl; status = 1; // 1 = open, 2 = cancelled, 3=closed, 4=arbitrated arbitrationCosts = arbCostPercent; requesterLocked = false; providerLocked = false; providerCompleted = false; requesterDisputed = false; providerDisputed = false; } // ---------------------------------------------------------------------------- // returns the owner of the Escrow contract. This is the main C4F Token contract // ---------------------------------------------------------------------------- function getOwner() public view returns (address ownner) { return owner; } function setOwner(address newOwner) public onlyOwner returns (bool success) { require(newOwner != address(0)); ownerChanged(owner,newOwner); owner = newOwner; return true; } // ---------------------------------------------------------------------------- // returns the Requester of the Escrow contract. This is the originator of the favor request // ---------------------------------------------------------------------------- function getRequester() public view returns (address req) { return requester; } // ---------------------------------------------------------------------------- // returns the Provider of the Escrow contract. This is the favor provider // ---------------------------------------------------------------------------- function getProvider() public view returns (address prov) { return provider; } // ---------------------------------------------------------------------------- // returns the startTime of the Escrow contract which is the time it was created // ---------------------------------------------------------------------------- function getStartTime() public view returns (uint256 st) { return startTime; } // ---------------------------------------------------------------------------- // returns the Deadline of the Escrow contract by which completion is needed // Reqeuster can cancel the Escrow 12 hours after deadline expires if favor // is not marked as completed by provider // ---------------------------------------------------------------------------- function getDeadline() public view returns (uint256 actDeadline) { actDeadline = deadline; return actDeadline; } // ---------------------------------------------------------------------------- // adjusts the Deadline of the Escrow contract by which completion is needed // Reqeuster can only change this till a provider accepted (locked) the contract // ---------------------------------------------------------------------------- function changeDeadline(uint newDeadline) public onlyRequester returns (bool success) { // deadline can only be changed if not locked by provider and not completed require ((!providerLocked) && (!providerDisputed) && (!providerCompleted) && (status==1)); deadlineChanged(newDeadline, deadline); deadline = newDeadline; return true; } // ---------------------------------------------------------------------------- // returns the status of the Escrow contract // ---------------------------------------------------------------------------- function getStatus() public view returns (uint8 s) { return status; } // ---------------------------------------------------------------------------- // Initiates dispute of the Escrow contract. Once requester or provider disputeFavor // because they cannot agree on completion, the C4F system can arbitrate the Escrow // based on the internal juror system. // ---------------------------------------------------------------------------- function disputeFavor() public onlyProviderOrRequester returns (bool success) { if(msg.sender == requester) { requesterDisputed = true; } if(msg.sender == provider) { providerDisputed = true; providerLocked = true; } favorDisputed(msg.sender); return true; } // ---------------------------------------------------------------------------- // Allows to take back a dispute on the Escrow if conflict has been resolved // ---------------------------------------------------------------------------- function undisputeFavor() public onlyProviderOrRequester returns (bool success) { if(msg.sender == requester) { requesterDisputed = false; } if(msg.sender == provider) { providerDisputed = false; } favorUndisputed(msg.sender); return true; } // ---------------------------------------------------------------------------- // allows to set the address of the provider for the Favor // this can be done by the requester or the C4F system // once the provider accepts, the providerLock flag disables changes to this // ---------------------------------------------------------------------------- function setProvider(address newProvider) public onlyOwnerOrRequester returns (bool success) { // can only change provider if not locked by current provider require(!providerLocked); require(!requesterLocked); provider = newProvider; providerSet(provider); return true; } // ---------------------------------------------------------------------------- // switches the ProviderLock on or off. Once provider lock is switched on, // it means the provider has formally accepted the offer and changes are // blocked // ---------------------------------------------------------------------------- function setProviderLock(bool lock) public onlyOwnerOrProvider returns (bool res) { providerLocked = lock; providerLockSet(lock); return providerLocked; } // ---------------------------------------------------------------------------- // allows to set Favor to completed from Provider view, indicating that // provider sess Favor as delivered // ---------------------------------------------------------------------------- function setProviderCompleted(bool c) public onlyOwnerOrProvider returns (bool res) { providerCompleted = c; providerCompletedSet(c); return c; } // ---------------------------------------------------------------------------- // allows to set requester lock, indicating requester accepted favor provider // ---------------------------------------------------------------------------- function setRequesterLock(bool lock) public onlyOwnerOrRequester returns (bool res) { requesterLocked = lock; requesterLockSet(lock); return requesterLocked; } function getRequesterLock() public onlyOwnerOrRequester view returns (bool res) { res = requesterLocked; return res; } // ---------------------------------------------------------------------------- // allows the C4F system to change the status of an Escrow contract // ---------------------------------------------------------------------------- function setStatus(uint8 newStatus) public onlyOwner returns (uint8 stat) { status = newStatus; stat = status; return stat; } // ---------------------------------------------------------------------------- // returns the current Token value of the escrow for competing the favor // this is the token balance of the escrow contract in the main contract // ---------------------------------------------------------------------------- function getTokenValue() public view returns (uint256 tokens) { C4FToken C4F = C4FToken(owner); return C4F.balanceOf(address(this)); } // ---------------------------------------------------------------------------- // completes the favor Escrow and pays out the tokens minus the commission fee // ---------------------------------------------------------------------------- function completeFavor() public onlyRequester returns (bool success) { // check if provider has been set require(provider != address(0)); // payout tokens to provider with commission uint256 actTokenvalue = getTokenValue(); C4FToken C4F = C4FToken(owner); if(!C4F.transferWithCommission(provider, actTokenvalue)) revert(); closeTime = now; status = 3; favorCompleted(provider,actTokenvalue); return true; } // ---------------------------------------------------------------------------- // this function cancels a favor request on behalf of the requester // only possible as long as no provider accepted the contract or 12 hours // after the deadline if the provider did not indicate completion or disputed // ---------------------------------------------------------------------------- function cancelFavor() public onlyRequester returns (bool success) { // cannot cancel if locked by provider unless deadline expired by 12 hours and not completed/disputed require((!providerLocked) || ((now > deadline.add(12*3600)) && (!providerCompleted) && (!providerDisputed))); // cannot cancel after completed or arbitrated require(status==1); // send tokens back to requester uint256 actTokenvalue = getTokenValue(); C4FToken C4F = C4FToken(owner); if(!C4F.transfer(requester,actTokenvalue)) revert(); closeTime = now; status = 2; favorCancelled(actTokenvalue); return true; } // ---------------------------------------------------------------------------- // allows the favor originator to reduce the token offer // This can only be done until a provider has accepted (locked) the favor request // ---------------------------------------------------------------------------- function changeTokenOffer(uint256 newOffer) public onlyRequester returns (bool success) { // cannot change if locked by provider require((!providerLocked) && (!providerDisputed) && (!providerCompleted)); // cannot change if cancelled, closed or arbitrated require(status==1); // only use for reducing tokens (to increase simply transfer tokens to contract) uint256 actTokenvalue = getTokenValue(); require(newOffer < actTokenvalue); // cannot set to 0, use cancel to do that require(newOffer > 0); // pay back tokens to reach new offer level C4FToken C4F = C4FToken(owner); if(!C4F.transfer(requester, actTokenvalue.sub(newOffer))) revert(); tokenOfferChanged(actTokenvalue,newOffer); return true; } // ---------------------------------------------------------------------------- // arbitration can be done by the C4F system once requester or provider have // disputed the favor contract. An independent juror system on the platform // will vote on the outcome and define a split of the tokens between the two // parties. The jurors get a percentage which is preset in the contratct for // the arbitration // ---------------------------------------------------------------------------- function arbitrateC4FContract(uint8 percentReturned) public onlyOwner returns (bool success) { // can only arbitrate if one of the two parties has disputed require((providerDisputed) || (requesterDisputed)); // C4F System owner can arbitrate and provide a split of tokens between 0-100% uint256 actTokens = getTokenValue(); // calc. arbitration fee based on percent costs uint256 arbitrationTokens = actTokens.mul(arbitrationCosts); arbitrationTokens = arbitrationTokens.div(100); // subtract these from the tokens to be distributed between requester and provider actTokens = actTokens.sub(arbitrationTokens); // now split the tokens up using provided percentage uint256 requesterTokens = actTokens.mul(percentReturned); requesterTokens = requesterTokens.div(100); // actTokens to hold what gets forwarded to provider actTokens = actTokens.sub(requesterTokens); // distribute the Tokens C4FToken C4F = C4FToken(owner); // arbitration tokens go to commissiontarget of master contract address commissionTarget = C4F.getCommissionTarget(); // requester gets refunded his split if(!C4F.transfer(requester, requesterTokens)) revert(); // provider gets his split of tokens if(!C4F.transfer(provider, actTokens)) revert(); // arbitration fee to system for distribution if(!C4F.transfer(commissionTarget, arbitrationTokens)) revert(); // set status & closeTime status = 4; closeTime = now; success = true; escrowArbitrated(provider,requesterTokens,arbitrationTokens); return success; } } // ---------------------------------------------------------------------------- // 'C4F' 'Coins4Favors FavorCoin contract // // Symbol : C4F // Name : FavorCoin // Total supply: 100,000,000,000.000000000000000000 // Decimals : 18 // // includes the crowdsale price, PreICO bonus structure, limits on sellable tokens // function to pause sale, commission fee transfer and favorcontract management // // (c) C4F Ltd Hongkong 2018 // ---------------------------------------------------------------------------- contract C4FToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint8 public _crowdsalePaused; uint public _totalSupply; uint public _salesprice; uint public _endOfICO; uint public _endOfPreICO; uint public _beginOfICO; uint public _bonusTime1; uint public _bonusTime2; uint public _bonusRatio1; uint public _bonusRatio2; uint public _percentSoldInPreICO; uint public _maxTokenSoldPreICO; uint public _percentSoldInICO; uint public _maxTokenSoldICO; uint public _total_sold; uint public _commission; uint8 public _arbitrationPercent; address public _commissionTarget; uint public _minimumContribution; address[] EscrowAddresses; uint public _escrowIndex; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => uint) whitelisted_amount; mapping(address => bool) C4FEscrowContracts; event newEscrowCreated(uint ID, address contractAddress, address requester); event ICOStartSet(uint256 starttime); event ICOEndSet(uint256 endtime); event PreICOEndSet(uint256 endtime); event BonusTime1Set(uint256 bonustime); event BonusTime2Set(uint256 bonustime); event accountWhitelisted(address account, uint256 limit); event crowdsalePaused(bool paused); event crowdsaleResumed(bool resumed); event commissionSet(uint256 commission); event commissionTargetSet(address target); event arbitrationPctSet(uint8 arbpercent); event contractOwnerChanged(address escrowcontract, address newOwner); event contractProviderChanged(address C4Fcontract, address provider); event contractArbitrated(address C4Fcontract, uint8 percentSplit); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function C4FToken() public { symbol = "C4F"; name = "C4F FavorCoins"; decimals = 18; _totalSupply = 100000000000 * 10**uint(decimals); _salesprice = 2000000; // C4Fs per 1 Eth _minimumContribution = 0.05 * 10**18; // minimum amount is 0.05 Ether _endOfICO = 1532908800; // end of ICO is 30.07.18 _beginOfICO = 1526342400; // begin is 15.05.18 _bonusRatio1 = 110; // 10% Bonus in second week of PreICO _bonusRatio2 = 125; // 25% Bonus in first week of PreICO _bonusTime1 = 1527638400; // prior to 30.05.18 add bonusRatio1 _bonusTime2 = 1526947200; // prior to 22.05.18 add bonusRatio2 _endOfPreICO = 1527811200; // Pre ICO ends 01.06.2018 _percentSoldInPreICO = 10; // we only offer 10% of total Supply during PreICO _maxTokenSoldPreICO = _totalSupply.mul(_percentSoldInPreICO); _maxTokenSoldPreICO = _maxTokenSoldPreICO.div(100); _percentSoldInICO = 60; // in addition to 10% sold in PreICO, 60% sold in ICO _maxTokenSoldICO = _totalSupply.mul(_percentSoldInPreICO.add(_percentSoldInICO)); _maxTokenSoldICO = _maxTokenSoldICO.div(100); _total_sold = 0; // total coins sold _commission = 0; // no comission on transfers _commissionTarget = owner; // default any commission goes to the owner of the contract _arbitrationPercent = 10; // default costs for arbitration of an escrow contract // is transferred to escrow contract at time of creation and kept there _crowdsalePaused = 0; balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // notLocked: ensure no coins are moved by owners prior to end of ICO // ------------------------------------------------------------------------ modifier notLocked { require((msg.sender == owner) || (now >= _endOfICO)); _; } // ------------------------------------------------------------------------ // onlyDuringICO: FavorCoins can only be bought via contract during ICO // ------------------------------------------------------------------------ modifier onlyDuringICO { require((now >= _beginOfICO) && (now <= _endOfICO)); _; } // ------------------------------------------------------------------------ // notPaused: ability to stop crowdsale if problems occur // ------------------------------------------------------------------------ modifier notPaused { require(_crowdsalePaused == 0); _; } // ------------------------------------------------------------------------ // set ICO and PRE ICO Dates // ------------------------------------------------------------------------ function setICOStart(uint ICOdate) public onlyOwner returns (bool success) { _beginOfICO = ICOdate; ICOStartSet(_beginOfICO); return true; } function setICOEnd(uint ICOdate) public onlyOwner returns (bool success) { _endOfICO = ICOdate; ICOEndSet(_endOfICO); return true; } function setPreICOEnd(uint ICOdate) public onlyOwner returns (bool success) { _endOfPreICO = ICOdate; PreICOEndSet(_endOfPreICO); return true; } function setBonusDate1(uint ICOdate) public onlyOwner returns (bool success) { _bonusTime1 = ICOdate; BonusTime1Set(_bonusTime1); return true; } function setBonusDate2(uint ICOdate) public onlyOwner returns (bool success) { _bonusTime2 = ICOdate; BonusTime2Set(_bonusTime2); return true; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Whitelist address up to maximum spending (AML and KYC) // ------------------------------------------------------------------------ function whitelistAccount(address account, uint limit) public onlyOwner { whitelisted_amount[account] = limit*10**18; accountWhitelisted(account,limit); } // ------------------------------------------------------------------------ // return maximum remaining whitelisted amount for account // ------------------------------------------------------------------------ function getWhitelistLimit(address account) public constant returns (uint limit) { return whitelisted_amount[account]; } // ------------------------------------------------------------------------ // Pause crowdsale in case of any problems // ------------------------------------------------------------------------ function pauseCrowdsale() public onlyOwner returns (bool success) { _crowdsalePaused = 1; crowdsalePaused(true); return true; } function resumeCrowdsale() public onlyOwner returns (bool success) { _crowdsalePaused = 0; crowdsaleResumed(true); return true; } // ------------------------------------------------------------------------ // Commission can be added later to a percentage of the transferred // C4F tokens for operating costs of the system. Percentage is capped at 2% // ------------------------------------------------------------------------ function setCommission(uint comm) public onlyOwner returns (bool success) { require(comm < 200); // we allow a maximum of 2% commission _commission = comm; commissionSet(comm); return true; } function setArbitrationPercentage(uint8 arbitPct) public onlyOwner returns (bool success) { require(arbitPct <= 15); // we allow a maximum of 15% arbitration costs _arbitrationPercent = arbitPct; arbitrationPctSet(_arbitrationPercent); return true; } function setCommissionTarget(address ct) public onlyOwner returns (bool success) { _commissionTarget = ct; commissionTargetSet(_commissionTarget); return true; } function getCommissionTarget() public view returns (address ct) { ct = _commissionTarget; return ct; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // - users cannot transfer C4Fs prior to close of ICO // - only owner can transfer anytime to do airdrops, etc. // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public notLocked notPaused returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // this function will be used by the C4F app to charge a Commission // on transfers later // ------------------------------------------------------------------------ function transferWithCommission(address to, uint tokens) public notLocked notPaused returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); // split tokens using commission Percentage uint comTokens = tokens.mul(_commission); comTokens = comTokens.div(10000); // adjust balances balances[to] = balances[to].add(tokens.sub(comTokens)); balances[_commissionTarget] = balances[_commissionTarget].add(comTokens); // trigger events Transfer(msg.sender, to, tokens.sub(comTokens)); Transfer(msg.sender, _commissionTarget, comTokens); return true; } // ------------------------------------------------------------------------ // TransferInternal handles Transfer of Tokens from Owner during ICO and Pre-ICO // ------------------------------------------------------------------------ function transferInternal(address to, uint tokens) private returns (bool success) { balances[owner] = balances[owner].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public notLocked notPaused returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // not possivbe before end of ICO // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public notLocked notPaused returns (bool success) { // check allowance is high enough require(allowed[from][msg.sender] >= tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // startEscrow FavorContract // starts an escrow contract and transfers the tokens into the contract // ------------------------------------------------------------------------ function startFavorEscrow(uint256 ID, uint256 deadl, uint tokens) public notLocked returns (address C4FFavorContractAddr) { // check if sufficient coins available require(balanceOf(msg.sender) >= tokens); // create contract address newFavor = new C4FEscrow(address(this), ID, msg.sender, deadl, _arbitrationPercent); // add to list of C4FEscrowContratcs EscrowAddresses.push(newFavor); C4FEscrowContracts[newFavor] = true; // transfer tokens to contract if(!transfer(newFavor, tokens)) revert(); C4FFavorContractAddr = newFavor; newEscrowCreated(ID, newFavor, msg.sender); return C4FFavorContractAddr; } function isFavorEscrow(uint id, address c4fes) public view returns (bool res) { if(EscrowAddresses[id] == c4fes) { res = true; } else { res = false; } return res; } function getEscrowCount() public view returns (uint) { return EscrowAddresses.length; } function getEscrowAddress(uint ind) public view returns(address esa) { require (ind <= EscrowAddresses.length); esa = EscrowAddresses[ind]; return esa; } // use this function to allow C4F System to adjust owner of C4FEscrows function setC4FContractOwner(address C4Fcontract, address newOwner) public onlyOwner returns (bool success) { require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call setProvider from there if(!c4fec.setOwner(newOwner)) revert(); contractOwnerChanged(C4Fcontract,newOwner); return true; } // use this function to allow C4F System to adjust provider of C4F Favorcontract function setC4FContractProvider(address C4Fcontract, address provider) public onlyOwner returns (bool success) { // ensure this is a C4FEscrowContract initiated by C4F system require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call setProvider from there if(!c4fec.setProvider(provider)) revert(); contractProviderChanged(C4Fcontract, provider); return true; } // use this function to allow C4F System to adjust providerLock function setC4FContractProviderLock(address C4Fcontract, bool lock) public onlyOwner returns (bool res) { // ensure this is a C4FEscrowContract initiated by C4F system require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call setProviderLock from there res = c4fec.setProviderLock(lock); return res; } // use this function to allow C4F System to adjust providerCompleted status function setC4FContractProviderCompleted(address C4Fcontract, bool completed) public onlyOwner returns (bool res) { // ensure this is a C4FEscrowContract initiated by C4F system require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call setProviderCompleted from there res = c4fec.setProviderCompleted(completed); return res; } // use this function to allow C4F System to adjust providerLock function setC4FContractRequesterLock(address C4Fcontract, bool lock) public onlyOwner returns (bool res) { // ensure this is a C4FEscrowContract initiated by C4F system require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call setRequesterLock from there res = c4fec.setRequesterLock(lock); return res; } function setC4FContractStatus(address C4Fcontract, uint8 newStatus) public onlyOwner returns (uint8 s) { // ensure this is a C4FEscrowContract initiated by C4F system require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call setStatus from there s = c4fec.setStatus(newStatus); return s; } function arbitrateC4FContract(address C4Fcontract, uint8 percentSplit) public onlyOwner returns (bool success) { // ensure this is a C4FEscrowContract initiated by C4F system require(C4FEscrowContracts[C4Fcontract]); C4FEscrow c4fec = C4FEscrow(C4Fcontract); // call arbitration if(!c4fec.arbitrateC4FContract(percentSplit)) revert(); contractArbitrated(C4Fcontract, percentSplit); return true; } // ------------------------------------------------------------------------ // Convert to C4Fs using salesprice and bonus period and forward Eth to owner // ------------------------------------------------------------------------ function () public onlyDuringICO notPaused payable { // check bonus ratio uint bonusratio = 100; // check for second week bonus if(now <= _bonusTime1) { bonusratio = _bonusRatio1; } // check for first week bonus if(now <= _bonusTime2) { bonusratio = _bonusRatio2; } // minimum contribution met ? require (msg.value >= _minimumContribution); // send C4F tokens back to sender based on Ether received if (msg.value > 0) { // check if whitelisted and sufficient contribution left (AML & KYC) if(!(whitelisted_amount[msg.sender] >= msg.value)) revert(); // reduce remaining contribution limit whitelisted_amount[msg.sender] = whitelisted_amount[msg.sender].sub(msg.value); // determine amount of C4Fs uint256 token_amount = msg.value.mul(_salesprice); token_amount = token_amount.mul(bonusratio); token_amount = token_amount.div(100); uint256 new_total = _total_sold.add(token_amount); // check if PreICO volume sold off if(now <= _endOfPreICO){ // check if we are above the limit with this transfer, then bounce if(new_total > _maxTokenSoldPreICO) revert(); } // check if exceeding total ICO sale tokens if(new_total > _maxTokenSoldICO) revert(); // transfer tokens from owner account to sender if(!transferInternal(msg.sender, token_amount)) revert(); _total_sold = new_total; // forward received ether to owner account if (!owner.send(msg.value)) revert(); // also reverts the transfer. } } }
------------------------------------------------------------------------ Transfer `tokens` from the `from` account to the `to` account not possivbe before end of ICO The calling account must already have sufficient tokens approve(...)-d for spending from the `from` account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------ check allowance is high enough
function transferFrom(address from, address to, uint tokens) public notLocked notPaused returns (bool success) { require(allowed[from][msg.sender] >= tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; }
1,501,523
./partial_match/1/0x1E3A682f5f9BDD87b88D28dc2eC9EDE002bfE95e/sources/vnxManager.sol
A method to remove a bearer from a role _account The account to remove as a bearer. _role The role to remove the bearer from./
function removeBearer(address _account, uint256 _role) external { require( _role < roles.length, "Role doesn't exist." ); require( hasRole(msg.sender, roles[_role].admin), "User can't remove bearers." ); require( hasRole(_account, _role), "Account is not bearer of role." ); if ( _role == roles[_role].admin && roles[_role].bearersCount == 1) { revert("Cannot remove last role admin"); } delete roles[_role].bearers[_account]; roles[_role].bearersCount--; emit BearerRemoved(_account, _role); }
3,979,003
pragma solidity ^0.5.5; //WLC VERSION 10 /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) interface ERC721 { // Required methods function totalSupply() external view returns (uint256 total); function balanceOf(address _owner) external view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function exists(uint256 _tokenId) external view returns (bool _exists); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional function tokensOfOwner(address _owner) external view returns (uint256[] memory tokenIds); function supportsInterface(bytes4 _interfaceID) external view returns (bool); } /** * @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 ERC721 { function name() external view returns (string memory _name); function symbol() external view returns (string memory _symbol); function tokenURI(uint256 _tokenId) public view returns (string memory); } contract DreamCarToken { function getWLCReward(uint256 _boughtWLCAmount, address _owner) public returns (uint256 remaining) {} function getForWLC(address _owner) public {} } contract WishListToken is ERC721, ERC721Metadata { string internal constant tokenName = 'WishListCoin'; string internal constant tokenSymbol = 'WLC'; uint256 public constant decimals = 0; //ERC721 VARIABLES //the total count of wishes uint256 public totalTokenSupply; //this address is the CEO address payable public CEO; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; //TOKEN SPECIFIC VARIABLES // Mapping from owner to ids of owned tokens mapping (address => uint256[]) internal tokensOwnedBy; // Mapping from owner to ids of exchanged tokens mapping (address => uint256[]) internal tokensExchangedBy; //Token price in WEI uint256 public tokenPrice; //A list of price admins; they can change price, in addition to the CEO address[] public priceAdmins; //Next id that will be assigned to token uint256 internal nextTokenId = 1; //DCC INTERACTION VARIABLES //A list, containing the addresses of DreamCarToken contracts, which will be used to award bonus tokens, //when an user purchases a large number of WLC tokens DreamCarToken[] public dreamCarCoinContracts; //A DreamCarToken contract address, which will be used to allow the excange of WLC tokens for DCC tokens DreamCarToken public dreamCarCoinExchanger; //ERC721 FUNCTIONS IMPLEMENTATIONS function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /** * Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256 total) { return totalTokenSupply; } /** * 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 _balance) { return tokensOwnedBy[_owner].length; } /** * 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 _owner) { return tokenOwner[_tokenId]; } /** * 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); } /** * Returns a list of the tokens ids, owned by the passed address * @param _owner address the address to chesck * @return the list of token ids */ function tokensOfOwner(address _owner) external view returns (uint256[] memory tokenIds) { return tokensOwnedBy[_owner]; } /** * Transfers the specified token to the specified address * @param _to address the receiver * @param _tokenId uint256 the id of the token */ function transfer(address _to, uint256 _tokenId) external { require(_to != address(0)); ensureAddressIsTokenOwner(msg.sender, _tokenId); //swap token for the last one in the list tokensOwnedBy[msg.sender][ownedTokensIndex[_tokenId]] = tokensOwnedBy[msg.sender][tokensOwnedBy[msg.sender].length - 1]; //record the changed position of the last element ownedTokensIndex[tokensOwnedBy[msg.sender][tokensOwnedBy[msg.sender].length - 1]] = ownedTokensIndex[_tokenId]; //remove last element of the list tokensOwnedBy[msg.sender].pop(); //delete tokensOwnedBy[msg.sender][ownedTokensIndex[_tokenId]]; tokensOwnedBy[_to].push(_tokenId); tokenOwner[_tokenId] = _to; ownedTokensIndex[_tokenId] = tokensOwnedBy[_to].length - 1; emit Transfer(msg.sender, _to, _tokenId); } /** * Not necessary in the contract */ function approve(address _to, uint256 _tokenId) external { } /** * Not necessary in the contract */ function transferFrom(address _from, address _to, uint256 _tokenId) external { } /** * Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string storage _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } //ERC721Metadata FUNCTIONS IMPLEMENTATIONS /** * Gets the token name * @return string representing the token name */ function name() external view returns (string memory _name) { return tokenName; } /** * Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string memory _symbol) { return tokenSymbol; } /** * Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string memory) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } //TOKEN SPECIFIC FUNCTIONS event Buy(address indexed from, uint256 amount, uint256 fromTokenId, uint256 toTokenId, uint256 timestamp); event Exchange(address indexed from, uint256 tokenId); event ExchangeForDCC(address indexed from, uint256 tokenId); /** * Ensures that the caller of the function is the CEO of contract */ modifier onlyCEO { require(msg.sender == CEO, 'You need to be the CEO to do that!'); _; } /** * Constructor of the contract * @param _ceo address the CEO (owner) of the contract */ constructor (address payable _ceo) public { CEO = _ceo; totalTokenSupply = 1001000; tokenPrice = 3067484662576687; // (if eth = 163USD, 0.5 USD for token) } /** * Gets an array of all tokens ids, exchanged by the specified address * @param _owner address The excanger of the tokens * @return uint256[] The list of exchanged tokens ids */ function exchangedBy(address _owner) external view returns (uint256[] memory tokenIds) { return tokensExchangedBy[_owner]; } /** * Gets the last existing token ids * @return uint256 the id of the token */ function lastTokenId() public view returns (uint256 tokenId) { return nextTokenId - 1; } /** * Sets a new price for the tokensExchangedBy * @param _newPrice uint256 the new price in WEI */ function setTokenPriceInWEI(uint256 _newPrice) public { bool transactionAllowed = false; if (msg.sender == CEO) { transactionAllowed = true; } else { for (uint256 i = 0; i < priceAdmins.length; i++) { if (msg.sender == priceAdmins[i]) { transactionAllowed = true; break; } } } require((transactionAllowed == true), 'You cannot do that!'); tokenPrice = _newPrice; } /** * Add a new price admin address to the list * @param _newPriceAdmin address the address of the new price admin */ function addPriceAdmin(address _newPriceAdmin) onlyCEO public { priceAdmins.push(_newPriceAdmin); } /** * Remove existing price admin address from the list * @param _existingPriceAdmin address the address of the existing price admin */ function removePriceAdmin(address _existingPriceAdmin) onlyCEO public { for (uint256 i = 0; i < priceAdmins.length; i++) { if (_existingPriceAdmin == priceAdmins[i]) { delete priceAdmins[i]; break; } } } /** * Adds the specified number of tokens to the specified address * Internal method, used when creating new tokens * @param _to address The address, which is going to own the tokens * @param _amount uint256 The number of tokens */ function _addTokensToAddress(address _to, uint256 _amount) internal { for (uint256 i = 0; i < _amount; i++) { tokensOwnedBy[_to].push(nextTokenId + i); tokenOwner[nextTokenId + i] = _to; ownedTokensIndex[nextTokenId + i] = tokensOwnedBy[_to].length - 1; } nextTokenId += _amount; } /** * Checks if the specified token is owned by the transaction sender */ function ensureAddressIsTokenOwner(address _owner, uint256 _tokenId) internal view { require(balanceOf(_owner) >= 1, 'You do not own any tokens!'); require(tokenOwner[_tokenId] == _owner, 'You do not own this token!'); } /** * Scales the amount of tokens in a purchase, to ensure it will be less or equal to the amount of unsold tokens * If there are no tokens left, it will return 0 * @param _amount uint256 the amout of tokens in the purchase attempt * @return _exactAmount uint256 */ function scalePurchaseTokenAmountToMatchRemainingTokens(uint256 _amount) internal view returns (uint256 _exactAmount) { if (nextTokenId + _amount - 1 > totalTokenSupply) { _amount = totalTokenSupply - nextTokenId + 1; } if (balanceOf(msg.sender) + _amount > 100) { _amount = 100 - balanceOf(msg.sender); require(_amount > 0, "You can own maximum of 100 tokens!"); } return _amount; } /** * Buy new tokens with ETH * Calculates the nubmer of tokens for the given ETH amount * Creates the new tokens when they are purchased * Returns the excessive ETH (if any) to the transaction sender */ function buy() payable public { require(msg.value >= tokenPrice, "You did't send enough ETH"); uint256 amount = scalePurchaseTokenAmountToMatchRemainingTokens(msg.value / tokenPrice); require(amount > 0, "Not enough tokens are available for purchase!"); _addTokensToAddress(msg.sender, amount); emit Buy(msg.sender, amount, nextTokenId - amount, nextTokenId - 1, now); //transfer ETH to CEO CEO.transfer((amount * tokenPrice)); getDCCRewards(amount); //returns excessive ETH msg.sender.transfer(msg.value - (amount * tokenPrice)); } /** * Removes a token from the provided address ballance and puts it in the tokensExchangedBy mapping * @param _owner address the address of the token owner * @param _tokenId uint256 the id of the token */ function exchangeToken(address _owner, uint256 _tokenId) internal { ensureAddressIsTokenOwner(_owner, _tokenId); //swap token for the last one in the list tokensOwnedBy[_owner][ownedTokensIndex[_tokenId]] = tokensOwnedBy[_owner][tokensOwnedBy[_owner].length - 1]; //record the changed position of the last element ownedTokensIndex[tokensOwnedBy[_owner][tokensOwnedBy[_owner].length - 1]] = ownedTokensIndex[_tokenId]; //remove last element of the list tokensOwnedBy[_owner].pop(); ownedTokensIndex[_tokenId] = 0; delete tokenOwner[_tokenId]; tokensExchangedBy[_owner].push(_tokenId); } /** * Allows user to destroy a specified token in order to claim his prize for the it * @param _tokenId uint256 ID of the token */ function exchange(uint256 _tokenId) public { exchangeToken(msg.sender, _tokenId); emit Exchange(msg.sender, _tokenId); } /** * Allows the CEO to increase the totalTokenSupply * @param _amount uint256 the number of tokens to create */ function mint(uint256 _amount) onlyCEO public { require (_amount > 0, 'Amount must be bigger than 0!'); totalTokenSupply += _amount; } //DCC INTERACTION FUNCTIONS /** * Adds a DreamCarToken contract address to the list on a specific position. * This allows to maintain and control the order of DreamCarToken contracts, according to their bonus rates * @param _index uint256 the index where the address will be inserted/overwritten * @param _address address the address of the DreamCarToken contract */ function setDreamCarCoinAddress(uint256 _index, address _address) public onlyCEO { require (_address != address(0)); if (dreamCarCoinContracts.length > 0 && dreamCarCoinContracts.length - 1 >= _index) { dreamCarCoinContracts[_index] = DreamCarToken(_address); } else { dreamCarCoinContracts.push(DreamCarToken(_address)); } } /** * Removes a DreamCarToken contract address from the list, by its list index * @param _index uint256 the position of the address */ function removeDreamCarCoinAddress(uint256 _index) public onlyCEO { delete(dreamCarCoinContracts[_index]); } /** * Allows the CEO to set an address of DreamCarToken contract, which will be used to excanger * WLCs for DCCs * @param _address address the address of the DreamCarToken contract */ function setDreamCarCoinExchanger(address _address) public onlyCEO { require (_address != address(0)); dreamCarCoinExchanger = DreamCarToken(_address); } /** * Allows the CEO to remove the address of DreamCarToken contract, which will be used to excanger * WLCs for DCCs */ function removeDreamCarCoinExchanger() public onlyCEO { dreamCarCoinExchanger = DreamCarToken(address(0)); } /** * Allows the buyer of WLC coins to receive DCCs as bonus. * Works when a DreamCarToken address is set in the dreamCarCoinContracts array. * Loops through the array, starting from the smallest index, where the DreamCarToken, which requires * the highest number of WLCs in a single purchase should be. * Gets the remaining WLCs, after the bonus is payed and tries to get bonus from the other DreamCarToken contracts * in the list * @param _amount uint256 how many tokens was purchased by the buyer */ function getDCCRewards(uint256 _amount) internal { for (uint256 i = 0; i < dreamCarCoinContracts.length; i++) { if (_amount > 0 && address(dreamCarCoinContracts[i]) != address(0)) { _amount = dreamCarCoinContracts[i].getWLCReward(_amount, msg.sender); } else { break; } } } /** * Allows a user to exchange any WLC coin token a DCC token * @param _tokenId uint256 the id of the owned token */ function exchangeForDCC(uint256 _tokenId) public { require (address(dreamCarCoinExchanger) != address(0)); dreamCarCoinExchanger.getForWLC(msg.sender); exchangeToken(msg.sender, _tokenId); emit ExchangeForDCC(msg.sender, _tokenId); } }
Returns an URI for a given token ID Throws if the token ID does not exist. May return an empty string. _tokenId uint256 ID of the token to query/
function tokenURI(uint256 _tokenId) public view returns (string memory) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } event Buy(address indexed from, uint256 amount, uint256 fromTokenId, uint256 toTokenId, uint256 timestamp); event Exchange(address indexed from, uint256 tokenId); event ExchangeForDCC(address indexed from, uint256 tokenId);
13,086,803