file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IController { function vaults(address) external view returns (address); function rewards() external view returns (address); function devfund() external view returns (address); function treasury() external view returns (address); function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function withdrawReward(address, uint256) external; function earn(address, uint256) external; function strategies(address) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; interface IRedeemPool { event RedeemStart(address indexed starter, uint256 reward); event DepositBond(address indexed owner, uint256 amount); event RewardClaimed(address indexed owner, uint256 amount); event ReCharge( address indexed owner, address indexed token, uint256 indexed rid, uint256 amount ); event ReChargeETH( address indexed owner, uint256 indexed rid, uint256 amount ); event Withdrawal( address indexed from, address indexed to, uint256 indexed at ); function rechargeCash(uint256 _rid, uint256 _amount) external; function cashToClaim() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; interface IStakingRewards { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function getReward() external; function stake(uint256 amount) external; function totalSupply() external view returns (uint256); function withdraw(uint256 amount) external; function transferOperator(address newOperator_) external; } // SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; interface UniswapRouterV2 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 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 (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; 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 ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); 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 skim(address to) external; function sync() external; } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } // 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; } } // File: contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./safe-math.sol"; import "./context.sol"; // File: 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: 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 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"); 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: 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 { } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev 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.7; import "../strategy-basis-farm-base.sol"; contract StrategyBasisBac is StrategyBasisFarmBase { // Token addresses address public staking_pool = 0x190503cFbE97d77E83dedfC550C79EFd6E2E799f; address public bac = 0x3449FC1Cd036255BA1EB19d65fF4BA2b8903A69a; constructor( address _governance, address _strategist, address _controller, address _timelock, address _redeem, address _burn, address _bond ) public StrategyBasisFarmBase( bac, staking_pool, bac, _governance, _strategist, _controller, _timelock, _redeem, _burn, _bond ) { } // **** Views **** function getName() external override pure returns (string memory) { return "StrategyBasisBac"; } } pragma solidity ^0.6.7; import "../lib/erc20.sol"; import "../lib/safe-math.sol"; import "../interfaces/staking-rewards.sol"; import "../interfaces/uniswapv2.sol"; import "../interfaces/controller.sol"; import "../interfaces/redeem.sol"; // Strategy Contract Basics abstract contract StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; using SafeMath for uint112; // Perfomance fees - start with 20% uint256 public performanceTreasuryFee = 2000; uint256 public constant performanceTreasuryMax = 10000; uint256 public performanceDevFee = 0; uint256 public constant performanceDevMax = 10000; // Withdrawal fee 0% // - 0% to treasury // - 0% to dev fund uint256 public withdrawalTreasuryFee = 0; uint256 public constant withdrawalTreasuryMax = 100000; uint256 public withdrawalDevFundFee = 0; uint256 public constant withdrawalDevFundMax = 100000; // Tokens address public want; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant pair = 0xd4405F0704621DBe9d4dEA60E128E0C3b26bddbD; // User accounts address public governance; address public controller; address public strategist; address public timelock; address public redeem; address public bond; address public burn; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public sushiRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; mapping(address => bool) public harvesters; constructor( address _want, address _governance, address _strategist, address _controller, address _timelock, address _redeem, address _burn, address _bond ) public { require(_want != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_controller != address(0)); require(_timelock != address(0)); want = _want; governance = _governance; strategist = _strategist; controller = _controller; timelock = _timelock; redeem = _redeem; burn = _burn; bond = _bond; } // **** Modifiers **** // modifier onlyBenevolent { require( harvesters[msg.sender] || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public virtual view returns (uint256); function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function getName() external virtual pure returns (string memory); // **** Setters **** // function whitelistHarvester(address _harvester) external { require(msg.sender == governance || msg.sender == strategist, "not authorized"); harvesters[_harvester] = true; } function revokeHarvester(address _harvester) external { require(msg.sender == governance || msg.sender == strategist, "not authorized"); harvesters[_harvester] = false; } function setWithdrawalDevFundFee(uint256 _withdrawalDevFundFee) external { require(msg.sender == timelock, "!timelock"); withdrawalDevFundFee = _withdrawalDevFundFee; } function setWithdrawalTreasuryFee(uint256 _withdrawalTreasuryFee) external { require(msg.sender == timelock, "!timelock"); withdrawalTreasuryFee = _withdrawalTreasuryFee; } function setPerformanceDevFee(uint256 _performanceDevFee) external { require(msg.sender == timelock, "!timelock"); performanceDevFee = _performanceDevFee; } function setPerformanceTreasuryFee(uint256 _performanceTreasuryFee) external { require(msg.sender == timelock, "!timelock"); performanceTreasuryFee = _performanceTreasuryFee; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) external { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) external { require(msg.sender == timelock, "!timelock"); controller = _controller; } function setBurn(address _burn) external { require(msg.sender == timelock, "!timelock"); burn = _burn; } // **** State mutations **** // function deposit() public virtual; // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _feeDev = _amount.mul(withdrawalDevFundFee).div( withdrawalDevFundMax ); IERC20(want).safeTransfer(IController(controller).devfund(), _feeDev); uint256 _feeTreasury = _amount.mul(withdrawalTreasuryFee).div( withdrawalTreasuryMax ); IERC20(want).safeTransfer( IController(controller).treasury(), _feeTreasury ); address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, _amount.sub(_feeDev).sub(_feeTreasury)); } // Withdraw funds, used to swap between strategies function withdrawForSwap(uint256 _amount) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawSome(_amount); balance = IERC20(want).balanceOf(address(this)); address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); IERC20(want).safeTransfer(_vault, balance); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } function _withdrawAll() internal { _withdrawSome(balanceOfPool()); } function _withdrawSome(uint256 _amount) internal virtual returns (uint256); function harvest(uint256 amount, uint256 minOut) public virtual; // **** Emergency functions **** function execute(address _target, bytes memory _data) public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _swapUniswap( address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); address[] memory path; if (_from == weth || _to == weth) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; } UniswapRouterV2(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } function _swapUniswapWithPath( address[] memory path, uint256 _amount, uint256 _minOut ) internal { require(path[1] != address(0)); UniswapRouterV2(univ2Router2).swapExactTokensForTokens( _amount, _minOut, path, address(this), now.add(60) ); } function _bacPrice() internal view returns (uint256) { (uint112 r1, uint112 r2, ) = IUniswapV2Pair(pair).getReserves(); return r2.mul(1e18).div(r1); } function redeemFee() public view returns (uint256) { uint256 bacPrice = _bacPrice(); if (bacPrice > 1e18) { return 0; } if (IERC20(want).balanceOf(redeem).sub(IRedeemPool(redeem).cashToClaim()) > IERC20(bond).totalSupply().sub(IERC20(bond).balanceOf(burn))) { return 0; } return uint256(1e18).sub(bacPrice).mul(3).div(10); } function _distributePerformanceFeesAndDeposit() internal { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { // Treasury fees IERC20(want).safeTransfer( IController(controller).treasury(), _want.mul(performanceTreasuryFee).div(performanceTreasuryMax) ); // Performance fee IERC20(want).safeTransfer( IController(controller).devfund(), _want.mul(performanceDevFee).div(performanceDevMax) ); // redeem fee IERC20(want).approve(redeem, _want.mul(redeemFee()).div(1e18)); IRedeemPool(redeem).rechargeCash(1, _want.mul(redeemFee()).div(1e18)); deposit(); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.7; import "./strategy-staking-rewards-base.sol"; abstract contract StrategyBasisFarmBase is StrategyStakingRewardsBase { // Token addresses address public bas = 0x106538CC16F938776c7c180186975BCA23875287; //bas v2 share token address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // DAI/<token1> pair address public token1; // How much BAS tokens to keep? uint256 public keepBAS = 0; uint256 public constant keepBASMax = 10000; constructor( address _token1, address _rewards, address _want, address _governance, address _strategist, address _controller, address _timelock, address _redeem, address _burn, address _bond ) public StrategyStakingRewardsBase( _rewards, _want, _governance, _strategist, _controller, _timelock, _redeem, _burn, _bond ) { token1 = _token1; IERC20(dai).approve(univ2Router2, uint(-1)); IERC20(bas).approve(univ2Router2, uint(-1)); } // **** Setters **** function setKeepBAS(uint256 _keepBAS) external { require(msg.sender == timelock, "!timelock"); keepBAS = _keepBAS; } // **** State Mutations **** function harvest(uint256 amount, uint256 minOut) public override onlyBenevolent { address[] memory path = new address[](3); // Collects BAS tokens IStakingRewards(rewards).getReward(); uint256 _bas = IERC20(bas).balanceOf(address(this)); if (_bas > 0) { // 10% is locked up for future gov uint256 _keepBAS = _bas.mul(keepBAS).div(keepBASMax); IERC20(bas).safeTransfer( IController(controller).treasury(), _keepBAS ); path[0] = bas; path[1] = dai; path[2] = token1; if(amount > _bas.sub(_keepBAS)) { amount = _bas.sub(_keepBAS); } _swapUniswapWithPath(path, amount, minOut); } // We want to get back Bac tokens _distributePerformanceFeesAndDeposit(); } } pragma solidity ^0.6.7; import "./strategy-base.sol"; // Base contract for SNX Staking rewards contract interfaces abstract contract StrategyStakingRewardsBase is StrategyBase { address public rewards; // **** Getters **** constructor( address _rewards, address _want, address _governance, address _strategist, address _controller, address _timelock, address _redeem, address _burn, address _bond ) public StrategyBase(_want, _governance, _strategist, _controller, _timelock, _redeem, _burn, _bond) { rewards = _rewards; } function balanceOfPool() public override view returns (uint256) { return IStakingRewards(rewards).balanceOf(address(this)); } function getHarvestable() external view returns (uint256) { return IStakingRewards(rewards).earned(address(this)); } // **** Setters **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(rewards, 0); IERC20(want).safeApprove(rewards, _want); IStakingRewards(rewards).stake(_want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { IStakingRewards(rewards).withdraw(_amount); return _amount; } }
Emergency functions call contract in current context throw if delegatecall failed
function _withdrawSome(uint256 _amount) internal virtual returns (uint256); function harvest(uint256 amount, uint256 minOut) public virtual; function execute(address _target, bytes memory _data) public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { revert(add(response, 0x20), size) } } }
10,022,639
// SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Ownable * @dev Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol */ abstract contract Ownable { /************* * Variables * *************/ address public owner; /********** * Events * **********/ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /*************** * Constructor * ***************/ constructor() { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } /********************** * Function Modifiers * **********************/ modifier onlyOwner() { require( owner == msg.sender, "Ownable: caller is not the owner" ); _; } /******************** * Public Functions * ********************/ /** * Sets the owner of this contract to the zero address, effectively renouncing ownership * completely. Can only be called by the current owner of this contract. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } /** * Transfers ownership of this contract to a new address. Can only be called by the current * owner of this contract. * @param _newOwner Address of the new contract owner. */ function transferOwnership( address _newOwner ) public virtual onlyOwner { require( _newOwner != address(0), "Ownable: new owner cannot be the zero address" ); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } }
Sets the owner of this contract to the zero address, effectively renouncing ownership completely. Can only be called by the current owner of this contract./
function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); }
12,663,595
pragma solidity 0.4.23; /** * @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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn'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 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]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title 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 view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /// @title Token /// @author Jose Perez - <[email protected]> /// @notice ERC20 token /// @dev The contract allows to perform a number of token sales in different periods in time. /// allowing participants in previous token sales to transfer tokens to other accounts. /// Additionally, token locking logic for KYC/AML compliance checking is supported. contract Token is StandardToken, Ownable { using SafeMath for uint256; string public constant name = "Token"; string public constant symbol = "TOK"; uint256 public constant decimals = 18; // Using same number of decimal figures as ETH (i.e. 18). uint256 public constant TOKEN_UNIT = 10 ** uint256(decimals); // Maximum number of tokens in circulation uint256 public constant MAX_TOKEN_SUPPLY = 3000000000 * TOKEN_UNIT; // Maximum number of tokens sales to be performed. uint256 public constant MAX_TOKEN_SALES = 2; // Maximum size of the batch functions input arrays. uint256 public constant MAX_BATCH_SIZE = 400; address public assigner; // The address allowed to assign or mint tokens during token sale. address public locker; // The address allowed to lock/unlock addresses. mapping(address => bool) public locked; // If true, address' tokens cannot be transferred. uint256 public currentTokenSaleId = 0; // The id of the current token sale. mapping(address => uint256) public tokenSaleId; // In which token sale the address participated. bool public tokenSaleOngoing = false; event TokenSaleStarting(uint indexed tokenSaleId); event TokenSaleEnding(uint indexed tokenSaleId); event Lock(address indexed addr); event Unlock(address indexed addr); event Assign(address indexed to, uint256 amount); event Mint(address indexed to, uint256 amount); event LockerTransferred(address indexed previousLocker, address indexed newLocker); event AssignerTransferred(address indexed previousAssigner, address indexed newAssigner); /// @dev Constructor that initializes the contract. /// @param _assigner The assigner account. /// @param _locker The locker account. constructor(address _assigner, address _locker) public { require(_assigner != address(0)); require(_locker != address(0)); assigner = _assigner; locker = _locker; } /// @dev True if a token sale is ongoing. modifier tokenSaleIsOngoing() { require(tokenSaleOngoing); _; } /// @dev True if a token sale is not ongoing. modifier tokenSaleIsNotOngoing() { require(!tokenSaleOngoing); _; } /// @dev Throws if called by any account other than the assigner. modifier onlyAssigner() { require(msg.sender == assigner); _; } /// @dev Throws if called by any account other than the locker. modifier onlyLocker() { require(msg.sender == locker); _; } /// @dev Starts a new token sale. Only the owner can start a new token sale. If a token sale /// is ongoing, it has to be ended before a new token sale can be started. /// No more than `MAX_TOKEN_SALES` sales can be carried out. /// @return True if the operation was successful. function tokenSaleStart() external onlyOwner tokenSaleIsNotOngoing returns(bool) { require(currentTokenSaleId < MAX_TOKEN_SALES); currentTokenSaleId++; tokenSaleOngoing = true; emit TokenSaleStarting(currentTokenSaleId); return true; } /// @dev Ends the current token sale. Only the owner can end a token sale. /// @return True if the operation was successful. function tokenSaleEnd() external onlyOwner tokenSaleIsOngoing returns(bool) { emit TokenSaleEnding(currentTokenSaleId); tokenSaleOngoing = false; return true; } /// @dev Returns whether or not a token sale is ongoing. /// @return True if a token sale is ongoing. function isTokenSaleOngoing() external view returns(bool) { return tokenSaleOngoing; } /// @dev Getter of the variable `currentTokenSaleId`. /// @return Returns the current token sale id. function getCurrentTokenSaleId() external view returns(uint256) { return currentTokenSaleId; } /// @dev Getter of the variable `tokenSaleId[]`. /// @param _address The address of the participant. /// @return Returns the id of the token sale the address participated in. function getAddressTokenSaleId(address _address) external view returns(uint256) { return tokenSaleId[_address]; } /// @dev Allows the current owner to change the assigner. /// @param _newAssigner The address of the new assigner. /// @return True if the operation was successful. function transferAssigner(address _newAssigner) external onlyOwner returns(bool) { require(_newAssigner != address(0)); emit AssignerTransferred(assigner, _newAssigner); assigner = _newAssigner; return true; } /// @dev Function to mint tokens. It can only be called by the assigner during an ongoing token sale. /// @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 onlyAssigner tokenSaleIsOngoing returns(bool) { totalSupply_ = totalSupply_.add(_amount); require(totalSupply_ <= MAX_TOKEN_SUPPLY); if (tokenSaleId[_to] == 0) { tokenSaleId[_to] = currentTokenSaleId; } require(tokenSaleId[_to] == currentTokenSaleId); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /// @dev Mints tokens for several addresses in one single call. /// @param _to address[] The addresses that get the tokens. /// @param _amount address[] The number of tokens to be minted. /// @return A boolean that indicates if the operation was successful. function mintInBatches(address[] _to, uint256[] _amount) external onlyAssigner tokenSaleIsOngoing returns(bool) { require(_to.length > 0); require(_to.length == _amount.length); require(_to.length <= MAX_BATCH_SIZE); for (uint i = 0; i < _to.length; i++) { mint(_to[i], _amount[i]); } return true; } /// @dev Function to assign any number of tokens to a given address. /// Compared to the `mint` function, the `assign` function allows not just to increase but also to decrease /// the number of tokens of an address by assigning a lower value than the address current balance. /// This function can only be executed during initial token sale. /// @param _to The address that will receive the assigned tokens. /// @param _amount The amount of tokens to assign. /// @return True if the operation was successful. function assign(address _to, uint256 _amount) public onlyAssigner tokenSaleIsOngoing returns(bool) { require(currentTokenSaleId == 1); // The desired value to assign (`_amount`) can be either higher or lower than the current number of tokens // of the address (`balances[_to]`). To calculate the new `totalSupply_` value, the difference between `_amount` // and `balances[_to]` (`delta`) is calculated first, and then added or substracted to `totalSupply_` accordingly. uint256 delta = 0; if (balances[_to] < _amount) { // balances[_to] will be increased, so totalSupply_ should be increased delta = _amount.sub(balances[_to]); totalSupply_ = totalSupply_.add(delta); } else { // balances[_to] will be decreased, so totalSupply_ should be decreased delta = balances[_to].sub(_amount); totalSupply_ = totalSupply_.sub(delta); } require(totalSupply_ <= MAX_TOKEN_SUPPLY); balances[_to] = _amount; tokenSaleId[_to] = currentTokenSaleId; emit Assign(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /// @dev Assigns tokens to several addresses in one call. /// @param _to address[] The addresses that get the tokens. /// @param _amount address[] The number of tokens to be assigned. /// @return True if the operation was successful. function assignInBatches(address[] _to, uint256[] _amount) external onlyAssigner tokenSaleIsOngoing returns(bool) { require(_to.length > 0); require(_to.length == _amount.length); require(_to.length <= MAX_BATCH_SIZE); for (uint i = 0; i < _to.length; i++) { assign(_to[i], _amount[i]); } return true; } /// @dev Allows the current owner to change the locker. /// @param _newLocker The address of the new locker. /// @return True if the operation was successful. function transferLocker(address _newLocker) external onlyOwner returns(bool) { require(_newLocker != address(0)); emit LockerTransferred(locker, _newLocker); locker = _newLocker; return true; } /// @dev Locks an address. A locked address cannot transfer its tokens or other addresses' tokens out. /// Only addresses participating in the current token sale can be locked. /// Only the locker account can lock addresses and only during the token sale. /// @param _address address The address to lock. /// @return True if the operation was successful. function lockAddress(address _address) public onlyLocker tokenSaleIsOngoing returns(bool) { require(tokenSaleId[_address] == currentTokenSaleId); require(!locked[_address]); locked[_address] = true; emit Lock(_address); return true; } /// @dev Unlocks an address so that its owner can transfer tokens out again. /// Addresses can be unlocked any time. Only the locker account can unlock addresses /// @param _address address The address to unlock. /// @return True if the operation was successful. function unlockAddress(address _address) public onlyLocker returns(bool) { require(locked[_address]); locked[_address] = false; emit Unlock(_address); return true; } /// @dev Locks several addresses in one single call. /// @param _addresses address[] The addresses to lock. /// @return True if the operation was successful. function lockInBatches(address[] _addresses) external onlyLocker returns(bool) { require(_addresses.length > 0); require(_addresses.length <= MAX_BATCH_SIZE); for (uint i = 0; i < _addresses.length; i++) { lockAddress(_addresses[i]); } return true; } /// @dev Unlocks several addresses in one single call. /// @param _addresses address[] The addresses to unlock. /// @return True if the operation was successful. function unlockInBatches(address[] _addresses) external onlyLocker returns(bool) { require(_addresses.length > 0); require(_addresses.length <= MAX_BATCH_SIZE); for (uint i = 0; i < _addresses.length; i++) { unlockAddress(_addresses[i]); } return true; } /// @dev Checks whether or not the given address is locked. /// @param _address address The address to be checked. /// @return Boolean indicating whether or not the address is locked. function isLocked(address _address) external view returns(bool) { return locked[_address]; } /// @dev Transfers tokens to the specified address. It prevents transferring tokens from a locked address. /// Locked addresses can receive tokens. /// Current token sale's addresses cannot receive or send tokens until the token sale ends. /// @param _to The address to transfer tokens to. /// @param _value The number of tokens to be transferred. function transfer(address _to, uint256 _value) public returns(bool) { require(!locked[msg.sender]); if (tokenSaleOngoing) { require(tokenSaleId[msg.sender] < currentTokenSaleId); require(tokenSaleId[_to] < currentTokenSaleId); } return super.transfer(_to, _value); } /// @dev Transfers tokens from one address to another. It prevents transferring tokens if the caller is locked or /// if the allowed address is locked. /// Locked addresses can receive tokens. /// Current token sale's addresses cannot receive or send tokens until the token sale ends. /// @param _from address The address to transfer tokens from. /// @param _to address The address to transfer tokens to. /// @param _value The number of tokens to be transferred. function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!locked[msg.sender]); require(!locked[_from]); if (tokenSaleOngoing) { require(tokenSaleId[msg.sender] < currentTokenSaleId); require(tokenSaleId[_from] < currentTokenSaleId); require(tokenSaleId[_to] < currentTokenSaleId); } return super.transferFrom(_from, _to, _value); } } /// @title ExchangeRate /// @author Jose Perez - <[email protected]> /// @notice Tamper-proof record of exchange rates e.g. BTC/USD, ETC/USD, etc. /// @dev Exchange rates are updated from off-chain server periodically. Rates are taken from a // publicly available third-party provider, such as Coinbase, CoinMarketCap, etc. contract ExchangeRate is Ownable { event RateUpdated(string id, uint256 rate); event UpdaterTransferred(address indexed previousUpdater, address indexed newUpdater); address public updater; mapping(string => uint256) internal currentRates; /// @dev The ExchangeRate constructor. /// @param _updater Account which can update the rates. constructor(address _updater) public { require(_updater != address(0)); updater = _updater; } /// @dev Throws if called by any account other than the updater. modifier onlyUpdater() { require(msg.sender == updater); _; } /// @dev Allows the current owner to change the updater. /// @param _newUpdater The address of the new updater. function transferUpdater(address _newUpdater) external onlyOwner { require(_newUpdater != address(0)); emit UpdaterTransferred(updater, _newUpdater); updater = _newUpdater; } /// @dev Allows the current updater account to update a single rate. /// @param _id The rate identifier. /// @param _rate The exchange rate. function updateRate(string _id, uint256 _rate) external onlyUpdater { require(_rate != 0); currentRates[_id] = _rate; emit RateUpdated(_id, _rate); } /// @dev Allows anyone to read the current rate. /// @param _id The rate identifier. /// @return The current rate. function getRate(string _id) external view returns(uint256) { return currentRates[_id]; } } /// @title VestingTrustee /// @author Jose Perez - <[email protected]> /// @notice Vesting trustee contract for Diginex ERC20 tokens. Tokens are granted to specific /// addresses and vested under certain criteria (vesting period, cliff period, etc.) // All time units are in seconds since Unix epoch. /// Tokens must be transferred to the VestingTrustee contract address prior to granting them. contract VestingTrustee is Ownable { using SafeMath for uint256; // ERC20 contract. Token public token; // The address allowed to grant and revoke tokens. address public vester; // Vesting grant for a specific holder. struct Grant { uint256 value; uint256 start; uint256 cliff; uint256 end; uint256 installmentLength; uint256 transferred; bool revocable; } // Holder to grant information mapping. mapping (address => Grant) public grants; // Total tokens available for vesting. uint256 public totalVesting; event NewGrant(address indexed _from, address indexed _to, uint256 _value); event TokensUnlocked(address indexed _to, uint256 _value); event GrantRevoked(address indexed _holder, uint256 _refund); event VesterTransferred(address indexed previousVester, address indexed newVester); /// @dev Constructor that initializes the VestingTrustee contract. /// @param _token The address of the previously deployed ERC20 token contract. /// @param _vester The vester address. constructor(Token _token, address _vester) public { require(_token != address(0)); require(_vester != address(0)); token = _token; vester = _vester; } // @dev Prevents being called by any account other than the vester. modifier onlyVester() { require(msg.sender == vester); _; } /// @dev Allows the owner to change the vester. /// @param _newVester The address of the new vester. /// @return True if the operation was successful. function transferVester(address _newVester) external onlyOwner returns(bool) { require(_newVester != address(0)); emit VesterTransferred(vester, _newVester); vester = _newVester; return true; } /// @dev Grant tokens to a specified address. /// Tokens must be transferred to the VestingTrustee contract address prior to calling this /// function. The number of tokens assigned to the VestingTrustee contract address must // always be equal or greater than the total number of vested tokens. /// @param _to address The holder address. /// @param _value uint256 The amount of tokens to be granted. /// @param _start uint256 The beginning of the vesting period. /// @param _cliff uint256 Time, between _start and _end, when the first installment is made. /// @param _end uint256 The end of the vesting period. /// @param _installmentLength uint256 The length of each vesting installment. /// @param _revocable bool Whether the grant is revocable or not. function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revocable) external onlyVester { require(_to != address(0)); require(_to != address(this)); // Don't allow holder to be this contract. require(_value > 0); // Require that every holder can be granted tokens only once. require(grants[_to].value == 0); // Require for time ranges to be consistent and valid. require(_start <= _cliff && _cliff <= _end); // Require installment length to be valid and no longer than (end - start). require(_installmentLength > 0 && _installmentLength <= _end.sub(_start)); // Grant must not exceed the total amount of tokens currently available for vesting. require(totalVesting.add(_value) <= token.balanceOf(address(this))); // Assign a new grant. grants[_to] = Grant({ value: _value, start: _start, cliff: _cliff, end: _end, installmentLength: _installmentLength, transferred: 0, revocable: _revocable }); // Since tokens have been granted, increase the total amount of vested tokens. // This indirectly reduces the total amount available for vesting. totalVesting = totalVesting.add(_value); emit NewGrant(msg.sender, _to, _value); } /// @dev Revoke the grant of tokens of a specified grantee address. /// The vester can arbitrarily revoke the tokens of a revocable grant anytime. /// However, the grantee owns `calculateVestedTokens` number of tokens, even if some of them /// have not been transferred to the grantee yet. Therefore, the `revoke` function should /// transfer all non-transferred tokens to their rightful owner. The rest of the granted tokens /// should be transferred to the vester. /// @param _holder The address which will have its tokens revoked. function revoke(address _holder) public onlyVester { Grant storage holderGrant = grants[_holder]; // Grant must be revocable. require(holderGrant.revocable); // Calculate number of tokens to be transferred to vester and to holder: // holderGrant.value = toVester + vested = toVester + ( toHolder + holderGrant.transferred ) uint256 vested = calculateVestedTokens(holderGrant, now); uint256 toVester = holderGrant.value.sub(vested); uint256 toHolder = vested.sub(holderGrant.transferred); // Remove grant information. delete grants[_holder]; // Update totalVesting. totalVesting = totalVesting.sub(toHolder); totalVesting = totalVesting.sub(toVester); // Transfer tokens. token.transfer(_holder, toHolder); token.transfer(vester, toVester); emit GrantRevoked(_holder, toVester); } /// @dev Calculate amount of vested tokens at a specifc time. /// @param _grant Grant The vesting grant. /// @param _time uint256 The time to be checked /// @return a uint256 Representing the amount of vested tokens of a specific grant. function calculateVestedTokens(Grant _grant, uint256 _time) private pure returns (uint256) { // If we're before the cliff, then nothing is vested. if (_time < _grant.cliff) { return 0; } // If we're after the end of the vesting period - everything is vested; if (_time >= _grant.end) { return _grant.value; } // Calculate amount of installments past until now. // NOTE: result gets floored because of integer division. uint256 installmentsPast = _time.sub(_grant.start).div(_grant.installmentLength); // Calculate amount of time in entire vesting period. uint256 vestingPeriod = _grant.end.sub(_grant.start); // Calculate and return installments that have passed according to vesting time that have passed. return _grant.value.mul(installmentsPast.mul(_grant.installmentLength)).div(vestingPeriod); } /// @dev Calculate the total amount of vested tokens of a holder at a given time. /// @param _holder address The address of the holder. /// @param _time uint256 The specific time to calculate against. /// @return a uint256 Representing a holder's total amount of vested tokens. function vestedTokens(address _holder, uint256 _time) external view returns (uint256) { Grant memory holderGrant = grants[_holder]; if (holderGrant.value == 0) { return 0; } return calculateVestedTokens(holderGrant, _time); } /// @dev Unlock vested tokens and transfer them to their holder. /// @param _holder address The address of the holder. function unlockVestedTokens(address _holder) external { Grant storage holderGrant = grants[_holder]; // Require that there will be funds left in grant to transfer to holder. require(holderGrant.value.sub(holderGrant.transferred) > 0); // Get the total amount of vested tokens, according to grant. uint256 vested = calculateVestedTokens(holderGrant, now); if (vested == 0) { return; } // Make sure the holder doesn't transfer more than what he already has. uint256 transferable = vested.sub(holderGrant.transferred); if (transferable == 0) { return; } // Update transferred and total vesting amount, then transfer remaining vested funds to holder. holderGrant.transferred = holderGrant.transferred.add(transferable); totalVesting = totalVesting.sub(transferable); token.transfer(_holder, transferable); emit TokensUnlocked(_holder, transferable); } }
Allows the owner to change the vester. _newVester The address of the new vester. return True if the operation was successful.
function transferVester(address _newVester) external onlyOwner returns(bool) { require(_newVester != address(0)); emit VesterTransferred(vester, _newVester); vester = _newVester; return true; }
12,976,282
./full_match/1/0x501acEF3315c5DcFE37be35fB59e33d755898E1A/sources/contracts/Governable.sol
Address of the current governor.
function governance() external view override returns (address) { return _governance; }
4,992,483
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./SpaceCoin.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title A contract for rolling out an ICO of SpaceCoin * @author Nathan Thomas * @notice This contract is not audited - Use at your own risk! */ contract ICO is Ownable { // ICO is for 150,000 tokens at 5/1 tokens/ether uint256 private constant TOKEN_MULTIPLIER = 5; // Seed phase is 75,000 tokens with an individual cap uint256 private constant SEED_CONTRIBUTIONS_PER_ADDRESS = 1_500 ether; uint256 private constant SEED_CONTRIBUTIONS_CAP = 15_000 ether; // General phase is 75,000 tokens with an individual cap uint256 private constant GENERAL_CONTRIBUTIONS_PER_ADDRESS = 1_000 ether; uint256 private constant GENERAL_CONTRIBUTIONS_CAP = 30_000 ether; enum Phases { SEED, GENERAL, OPEN } Phases public currentPhase = Phases.SEED; bool public isInitialized = false; bool public isPaused = false; address public tokenAddress; uint256 public totalContributions = 0; mapping(address => uint256) public addressToContributions; mapping(address => bool) public approvedSeedInvestors; event NewInvestment(address indexed purchaser, uint256 etherAmount); event NewPhase(Phases indexed phase); event Refund(address indexed refundAddress, uint256 etherAmount); event TokensClaimed(address indexed claimingAddress, uint256 tokenAmount); modifier hasBeenInitialized() { require(isInitialized, "ICO: not initialized"); _; } modifier hasNotBeenInitialized() { require(!isInitialized, "ICO: has been initialized"); _; } modifier isNotPaused() { require(!isPaused, "ICO: the ICO is paused"); _; } modifier isOpenPhase() { require(currentPhase == Phases.OPEN, "ICO: not open phase"); _; } modifier canContributeForCurrentPhase() { if (currentPhase == Phases.SEED) { require( totalContributions < SEED_CONTRIBUTIONS_CAP, "ICO: phase contributions reached" ); require( addressToContributions[msg.sender] < SEED_CONTRIBUTIONS_PER_ADDRESS, "ICO: contribution maximum reached" ); require( approvedSeedInvestors[msg.sender], "ICO: address is not approved" ); } else if (currentPhase == Phases.GENERAL) { require( totalContributions < GENERAL_CONTRIBUTIONS_CAP, "ICO: phase contributions reached" ); require( addressToContributions[msg.sender] < GENERAL_CONTRIBUTIONS_PER_ADDRESS, "ICO: contribution maximum reached" ); } _; } /** * @notice Allows users to buy tokens in the ICO * @dev Addresses can participate under the following conditions: * - For seed phase, they must be approved and under 1,500 ether limit * - For general phase, they must be under the 1,000 limit (inclusive of seed) * In addition, the private method _getExcessEtherToReturn checks if the address should have * ether returned to it with the following constraints: * - If msg.value puts address partly over max individual contribution limit for phase, * the excess is returned * - If the msg.value puts the address partly over the max contribution limit for the phase, * the excess is returned * If there is excess ether to return, that call is made immediately */ function buyTokens() external payable hasBeenInitialized isNotPaused canContributeForCurrentPhase { uint256 amountToReturn = _getExcessEtherToReturn(msg.value); uint256 validContributionAmount = msg.value - amountToReturn; addressToContributions[msg.sender] += validContributionAmount; totalContributions += validContributionAmount; if (amountToReturn > 0) { (bool success, ) = msg.sender.call{ value: amountToReturn }(""); require(success, "ICO: excess funds transfer failed"); emit Refund(msg.sender, amountToReturn); } emit NewInvestment(msg.sender, validContributionAmount); } /** * @notice Allows addresses that participated in the ICO to claim tokens in open phase */ function claimTokens() external hasBeenInitialized isOpenPhase { require( addressToContributions[msg.sender] > 0, "ICO: address has no contributions" ); uint256 amountToTransfer = addressToContributions[msg.sender] * 5; bool success = IERC20(tokenAddress).transfer(msg.sender, amountToTransfer); require(success, "ICO: tokens could not be claimed"); emit TokensClaimed(msg.sender, amountToTransfer); } /** emit TokensClaimed(msg.sender, amountToTransfer); * @notice Allows the owner to initialize (e.g. start) the ICO contract * @param _tokenAddress The deployed token address to be used in the ICO */ function initialize(address _tokenAddress) external onlyOwner hasNotBeenInitialized { require(_tokenAddress != address(0), "ICO: address must be valid"); tokenAddress = _tokenAddress; isInitialized = true; } /** * @notice Allows the owner to progress the phases of the ICO if contract has been initialized * @dev The phases cannot be progressed past open phase, nor can they be reversed once moved * forward */ function progressPhases() external onlyOwner hasBeenInitialized { require(currentPhase != Phases.OPEN, "ICO: phases complete"); currentPhase = Phases(uint256(currentPhase) + 1); emit NewPhase(currentPhase); } /** * @notice Allows the owner to pause/unpause the ICO */ function toggleIsPaused() external onlyOwner { isPaused = !isPaused; } /** * @notice Allows the owner to toggle on/off if another address is a seed investor * @param _seedInvestor The address to toggle on/off */ function toggleSeedInvestor(address _seedInvestor) external onlyOwner { approvedSeedInvestors[_seedInvestor] = !approvedSeedInvestors[ _seedInvestor ]; } /** * @notice Returns the excess amount of ether to return to a given address * @param _messageValue The msg.value that the address sent */ function _getExcessEtherToReturn(uint256 _messageValue) private view hasBeenInitialized canContributeForCurrentPhase returns (uint256) { uint256 addressContributions = addressToContributions[msg.sender]; uint256 newAddressContributions = addressContributions + _messageValue; uint256 newTotalContributions = totalContributions + _messageValue; if ( currentPhase == Phases.SEED && newAddressContributions > SEED_CONTRIBUTIONS_PER_ADDRESS ) { return newAddressContributions - SEED_CONTRIBUTIONS_PER_ADDRESS; } else if ( currentPhase == Phases.SEED && newTotalContributions > SEED_CONTRIBUTIONS_CAP ) { return newTotalContributions - SEED_CONTRIBUTIONS_CAP; } else if ( currentPhase == Phases.GENERAL && newAddressContributions > GENERAL_CONTRIBUTIONS_PER_ADDRESS ) { return newAddressContributions - GENERAL_CONTRIBUTIONS_PER_ADDRESS; } else if ( currentPhase == Phases.GENERAL && newTotalContributions > GENERAL_CONTRIBUTIONS_CAP ) { return newTotalContributions - GENERAL_CONTRIBUTIONS_CAP; } return 0; } /** * @dev This method has been specifically disallowed in favor of the buyTokens function */ receive() external payable { revert("ICO: use buyTokens function"); } }
Allows the owner to progress the phases of the ICO if contract has been initialized The phases cannot be progressed past open phase, nor can they be reversed once moved forward/
function progressPhases() external onlyOwner hasBeenInitialized { require(currentPhase != Phases.OPEN, "ICO: phases complete"); currentPhase = Phases(uint256(currentPhase) + 1); emit NewPhase(currentPhase); }
1,816,527
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "../interfaces/INormalDistribution.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title NormalDistribution * @author Pods Finance * @notice Calculates the Cumulative Distribution Function of * the standard normal distribution */ contract NormalDistribution is INormalDistribution, Ownable { using SafeMath for uint256; mapping(uint256 => uint256) private _probabilities; event DataPointSet(uint256 key, uint256 value); constructor() public { _probabilities[0] = 50000; _probabilities[100] = 50399; _probabilities[200] = 50798; _probabilities[300] = 51197; _probabilities[400] = 51595; _probabilities[500] = 51994; _probabilities[600] = 52392; _probabilities[700] = 52790; _probabilities[800] = 53188; _probabilities[900] = 53586; _probabilities[1000] = 53983; _probabilities[1100] = 54380; _probabilities[1200] = 54776; _probabilities[1300] = 55172; _probabilities[1400] = 55567; _probabilities[1500] = 55962; _probabilities[1600] = 56356; _probabilities[1700] = 56749; _probabilities[1800] = 57142; _probabilities[1900] = 57535; _probabilities[2000] = 57926; _probabilities[2100] = 58317; _probabilities[2200] = 58706; _probabilities[2300] = 59095; _probabilities[2400] = 59483; _probabilities[2500] = 59871; _probabilities[2600] = 60257; _probabilities[2700] = 60642; _probabilities[2800] = 61026; _probabilities[2900] = 61409; _probabilities[3000] = 61791; _probabilities[3100] = 62172; _probabilities[3200] = 62552; _probabilities[3300] = 62930; _probabilities[3400] = 63307; _probabilities[3500] = 63683; _probabilities[3600] = 64058; _probabilities[3700] = 64431; _probabilities[3800] = 64803; _probabilities[3900] = 65173; _probabilities[4000] = 65542; _probabilities[4100] = 65910; _probabilities[4200] = 66276; _probabilities[4300] = 66640; _probabilities[4400] = 67003; _probabilities[4500] = 67364; _probabilities[4600] = 67724; _probabilities[4700] = 68082; _probabilities[4800] = 68439; _probabilities[4900] = 68793; _probabilities[5000] = 69146; _probabilities[5100] = 69497; _probabilities[5200] = 69847; _probabilities[5300] = 70194; _probabilities[5400] = 70540; _probabilities[5500] = 70884; _probabilities[5600] = 71226; _probabilities[5700] = 71566; _probabilities[5800] = 71904; _probabilities[5900] = 72240; _probabilities[6000] = 72575; _probabilities[6100] = 72907; _probabilities[6200] = 73237; _probabilities[6300] = 73565; _probabilities[6400] = 73891; _probabilities[6500] = 74215; _probabilities[6600] = 74537; _probabilities[6700] = 74857; _probabilities[6800] = 75175; _probabilities[6900] = 75490; _probabilities[7000] = 75804; _probabilities[7100] = 76115; _probabilities[7200] = 76424; _probabilities[7300] = 76730; _probabilities[7400] = 77035; _probabilities[7500] = 77337; _probabilities[7600] = 77637; _probabilities[7700] = 77935; _probabilities[7800] = 78230; _probabilities[7900] = 78524; _probabilities[8000] = 78814; _probabilities[8100] = 79103; _probabilities[8200] = 79389; _probabilities[8300] = 79673; _probabilities[8400] = 79955; _probabilities[8500] = 80234; _probabilities[8600] = 80511; _probabilities[8700] = 80785; _probabilities[8800] = 81057; _probabilities[8900] = 81327; _probabilities[9000] = 81594; _probabilities[9100] = 81859; _probabilities[9200] = 82121; _probabilities[9300] = 82381; _probabilities[9400] = 82639; _probabilities[9500] = 82894; _probabilities[9600] = 83147; _probabilities[9700] = 83398; _probabilities[9800] = 83646; _probabilities[9900] = 83891; _probabilities[10000] = 84134; _probabilities[10100] = 84375; _probabilities[10200] = 84614; _probabilities[10300] = 84849; _probabilities[10400] = 85083; _probabilities[10500] = 85314; _probabilities[10600] = 85543; _probabilities[10700] = 85769; _probabilities[10800] = 85993; _probabilities[10900] = 86214; _probabilities[11000] = 86433; _probabilities[11100] = 86650; _probabilities[11200] = 86864; _probabilities[11300] = 87076; _probabilities[11400] = 87286; _probabilities[11500] = 87493; _probabilities[11600] = 87698; _probabilities[11700] = 87900; _probabilities[11800] = 88100; _probabilities[11900] = 88298; _probabilities[12000] = 88493; _probabilities[12100] = 88686; _probabilities[12200] = 88877; _probabilities[12300] = 89065; _probabilities[12400] = 89251; _probabilities[12500] = 89435; _probabilities[12600] = 89617; _probabilities[12700] = 89796; _probabilities[12800] = 89973; _probabilities[12900] = 90147; _probabilities[13000] = 90320; _probabilities[13100] = 90490; _probabilities[13200] = 90658; _probabilities[13300] = 90824; _probabilities[13400] = 90988; _probabilities[13500] = 91149; _probabilities[13600] = 91309; _probabilities[13700] = 91466; _probabilities[13800] = 91621; _probabilities[13900] = 91774; _probabilities[14000] = 91924; _probabilities[14100] = 92073; _probabilities[14200] = 92220; _probabilities[14300] = 92364; _probabilities[14400] = 92507; _probabilities[14500] = 92647; _probabilities[14600] = 92785; _probabilities[14700] = 92922; _probabilities[14800] = 93056; _probabilities[14900] = 93189; _probabilities[15000] = 93319; _probabilities[15100] = 93448; _probabilities[15200] = 93574; _probabilities[15300] = 93699; _probabilities[15400] = 93822; _probabilities[15500] = 93943; _probabilities[15600] = 94062; _probabilities[15700] = 94179; _probabilities[15800] = 94295; _probabilities[15900] = 94408; _probabilities[16000] = 94520; _probabilities[16100] = 94630; _probabilities[16200] = 94738; _probabilities[16300] = 94845; _probabilities[16400] = 94950; _probabilities[16500] = 95053; _probabilities[16600] = 95154; _probabilities[16700] = 95254; _probabilities[16800] = 95352; _probabilities[16900] = 95449; _probabilities[17000] = 95543; _probabilities[17100] = 95637; _probabilities[17200] = 95728; _probabilities[17300] = 95818; _probabilities[17400] = 95907; _probabilities[17500] = 95994; _probabilities[17600] = 96080; _probabilities[17700] = 96164; _probabilities[17800] = 96246; _probabilities[17900] = 96327; _probabilities[18000] = 96407; _probabilities[18100] = 96485; _probabilities[18200] = 96562; _probabilities[18300] = 96638; _probabilities[18400] = 96712; _probabilities[18500] = 96784; _probabilities[18600] = 96856; _probabilities[18700] = 96926; _probabilities[18800] = 96995; _probabilities[18900] = 97062; _probabilities[19000] = 97128; _probabilities[19100] = 97193; _probabilities[19200] = 97257; _probabilities[19300] = 97320; _probabilities[19400] = 97381; _probabilities[19500] = 97441; _probabilities[19600] = 97500; _probabilities[19700] = 97558; _probabilities[19800] = 97615; _probabilities[19900] = 97670; _probabilities[20000] = 97725; _probabilities[20100] = 97778; _probabilities[20200] = 97831; _probabilities[20300] = 97882; _probabilities[20400] = 97932; _probabilities[20500] = 97982; _probabilities[20600] = 98030; _probabilities[20700] = 98077; _probabilities[20800] = 98124; _probabilities[20900] = 98169; _probabilities[21000] = 98214; _probabilities[21100] = 98257; _probabilities[21200] = 98300; _probabilities[21300] = 98341; _probabilities[21400] = 98382; _probabilities[21500] = 98422; _probabilities[21600] = 98461; _probabilities[21700] = 98500; _probabilities[21800] = 98537; _probabilities[21900] = 98574; _probabilities[22000] = 98610; _probabilities[22100] = 98645; _probabilities[22200] = 98679; _probabilities[22300] = 98713; _probabilities[22400] = 98745; _probabilities[22500] = 98778; _probabilities[22600] = 98809; _probabilities[22700] = 98840; _probabilities[22800] = 98870; _probabilities[22900] = 98899; _probabilities[23000] = 98928; _probabilities[23100] = 98956; _probabilities[23200] = 98983; _probabilities[23300] = 99010; _probabilities[23400] = 99036; _probabilities[23500] = 99061; _probabilities[23600] = 99086; _probabilities[23700] = 99111; _probabilities[23800] = 99134; _probabilities[23900] = 99158; _probabilities[24000] = 99180; _probabilities[24100] = 99202; _probabilities[24200] = 99224; _probabilities[24300] = 99245; _probabilities[24400] = 99266; _probabilities[24500] = 99286; _probabilities[24600] = 99305; _probabilities[24700] = 99324; _probabilities[24800] = 99343; _probabilities[24900] = 99361; _probabilities[25000] = 99379; _probabilities[25100] = 99396; _probabilities[25200] = 99413; _probabilities[25300] = 99430; _probabilities[25400] = 99446; _probabilities[25500] = 99461; _probabilities[25600] = 99477; _probabilities[25700] = 99492; _probabilities[25800] = 99506; _probabilities[25900] = 99520; _probabilities[26000] = 99534; _probabilities[26100] = 99547; _probabilities[26200] = 99560; _probabilities[26300] = 99573; _probabilities[26400] = 99585; _probabilities[26500] = 99598; _probabilities[26600] = 99609; _probabilities[26700] = 99621; _probabilities[26800] = 99632; _probabilities[26900] = 99643; _probabilities[27000] = 99653; _probabilities[27100] = 99664; _probabilities[27200] = 99674; _probabilities[27300] = 99683; _probabilities[27400] = 99693; _probabilities[27500] = 99702; _probabilities[27600] = 99711; _probabilities[27700] = 99720; _probabilities[27800] = 99728; _probabilities[27900] = 99736; _probabilities[28000] = 99744; _probabilities[28100] = 99752; _probabilities[28200] = 99760; _probabilities[28300] = 99767; _probabilities[28400] = 99774; _probabilities[28500] = 99781; _probabilities[28600] = 99788; _probabilities[28700] = 99795; _probabilities[28800] = 99801; _probabilities[28900] = 99807; _probabilities[29000] = 99813; _probabilities[29100] = 99819; _probabilities[29200] = 99825; _probabilities[29300] = 99831; _probabilities[29400] = 99836; _probabilities[29500] = 99841; _probabilities[29600] = 99846; _probabilities[29700] = 99851; _probabilities[29800] = 99856; _probabilities[29900] = 99861; _probabilities[30000] = 99865; _probabilities[30100] = 99869; _probabilities[30200] = 99874; _probabilities[30300] = 99878; _probabilities[30400] = 99882; _probabilities[30500] = 99886; _probabilities[30600] = 99889; _probabilities[30700] = 99893; _probabilities[30800] = 99896; _probabilities[30900] = 99900; _probabilities[31000] = 99903; _probabilities[31100] = 99906; _probabilities[31200] = 99910; _probabilities[31300] = 99913; _probabilities[31400] = 99916; _probabilities[31500] = 99918; _probabilities[31600] = 99921; _probabilities[31700] = 99924; _probabilities[31800] = 99926; _probabilities[31900] = 99929; _probabilities[32000] = 99931; _probabilities[32100] = 99934; _probabilities[32200] = 99936; _probabilities[32300] = 99938; _probabilities[32400] = 99940; _probabilities[32500] = 99942; _probabilities[32600] = 99944; _probabilities[32700] = 99946; _probabilities[32800] = 99948; _probabilities[32900] = 99950; _probabilities[33000] = 99952; _probabilities[33100] = 99953; _probabilities[33200] = 99955; _probabilities[33300] = 99957; _probabilities[33400] = 99958; _probabilities[33500] = 99960; _probabilities[33600] = 99961; _probabilities[33700] = 99962; _probabilities[33800] = 99964; _probabilities[33900] = 99965; _probabilities[34000] = 99966; _probabilities[34100] = 99968; _probabilities[34200] = 99969; _probabilities[34300] = 99970; _probabilities[34400] = 99971; _probabilities[34500] = 99972; _probabilities[34600] = 99973; _probabilities[34700] = 99974; _probabilities[34800] = 99975; _probabilities[34900] = 99976; _probabilities[35000] = 99977; _probabilities[35100] = 99978; _probabilities[35200] = 99978; _probabilities[35300] = 99979; _probabilities[35400] = 99980; _probabilities[35500] = 99981; _probabilities[35600] = 99981; _probabilities[35700] = 99982; _probabilities[35800] = 99983; _probabilities[35900] = 99983; _probabilities[36000] = 99984; _probabilities[36100] = 99985; _probabilities[36200] = 99985; _probabilities[36300] = 99986; _probabilities[36400] = 99986; _probabilities[36500] = 99987; _probabilities[36600] = 99987; _probabilities[36700] = 99988; _probabilities[36800] = 99988; _probabilities[36900] = 99989; _probabilities[37000] = 99989; _probabilities[37100] = 99990; _probabilities[37200] = 99990; _probabilities[37300] = 99990; _probabilities[37400] = 99991; _probabilities[37500] = 99991; _probabilities[37600] = 99992; _probabilities[37700] = 99992; _probabilities[37800] = 99992; _probabilities[37900] = 99992; _probabilities[38000] = 99993; _probabilities[38100] = 99993; _probabilities[38200] = 99993; _probabilities[38300] = 99994; _probabilities[38400] = 99994; _probabilities[38500] = 99994; _probabilities[38600] = 99994; _probabilities[38700] = 99995; _probabilities[38800] = 99995; _probabilities[38900] = 99995; _probabilities[39000] = 99995; _probabilities[39100] = 99995; _probabilities[39200] = 99996; _probabilities[39300] = 99996; _probabilities[39400] = 99996; _probabilities[39500] = 99996; _probabilities[39600] = 99996; _probabilities[39700] = 99996; _probabilities[39800] = 99997; _probabilities[39900] = 99997; _probabilities[40000] = 99997; } /** * @notice Returns the probability of Z in a normal distribution curve * @dev For performance numbers are truncated to 2 decimals. Ex: 1134500000000000000(1.13) gets truncated to 113 * @dev For Z > ±0.307 the curve response gets more concentrated * @param z A point in the normal distribution * @param decimals Amount of decimals of z * @return The probability of a z variable in a normal distribution */ function getProbability(int256 z, uint256 decimals) external override view returns (uint256) { require(decimals >= 5 && decimals < 77, "NormalDistribution: invalid decimals"); uint256 absZ = _abs(z); uint256 truncatedZ = absZ.div(10**(decimals.sub(2))).mul(100); uint256 fourthDigit = _abs(z).div(10**(decimals.sub(3))) - _abs(z).div(10**(decimals.sub(2))).mul(10); uint256 responseDecimals = 10**(decimals.sub(5)); uint256 responseValue; if (truncatedZ >= 41900) { responseValue = 99999; } else if (truncatedZ >= 41100) { responseValue = 99998; } else if (truncatedZ >= 40100) { responseValue = 99997; } else if (fourthDigit >= 7) { // If the fourthDigit is 7, 8 or 9, rounds up to the next data point responseValue = _probabilities[truncatedZ + 100]; } else if (fourthDigit >= 4) { // If the fourthDigit is 4, 5 or 6, get the average between the current and the next responseValue = _probabilities[truncatedZ].add(_probabilities[truncatedZ + 100]).div(2); } else { // If the fourthDigit is 0, 1, 2 or 3, get the current responseValue = _probabilities[truncatedZ]; } // Handle negative z if (z < 0) { responseValue = uint256(100000).sub(responseValue); } return responseValue.mul(responseDecimals); } /** * @dev Defines a new probability point * @param key A point in the normal distribution * @param value The value */ function setDataPoint(uint256 key, uint256 value) external override onlyOwner { _probabilities[key] = value; emit DataPointSet(key, value); } /** * @dev Returns the module of a number. */ function _abs(int256 a) internal pure returns (uint256) { return a < 0 ? uint256(-a) : uint256(a); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface INormalDistribution { function getProbability(int256 z, uint256 decimals) external view returns (uint256); function setDataPoint(uint256 key, uint256 value) external; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.6.0; /** * @dev 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; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
Returns the probability of Z in a normal distribution curve For performance numbers are truncated to 2 decimals. Ex: 1134500000000000000(1.13) gets truncated to 113 For Z > ±0.307 the curve response gets more concentrated z A point in the normal distribution decimals Amount of decimals of z return The probability of a z variable in a normal distribution/ If the fourthDigit is 7, 8 or 9, rounds up to the next data point If the fourthDigit is 4, 5 or 6, get the average between the current and the next If the fourthDigit is 0, 1, 2 or 3, get the current Handle negative z
function getProbability(int256 z, uint256 decimals) external override view returns (uint256) { require(decimals >= 5 && decimals < 77, "NormalDistribution: invalid decimals"); uint256 absZ = _abs(z); uint256 truncatedZ = absZ.div(10**(decimals.sub(2))).mul(100); uint256 fourthDigit = _abs(z).div(10**(decimals.sub(3))) - _abs(z).div(10**(decimals.sub(2))).mul(10); uint256 responseDecimals = 10**(decimals.sub(5)); uint256 responseValue; if (truncatedZ >= 41900) { responseValue = 99999; responseValue = 99998; responseValue = 99997; responseValue = _probabilities[truncatedZ + 100]; responseValue = _probabilities[truncatedZ].add(_probabilities[truncatedZ + 100]).div(2); responseValue = _probabilities[truncatedZ]; } if (z < 0) { responseValue = uint256(100000).sub(responseValue); } return responseValue.mul(responseDecimals); }
574,903
./partial_match/82/0x1d5935d36D0E1d812c4ea6Af40c3D6eb361eeb07/sources/GnosisSafe.sol
Setup function sets initial storage of contract. _owners List of Safe owners. _threshold Number of required confirmations for a Safe transaction. Threshold can only be 0 at initialization. Check ensures that setup function can only be called once. Validate that threshold is smaller than number of added owners. There has to be at least one Safe owner. Initializing Safe owners. Owner address cannot be null. No duplicate owners allowed.
function setupOwners(address[] memory _owners, uint256 _threshold) internal { require(threshold == 0, 'Owners have already been setup'); require(_threshold <= _owners.length, 'Threshold cannot exceed owner count'); require(_threshold >= 1, 'Threshold needs to be greater than 0'); address currentOwner = SENTINEL_OWNERS; for (uint256 i = 0; i < _owners.length; i++) { address owner = _owners[i]; require( owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, 'Invalid owner address provided' ); require(owners[owner] == address(0), 'Duplicate owner address provided'); owners[currentOwner] = owner; currentOwner = owner; } owners[currentOwner] = SENTINEL_OWNERS; ownerCount = _owners.length; threshold = _threshold; }
16,902,067
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {IAaveDistributionManager} from '../interfaces/IAaveDistributionManager.sol'; import {SafeMath} from '../lib/SafeMath.sol'; import {DistributionTypes} from '../lib/DistributionTypes.sol'; /** * @title DistributionManager * @notice Accounting contract to manage multiple staking distributions * @author Aave **/ contract DistributionManager is IAaveDistributionManager { using SafeMath for uint256; struct AssetData { uint104 emissionPerSecond; uint104 index; uint40 lastUpdateTimestamp; mapping(address => uint256) users; } address public immutable EMISSION_MANAGER; uint8 public constant PRECISION = 18; mapping(address => AssetData) public assets; uint256 internal _distributionEnd; modifier onlyEmissionManager() { require(msg.sender == EMISSION_MANAGER, 'ONLY_EMISSION_MANAGER'); _; } constructor(address emissionManager) { EMISSION_MANAGER = emissionManager; } /// @inheritdoc IAaveDistributionManager function setDistributionEnd(uint256 distributionEnd) external override onlyEmissionManager { _distributionEnd = distributionEnd; emit DistributionEndUpdated(distributionEnd); } /// @inheritdoc IAaveDistributionManager function getDistributionEnd() external view override returns (uint256) { return _distributionEnd; } /// @inheritdoc IAaveDistributionManager function DISTRIBUTION_END() external view override returns (uint256) { return _distributionEnd; } /// @inheritdoc IAaveDistributionManager function getUserAssetData(address user, address asset) public view override returns (uint256) { return assets[asset].users[user]; } /// @inheritdoc IAaveDistributionManager function getAssetData(address asset) public view override returns (uint256, uint256, uint256) { return (assets[asset].index, assets[asset].emissionPerSecond, assets[asset].lastUpdateTimestamp); } /** * @dev Configure the assets for a specific emission * @param assetsConfigInput The array of each asset configuration **/ function _configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) internal { for (uint256 i = 0; i < assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset]; _updateAssetStateInternal( assetsConfigInput[i].underlyingAsset, assetConfig, assetsConfigInput[i].totalStaked ); assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond; emit AssetConfigUpdated( assetsConfigInput[i].underlyingAsset, assetsConfigInput[i].emissionPerSecond ); } } /** * @dev Updates the state of one distribution, mainly rewards index and timestamp * @param asset The address of the asset being updated * @param assetConfig Storage pointer to the distribution's config * @param totalStaked Current total of staked assets for this distribution * @return The new distribution index **/ function _updateAssetStateInternal( address asset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint256 emissionPerSecond = assetConfig.emissionPerSecond; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex(oldIndex, emissionPerSecond, lastUpdateTimestamp, totalStaked); if (newIndex != oldIndex) { require(uint104(newIndex) == newIndex, 'Index overflow'); //optimization: storing one after another saves one SSTORE assetConfig.index = uint104(newIndex); assetConfig.lastUpdateTimestamp = uint40(block.timestamp); emit AssetIndexUpdated(asset, newIndex); } else { assetConfig.lastUpdateTimestamp = uint40(block.timestamp); } return newIndex; } /** * @dev Updates the state of an user in a distribution * @param user The user's address * @param asset The address of the reference asset of the distribution * @param stakedByUser Amount of tokens staked by the user in the distribution at the moment * @param totalStaked Total tokens staked in the distribution * @return The accrued rewards for the user until the moment **/ function _updateUserAssetInternal( address user, address asset, uint256 stakedByUser, uint256 totalStaked ) internal returns (uint256) { AssetData storage assetData = assets[asset]; uint256 userIndex = assetData.users[user]; uint256 accruedRewards = 0; uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked); if (userIndex != newIndex) { if (stakedByUser != 0) { accruedRewards = _getRewards(stakedByUser, newIndex, userIndex); } assetData.users[user] = newIndex; emit UserIndexUpdated(user, asset, newIndex); } return accruedRewards; } /** * @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _claimRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { accruedRewards = accruedRewards.add( _updateUserAssetInternal( user, stakes[i].underlyingAsset, stakes[i].stakedByUser, stakes[i].totalStaked ) ); } return accruedRewards; } /** * @dev Return the accrued rewards for an user over a list of distribution * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal view returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { AssetData storage assetConfig = assets[stakes[i].underlyingAsset]; uint256 assetIndex = _getAssetIndex( assetConfig.index, assetConfig.emissionPerSecond, assetConfig.lastUpdateTimestamp, stakes[i].totalStaked ); accruedRewards = accruedRewards.add( _getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user]) ); } return accruedRewards; } /** * @dev Internal function for the calculation of user's rewards on a distribution * @param principalUserBalance Amount staked by the user on a distribution * @param reserveIndex Current index of the distribution * @param userIndex Index stored for the user, representation his staking moment * @return The rewards **/ function _getRewards( uint256 principalUserBalance, uint256 reserveIndex, uint256 userIndex ) internal pure returns (uint256) { return principalUserBalance.mul(reserveIndex.sub(userIndex)) / 10**uint256(PRECISION); } /** * @dev Calculates the next value of an specific distribution index, with validations * @param currentIndex Current index of the distribution * @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution * @param lastUpdateTimestamp Last moment this distribution was updated * @param totalBalance of tokens considered for the distribution * @return The new index. **/ function _getAssetIndex( uint256 currentIndex, uint256 emissionPerSecond, uint128 lastUpdateTimestamp, uint256 totalBalance ) internal view returns (uint256) { uint256 distributionEnd = _distributionEnd; if ( emissionPerSecond == 0 || totalBalance == 0 || lastUpdateTimestamp == block.timestamp || lastUpdateTimestamp >= distributionEnd ) { return currentIndex; } uint256 currentTimestamp = block.timestamp > distributionEnd ? distributionEnd : block.timestamp; uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp); return emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add( currentIndex ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {DistributionTypes} from '../lib/DistributionTypes.sol'; interface IAaveDistributionManager { event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated(address indexed user, address indexed asset, uint256 index); event DistributionEndUpdated(uint256 newDistributionEnd); /** * @dev Sets the end date for the distribution * @param distributionEnd The end date timestamp **/ function setDistributionEnd(uint256 distributionEnd) external; /** * @dev Gets the end date for the distribution * @return The end of the distribution **/ function getDistributionEnd() external view returns (uint256); /** * @dev for backwards compatibility with the previous DistributionManager used * @return The end of the distribution **/ function DISTRIBUTION_END() external view returns(uint256); /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) external view returns (uint256); /** * @dev Returns the configuration of the distribution for a certain asset * @param asset The address of the reference asset of the distribution * @return The asset index, the emission per second and the last updated timestamp **/ function getAssetData(address asset) external view returns (uint256, uint256, uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.7.5; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost /// inspired by uniswap V3 library SafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } function div(uint256 x, uint256 y) internal pure returns(uint256) { // no need to check for division by zero - solidity already reverts return x / y; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; library DistributionTypes { struct AssetConfigInput { uint104 emissionPerSecond; uint256 totalStaked; address underlyingAsset; } struct UserStakeInput { address underlyingAsset; uint256 stakedByUser; uint256 totalStaked; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {SafeERC20} from '@aave/aave-stake/contracts/lib/SafeERC20.sol'; import {SafeMath} from '../lib/SafeMath.sol'; import {DistributionTypes} from '../lib/DistributionTypes.sol'; import {VersionedInitializable} from '@aave/aave-stake/contracts/utils/VersionedInitializable.sol'; import {DistributionManager} from './DistributionManager.sol'; import {IStakedTokenWithConfig} from '../interfaces/IStakedTokenWithConfig.sol'; import {IERC20} from '@aave/aave-stake/contracts/interfaces/IERC20.sol'; import {IScaledBalanceToken} from '../interfaces/IScaledBalanceToken.sol'; import {IAaveIncentivesController} from '../interfaces/IAaveIncentivesController.sol'; /** * @title StakedTokenIncentivesController * @notice Distributor contract for rewards to the Aave protocol, using a staked token as rewards asset. * The contract stakes the rewards before redistributing them to the Aave protocol participants. * The reference staked token implementation is at https://github.com/aave/aave-stake-v2 * @author Aave **/ contract StakedTokenIncentivesController is IAaveIncentivesController, VersionedInitializable, DistributionManager { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant REVISION = 2; IStakedTokenWithConfig public immutable STAKE_TOKEN; mapping(address => uint256) internal _usersUnclaimedRewards; // this mapping allows whitelisted addresses to claim on behalf of others // useful for contracts that hold tokens to be rewarded but don't have any native logic to claim Liquidity Mining rewards mapping(address => address) internal _authorizedClaimers; modifier onlyAuthorizedClaimers(address claimer, address user) { require(_authorizedClaimers[user] == claimer, 'CLAIMER_UNAUTHORIZED'); _; } constructor(IStakedTokenWithConfig stakeToken, address emissionManager) DistributionManager(emissionManager) { STAKE_TOKEN = stakeToken; } /** * @dev Initialize IStakedTokenIncentivesController. Empty after REVISION 1, but maintains the expected interface. **/ function initialize(address) external initializer {} /// @inheritdoc IAaveIncentivesController function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond) external override onlyEmissionManager { require(assets.length == emissionsPerSecond.length, 'INVALID_CONFIGURATION'); DistributionTypes.AssetConfigInput[] memory assetsConfig = new DistributionTypes.AssetConfigInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { assetsConfig[i].underlyingAsset = assets[i]; assetsConfig[i].emissionPerSecond = uint104(emissionsPerSecond[i]); require(assetsConfig[i].emissionPerSecond == emissionsPerSecond[i], 'INVALID_CONFIGURATION'); assetsConfig[i].totalStaked = IScaledBalanceToken(assets[i]).scaledTotalSupply(); } _configureAssets(assetsConfig); } /// @inheritdoc IAaveIncentivesController function handleAction( address user, uint256 totalSupply, uint256 userBalance ) external override { uint256 accruedRewards = _updateUserAssetInternal(user, msg.sender, userBalance, totalSupply); if (accruedRewards != 0) { _usersUnclaimedRewards[user] = _usersUnclaimedRewards[user].add(accruedRewards); emit RewardsAccrued(user, accruedRewards); } } /// @inheritdoc IAaveIncentivesController function getRewardsBalance(address[] calldata assets, address user) external view override returns (uint256) { uint256 unclaimedRewards = _usersUnclaimedRewards[user]; DistributionTypes.UserStakeInput[] memory userState = new DistributionTypes.UserStakeInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userState[i].underlyingAsset = assets[i]; (userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i]) .getScaledUserBalanceAndSupply(user); } unclaimedRewards = unclaimedRewards.add(_getUnclaimedRewards(user, userState)); return unclaimedRewards; } /// @inheritdoc IAaveIncentivesController function claimRewards( address[] calldata assets, uint256 amount, address to ) external override returns (uint256) { require(to != address(0), 'INVALID_TO_ADDRESS'); return _claimRewards(assets, amount, msg.sender, msg.sender, to); } /// @inheritdoc IAaveIncentivesController function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external override onlyAuthorizedClaimers(msg.sender, user) returns (uint256) { require(user != address(0), 'INVALID_USER_ADDRESS'); require(to != address(0), 'INVALID_TO_ADDRESS'); return _claimRewards(assets, amount, msg.sender, user, to); } /// @inheritdoc IAaveIncentivesController function claimRewardsToSelf(address[] calldata assets, uint256 amount) external override returns (uint256) { return _claimRewards(assets, amount, msg.sender, msg.sender, msg.sender); } /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ /// @inheritdoc IAaveIncentivesController function setClaimer(address user, address caller) external override onlyEmissionManager { _authorizedClaimers[user] = caller; emit ClaimerSet(user, caller); } /// @inheritdoc IAaveIncentivesController function getClaimer(address user) external view override returns (address) { return _authorizedClaimers[user]; } /// @inheritdoc IAaveIncentivesController function getUserUnclaimedRewards(address _user) external view override returns (uint256) { return _usersUnclaimedRewards[_user]; } /// @inheritdoc IAaveIncentivesController function REWARD_TOKEN() external view override returns (address) { return address(STAKE_TOKEN); } /** * @dev returns the revision of the implementation contract */ function getRevision() internal pure override returns (uint256) { return REVISION; } /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function _claimRewards( address[] calldata assets, uint256 amount, address claimer, address user, address to ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 unclaimedRewards = _usersUnclaimedRewards[user]; DistributionTypes.UserStakeInput[] memory userState = new DistributionTypes.UserStakeInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userState[i].underlyingAsset = assets[i]; (userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i]) .getScaledUserBalanceAndSupply(user); } uint256 accruedRewards = _claimRewards(user, userState); if (accruedRewards != 0) { unclaimedRewards = unclaimedRewards.add(accruedRewards); emit RewardsAccrued(user, accruedRewards); } if (unclaimedRewards == 0) { return 0; } uint256 amountToClaim = amount > unclaimedRewards ? unclaimedRewards : amount; _usersUnclaimedRewards[user] = unclaimedRewards - amountToClaim; // Safe due to the previous line STAKE_TOKEN.stake(to, amountToClaim); emit RewardsClaimed(user, to, claimer, amountToClaim); return amountToClaim; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import {IERC20} from '../interfaces/IERC20.sol'; import {SafeMath} from './SafeMath.sol'; import {Address} from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * 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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { 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 callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * * @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. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, 'Contract instance has already been initialized'); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns (uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import {IStakedToken} from '@aave/aave-stake/contracts/interfaces/IStakedToken.sol'; interface IStakedTokenWithConfig is IStakedToken { function STAKED_TOKEN() external view returns(address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Interface of the ERC20 standard as defined in the EIP. * From https://github.com/OpenZeppelin/openzeppelin-contracts */ 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: agpl-3.0 pragma solidity 0.7.5; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {IAaveDistributionManager} from '../interfaces/IAaveDistributionManager.sol'; interface IAaveIncentivesController is IAaveDistributionManager { event RewardsAccrued(address indexed user, uint256 amount); event RewardsClaimed( address indexed user, address indexed to, address indexed claimer, uint256 amount ); event ClaimerSet(address indexed user, address indexed claimer); /** * @dev Whitelists an address to claim the rewards on behalf of another address * @param user The address of the user * @param claimer The address of the claimer */ function setClaimer(address user, address claimer) external; /** * @dev Returns the whitelisted claimer for a certain address (0x0 if not set) * @param user The address of the user * @return The claimer address */ function getClaimer(address user) external view returns (address); /** * @dev Configure assets for a certain rewards emission * @param assets The assets to incentivize * @param emissionsPerSecond The emission for each asset */ function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond) external; /** * @dev Called by the corresponding asset on any update that affects the rewards distribution * @param asset The address of the user * @param userBalance The balance of the user of the asset in the lending pool * @param totalSupply The total supply of the asset in the lending pool **/ function handleAction( address asset, uint256 userBalance, uint256 totalSupply ) external; /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev Claims rewards for a user, on the specified assets of the lending pool, distributing the pending rewards to self * @param assets Incentivized assets on which to claim rewards * @param amount Amount of rewards to claim * @return Rewards claimed **/ function claimRewardsToSelf(address[] calldata assets, uint256 amount) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; /** * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type * From https://github.com/OpenZeppelin/openzeppelin-contracts */ 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'); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface IStakedToken { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import {IERC20} from '@aave/aave-stake/contracts/interfaces/IERC20.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPoolConfigurator} from '../interfaces/ILendingPoolConfigurator.sol'; import {IAaveIncentivesController} from '../interfaces/IAaveIncentivesController.sol'; import {IAaveEcosystemReserveController} from '../interfaces/IAaveEcosystemReserveController.sol'; import {IProposalIncentivesExecutor} from '../interfaces/IProposalIncentivesExecutor.sol'; import {DistributionTypes} from '../lib/DistributionTypes.sol'; import {DataTypes} from '../utils/DataTypes.sol'; import {ILendingPoolData} from '../interfaces/ILendingPoolData.sol'; import {IATokenDetailed} from '../interfaces/IATokenDetailed.sol'; import {PercentageMath} from '../utils/PercentageMath.sol'; import {SafeMath} from '../lib/SafeMath.sol'; contract ProposalIncentivesExecutor is IProposalIncentivesExecutor { using SafeMath for uint256; using PercentageMath for uint256; address constant AAVE_TOKEN = 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9; address constant POOL_CONFIGURATOR = 0x311Bb771e4F8952E6Da169b425E7e92d6Ac45756; address constant ADDRESSES_PROVIDER = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5; address constant LENDING_POOL = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9; address constant ECO_RESERVE_ADDRESS = 0x1E506cbb6721B83B1549fa1558332381Ffa61A93; address constant INCENTIVES_CONTROLLER_PROXY_ADDRESS = 0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5; address constant INCENTIVES_CONTROLLER_IMPL_ADDRESS = 0x83D055D382f25e6793099713505c68a5C7535a35; uint256 constant DISTRIBUTION_DURATION = 7776000; // 90 days uint256 constant DISTRIBUTION_AMOUNT = 198000000000000000000000; // 198000 AAVE during 90 days function execute( address[6] memory aTokenImplementations, address[6] memory variableDebtImplementations ) external override { uint256 tokensCounter; address[] memory assets = new address[](12); // Reserves Order: DAI/GUSD/USDC/USDT/WBTC/WETH address payable[6] memory reserves = [ 0x6B175474E89094C44Da98b954EedeAC495271d0F, 0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd, 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 0xdAC17F958D2ee523a2206206994597C13D831ec7, 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ]; uint256[] memory emissions = new uint256[](12); emissions[0] = 1706018518518520; //aDAI emissions[1] = 1706018518518520; //vDebtDAI emissions[2] = 92939814814815; //aGUSD emissions[3] = 92939814814815; //vDebtGUSD emissions[4] = 5291203703703700; //aUSDC emissions[5] = 5291203703703700; //vDebtUSDC emissions[6] = 3293634259259260; //aUSDT emissions[7] = 3293634259259260; //vDebtUSDT emissions[8] = 1995659722222220; //aWBTC emissions[9] = 105034722222222; //vDebtWBTC emissions[10] = 2464942129629630; //aETH emissions[11] = 129733796296296; //vDebtWETH ILendingPoolConfigurator poolConfigurator = ILendingPoolConfigurator(POOL_CONFIGURATOR); IAaveIncentivesController incentivesController = IAaveIncentivesController(INCENTIVES_CONTROLLER_PROXY_ADDRESS); IAaveEcosystemReserveController ecosystemReserveController = IAaveEcosystemReserveController(ECO_RESERVE_ADDRESS); ILendingPoolAddressesProvider provider = ILendingPoolAddressesProvider(ADDRESSES_PROVIDER); //adding the incentives controller proxy to the addresses provider provider.setAddress(keccak256('INCENTIVES_CONTROLLER'), INCENTIVES_CONTROLLER_PROXY_ADDRESS); //updating the implementation of the incentives controller proxy provider.setAddressAsProxy(keccak256('INCENTIVES_CONTROLLER'), INCENTIVES_CONTROLLER_IMPL_ADDRESS); require( aTokenImplementations.length == variableDebtImplementations.length && aTokenImplementations.length == reserves.length, 'ARRAY_LENGTH_MISMATCH' ); // Update each reserve AToken implementation, Debt implementation, and prepare incentives configuration input for (uint256 x = 0; x < reserves.length; x++) { require( IATokenDetailed(aTokenImplementations[x]).UNDERLYING_ASSET_ADDRESS() == reserves[x], 'AToken underlying does not match' ); require( IATokenDetailed(variableDebtImplementations[x]).UNDERLYING_ASSET_ADDRESS() == reserves[x], 'Debt Token underlying does not match' ); DataTypes.ReserveData memory reserveData = ILendingPoolData(LENDING_POOL).getReserveData(reserves[x]); // Update aToken impl poolConfigurator.updateAToken(reserves[x], aTokenImplementations[x]); // Update variable debt impl poolConfigurator.updateVariableDebtToken(reserves[x], variableDebtImplementations[x]); assets[tokensCounter++] = reserveData.aTokenAddress; // Configure variable debt token at incentives controller assets[tokensCounter++] = reserveData.variableDebtTokenAddress; } // Transfer AAVE funds to the Incentives Controller ecosystemReserveController.transfer( AAVE_TOKEN, INCENTIVES_CONTROLLER_PROXY_ADDRESS, DISTRIBUTION_AMOUNT ); // Enable incentives in aTokens and Variable Debt tokens incentivesController.configureAssets(assets, emissions); // Sets the end date for the distribution incentivesController.setDistributionEnd(block.timestamp + DISTRIBUTION_DURATION); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface ILendingPoolConfigurator { function updateAToken(address reserve, address implementation) external; function updateVariableDebtToken(address reserve, address implementation) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface IAaveEcosystemReserveController { function AAVE_RESERVE_ECOSYSTEM() external view returns (address); function approve( address token, address recipient, uint256 amount ) external; function owner() external view returns (address); function renounceOwnership() external; function transfer( address token, address recipient, uint256 amount ) external; function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; interface IProposalIncentivesExecutor { function execute( address[6] memory aTokenImplementations, address[6] memory variableDebtImplementation ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma abicoder v2; import {DataTypes} from '../utils/DataTypes.sol'; interface ILendingPoolData { /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface IATokenDetailed { function UNDERLYING_ASSET_ADDRESS() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, 'MATH_MULTIPLICATION_OVERFLOW' ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, 'MATH_DIVISION_BY_ZERO'); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, 'MATH_MULTIPLICATION_OVERFLOW' ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {IAaveIncentivesController} from '../interfaces/IAaveIncentivesController.sol'; import {DistributionTypes} from '../lib/DistributionTypes.sol'; import {IAToken} from '@aave/aave-stake/contracts/interfaces/IAToken.sol'; contract ATokenMock is IAToken { IAaveIncentivesController public _aic; uint256 internal _userBalance; uint256 internal _totalSupply; // hack to be able to test event from EI properly event RewardsAccrued(address indexed user, uint256 amount); // hack to be able to test event from Distribution manager properly event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated(address indexed user, address indexed asset, uint256 index); constructor(IAaveIncentivesController aic) public { _aic = aic; } function handleActionOnAic( address user, uint256 totalSupply, uint256 userBalance ) external { _aic.handleAction(user, totalSupply, userBalance); } function doubleHandleActionOnAic( address user, uint256 totalSupply, uint256 userBalance ) external { _aic.handleAction(user, totalSupply, userBalance); _aic.handleAction(user, totalSupply, userBalance); } function setUserBalanceAndSupply(uint256 userBalance, uint256 totalSupply) public { _userBalance = userBalance; _totalSupply = totalSupply; } function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (_userBalance, _totalSupply); } function scaledTotalSupply() external view returns (uint256) { return _totalSupply; } function cleanUserState() external { _userBalance = 0; _totalSupply = 0; } } pragma solidity ^0.7.5; interface IAToken { function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; import {IERC20} from './IERC20.sol'; /** * @dev Interface for ERC20 including metadata **/ interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; import {Context} from './Context.sol'; import {IERC20} from '../interfaces/IERC20.sol'; import {IERC20Detailed} from '../interfaces/IERC20Detailed.sol'; import {SafeMath} from './SafeMath.sol'; /** * @title ERC20 * @notice Basic ERC20 implementation * @author Aave **/ contract ERC20 is Context, IERC20, IERC20Detailed { 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; constructor( string memory name, string memory symbol, uint8 decimals ) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token **/ function name() public view override returns (string memory) { return _name; } /** * @return the symbol of the token **/ function symbol() public view override returns (string memory) { return _symbol; } /** * @return the decimals of the token **/ function decimals() public view override returns (uint8) { return _decimals; } /** * @return the total supply of the token **/ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @return the balance of the token **/ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev executes a transfer of tokens from msg.sender to recipient * @param recipient the recipient of the tokens * @param amount the amount of tokens being transferred * @return true if the transfer succeeds, false otherwise **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev returns the allowance of spender on the tokens owned by owner * @param owner the owner of the tokens * @param spender the user allowed to spend the owner's tokens * @return the amount of owner's tokens spender is allowed to spend **/ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev allows spender to spend the tokens owned by msg.sender * @param spender the user allowed to spend msg.sender tokens * @return true **/ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev executes a transfer of token from sender to recipient, if msg.sender is allowed to do so * @param sender the owner of the tokens * @param recipient the recipient of the tokens * @param amount the amount of tokens being transferred * @return true if the transfer succeeds, false otherwise **/ 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 increases the allowance of spender to spend msg.sender tokens * @param spender the user allowed to spend on behalf of msg.sender * @param addedValue the amount being added to the allowance * @return true **/ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev decreases the allowance of spender to spend msg.sender tokens * @param spender the user allowed to spend on behalf of msg.sender * @param subtractedValue the amount being subtracted to the allowance * @return true **/ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } function _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); } 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); } 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); } 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); } function _setName(string memory newName) internal { _name = newName; } function _setSymbol(string memory newSymbol) internal { _symbol = newSymbol; } function _setDecimals(uint8 newDecimals) internal { _decimals = newDecimals; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * 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: agpl-3.0 pragma solidity 0.7.5; import {ERC20} from '../lib/ERC20.sol'; import {ITransferHook} from '../interfaces/ITransferHook.sol'; import {SafeMath} from '../lib/SafeMath.sol'; import { GovernancePowerDelegationERC20 } from '@aave/aave-token/contracts/token/base/GovernancePowerDelegationERC20.sol'; /** * @title ERC20WithSnapshot * @notice ERC20 including snapshots of balances on transfer-related actions * @author Aave **/ abstract contract GovernancePowerWithSnapshot is GovernancePowerDelegationERC20 { using SafeMath for uint256; /** * @dev The following storage layout points to the prior StakedToken.sol implementation: * _snapshots => _votingSnapshots * _snapshotsCounts => _votingSnapshotsCounts * _aaveGovernance => _aaveGovernance */ mapping(address => mapping(uint256 => Snapshot)) public _votingSnapshots; mapping(address => uint256) public _votingSnapshotsCounts; /// @dev reference to the Aave governance contract to call (if initialized) on _beforeTokenTransfer /// !!! IMPORTANT The Aave governance is considered a trustable contract, being its responsibility /// to control all potential reentrancies by calling back the this contract ITransferHook public _aaveGovernance; function _setAaveGovernance(ITransferHook aaveGovernance) internal virtual { _aaveGovernance = aaveGovernance; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface ITransferHook { function onTransfer( address from, address to, uint256 amount ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; import {SafeMath} from '../../open-zeppelin/SafeMath.sol'; import {ERC20} from '../../open-zeppelin/ERC20.sol'; import { IGovernancePowerDelegationToken } from '../../interfaces/IGovernancePowerDelegationToken.sol'; /** * @notice implementation of the AAVE token contract * @author Aave */ abstract contract GovernancePowerDelegationERC20 is ERC20, IGovernancePowerDelegationToken { using SafeMath for uint256; /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256( 'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)' ); bytes32 public constant DELEGATE_TYPEHASH = keccak256( 'Delegate(address delegatee,uint256 nonce,uint256 expiry)' ); /// @dev snapshot of a value on a specific block, used for votes struct Snapshot { uint128 blockNumber; uint128 value; } /** * @dev delegates one specific power to a delegatee * @param delegatee the user which delegated power has changed * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) **/ function delegateByType(address delegatee, DelegationType delegationType) external override { _delegateByType(msg.sender, delegatee, delegationType); } /** * @dev delegates all the powers to a specific user * @param delegatee the user to which the power will be delegated **/ function delegate(address delegatee) external override { _delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER); _delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER); } /** * @dev returns the delegatee of an user * @param delegator the address of the delegator **/ function getDelegateeByType(address delegator, DelegationType delegationType) external override view returns (address) { (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); return _getDelegatee(delegator, delegates); } /** * @dev returns the current delegated power of a user. The current power is the * power delegated at the time of the last snapshot * @param user the user **/ function getPowerCurrent(address user, DelegationType delegationType) external override view returns (uint256) { ( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, ) = _getDelegationDataByType(delegationType); return _searchByBlockNumber(snapshots, snapshotsCounts, user, block.number); } /** * @dev returns the delegated power of a user at a certain block * @param user the user **/ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external override view returns (uint256) { ( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, ) = _getDelegationDataByType(delegationType); return _searchByBlockNumber(snapshots, snapshotsCounts, user, blockNumber); } /** * @dev returns the total supply at a certain block number * used by the voting strategy contracts to calculate the total votes needed for threshold/quorum * In this initial implementation with no AAVE minting, simply returns the current supply * A snapshots mapping will need to be added in case a mint function is added to the AAVE token in the future **/ function totalSupplyAt(uint256 blockNumber) external override view returns (uint256) { return super.totalSupply(); } /** * @dev delegates the specific power to a delegatee * @param delegatee the user which delegated power has changed * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) **/ function _delegateByType( address delegator, address delegatee, DelegationType delegationType ) internal { require(delegatee != address(0), 'INVALID_DELEGATEE'); (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); uint256 delegatorBalance = balanceOf(delegator); address previousDelegatee = _getDelegatee(delegator, delegates); delegates[delegator] = delegatee; _moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType); emit DelegateChanged(delegator, delegatee, delegationType); } /** * @dev moves delegated power from one user to another * @param from the user from which delegated power is moved * @param to the user that will receive the delegated power * @param amount the amount of delegated power to be moved * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) **/ function _moveDelegatesByType( address from, address to, uint256 amount, DelegationType delegationType ) internal { if (from == to) { return; } ( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, ) = _getDelegationDataByType(delegationType); if (from != address(0)) { uint256 previous = 0; uint256 fromSnapshotsCount = snapshotsCounts[from]; if (fromSnapshotsCount != 0) { previous = snapshots[from][fromSnapshotsCount - 1].value; } else { previous = balanceOf(from); } _writeSnapshot( snapshots, snapshotsCounts, from, uint128(previous), uint128(previous.sub(amount)) ); emit DelegatedPowerChanged(from, previous.sub(amount), delegationType); } if (to != address(0)) { uint256 previous = 0; uint256 toSnapshotsCount = snapshotsCounts[to]; if (toSnapshotsCount != 0) { previous = snapshots[to][toSnapshotsCount - 1].value; } else { previous = balanceOf(to); } _writeSnapshot( snapshots, snapshotsCounts, to, uint128(previous), uint128(previous.add(amount)) ); emit DelegatedPowerChanged(to, previous.add(amount), delegationType); } } /** * @dev searches a snapshot by block number. Uses binary search. * @param snapshots the snapshots mapping * @param snapshotsCounts the number of snapshots * @param user the user for which the snapshot is being searched * @param blockNumber the block number being searched **/ function _searchByBlockNumber( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, address user, uint256 blockNumber ) internal view returns (uint256) { require(blockNumber <= block.number, 'INVALID_BLOCK_NUMBER'); uint256 snapshotsCount = snapshotsCounts[user]; if (snapshotsCount == 0) { return balanceOf(user); } // First check most recent balance if (snapshots[user][snapshotsCount - 1].blockNumber <= blockNumber) { return snapshots[user][snapshotsCount - 1].value; } // Next check implicit zero balance if (snapshots[user][0].blockNumber > blockNumber) { return 0; } uint256 lower = 0; uint256 upper = snapshotsCount - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Snapshot memory snapshot = snapshots[user][center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; } else if (snapshot.blockNumber < blockNumber) { lower = center; } else { upper = center - 1; } } return snapshots[user][lower].value; } /** * @dev returns the delegation data (snapshot, snapshotsCount, list of delegates) by delegation type * NOTE: Ideal implementation would have mapped this in a struct by delegation type. Unfortunately, * the AAVE token and StakeToken already include a mapping for the snapshots, so we require contracts * who inherit from this to provide access to the delegation data by overriding this method. * @param delegationType the type of delegation **/ function _getDelegationDataByType(DelegationType delegationType) internal virtual view returns ( mapping(address => mapping(uint256 => Snapshot)) storage, //snapshots mapping(address => uint256) storage, //snapshots count mapping(address => address) storage //delegatees list ); /** * @dev Writes a snapshot for an owner of tokens * @param owner The owner of the tokens * @param oldValue The value before the operation that is gonna be executed after the snapshot * @param newValue The value after the operation */ function _writeSnapshot( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, address owner, uint128 oldValue, uint128 newValue ) internal { uint128 currentBlock = uint128(block.number); uint256 ownerSnapshotsCount = snapshotsCounts[owner]; mapping(uint256 => Snapshot) storage snapshotsOwner = snapshots[owner]; // Doing multiple operations in the same block if ( ownerSnapshotsCount != 0 && snapshotsOwner[ownerSnapshotsCount - 1].blockNumber == currentBlock ) { snapshotsOwner[ownerSnapshotsCount - 1].value = newValue; } else { snapshotsOwner[ownerSnapshotsCount] = Snapshot(currentBlock, newValue); snapshotsCounts[owner] = ownerSnapshotsCount + 1; } } /** * @dev returns the user delegatee. If a user never performed any delegation, * his delegated address will be 0x0. In that case we simply return the user itself * @param delegator the address of the user for which return the delegatee * @param delegates the array of delegates for a particular type of delegation **/ function _getDelegatee(address delegator, mapping(address => address) storage delegates) internal view returns (address) { address previousDelegatee = delegates[delegator]; if (previousDelegatee == address(0)) { return delegator; } return previousDelegatee; } } pragma solidity ^0.7.5; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.5; import "./Context.sol"; import "../interfaces/IERC20.sol"; import "./SafeMath.sol"; import "./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 internal _name; string internal _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface IGovernancePowerDelegationToken { enum DelegationType {VOTING_POWER, PROPOSITION_POWER} /** * @dev emitted when a user delegates to another * @param delegator the delegator * @param delegatee the delegatee * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) **/ event DelegateChanged( address indexed delegator, address indexed delegatee, DelegationType delegationType ); /** * @dev emitted when an action changes the delegated power of a user * @param user the user which delegated power has changed * @param amount the amount of delegated power for the user * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) **/ event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType); /** * @dev delegates the specific power to a delegatee * @param delegatee the user which delegated power has changed * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) **/ function delegateByType(address delegatee, DelegationType delegationType) external virtual; /** * @dev delegates all the powers to a specific user * @param delegatee the user to which the power will be delegated **/ function delegate(address delegatee) external virtual; /** * @dev returns the delegatee of an user * @param delegator the address of the delegator **/ function getDelegateeByType(address delegator, DelegationType delegationType) external virtual view returns (address); /** * @dev returns the current delegated power of a user. The current power is the * power delegated at the time of the last snapshot * @param user the user **/ function getPowerCurrent(address user, DelegationType delegationType) external virtual view returns (uint256); /** * @dev returns the delegated power of a user at a certain block * @param user the user **/ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external virtual view returns (uint256); /** * @dev returns the total supply at a certain block number **/ function totalSupplyAt(uint256 blockNumber) external virtual view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.5; /* * @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: agpl-3.0 pragma solidity 0.7.5; /** * @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.7.5; /** * @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"); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {ERC20} from '@aave/aave-token/contracts/open-zeppelin/ERC20.sol'; import {IERC20} from '../interfaces/IERC20.sol'; import {IStakedToken} from '../interfaces/IStakedToken.sol'; import {ITransferHook} from '../interfaces/ITransferHook.sol'; import {DistributionTypes} from '../lib/DistributionTypes.sol'; import {SafeMath} from '../lib/SafeMath.sol'; import {SafeERC20} from '../lib/SafeERC20.sol'; import {VersionedInitializable} from '../utils/VersionedInitializable.sol'; import {AaveDistributionManager} from './AaveDistributionManager.sol'; import {GovernancePowerWithSnapshot} from '../lib/GovernancePowerWithSnapshot.sol'; /** * @title StakedToken * @notice Contract to stake Aave token, tokenize the position and get rewards, inheriting from a distribution manager contract * @author Aave **/ contract StakedTokenV2 is IStakedToken, GovernancePowerWithSnapshot, VersionedInitializable, AaveDistributionManager { using SafeMath for uint256; using SafeERC20 for IERC20; function REVISION() public pure virtual returns (uint256) { return 2; } IERC20 public immutable STAKED_TOKEN; IERC20 public immutable REWARD_TOKEN; uint256 public immutable COOLDOWN_SECONDS; /// @notice Seconds available to redeem once the cooldown period is fullfilled uint256 public immutable UNSTAKE_WINDOW; /// @notice Address to pull from the rewards, needs to have approved this contract address public immutable REWARDS_VAULT; mapping(address => uint256) public stakerRewardsToClaim; mapping(address => uint256) public stakersCooldowns; /// @dev End of Storage layout from StakedToken v1 /// @dev To see the voting mappings, go to GovernancePowerWithSnapshot.sol mapping(address => address) internal _votingDelegates; mapping(address => mapping(uint256 => Snapshot)) internal _propositionPowerSnapshots; mapping(address => uint256) internal _propositionPowerSnapshotsCounts; mapping(address => address) internal _propositionPowerDelegates; bytes32 public DOMAIN_SEPARATOR; bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); bytes32 public constant PERMIT_TYPEHASH = keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'); /// @dev owner => next valid nonce to submit with permit() mapping(address => uint256) public _nonces; event Staked(address indexed from, address indexed onBehalfOf, uint256 amount); event Redeem(address indexed from, address indexed to, uint256 amount); event RewardsAccrued(address user, uint256 amount); event RewardsClaimed(address indexed from, address indexed to, uint256 amount); event Cooldown(address indexed user); constructor( IERC20 stakedToken, IERC20 rewardToken, uint256 cooldownSeconds, uint256 unstakeWindow, address rewardsVault, address emissionManager, uint128 distributionDuration, string memory name, string memory symbol, uint8 decimals, address governance ) public ERC20(name, symbol) AaveDistributionManager(emissionManager, distributionDuration) { STAKED_TOKEN = stakedToken; REWARD_TOKEN = rewardToken; COOLDOWN_SECONDS = cooldownSeconds; UNSTAKE_WINDOW = unstakeWindow; REWARDS_VAULT = rewardsVault; _aaveGovernance = ITransferHook(governance); ERC20._setupDecimals(decimals); } /** * @dev Called by the proxy contract **/ function initialize() external virtual initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(name())), keccak256(EIP712_REVISION), chainId, address(this) ) ); } function stake(address onBehalfOf, uint256 amount) external virtual override { require(amount != 0, 'INVALID_ZERO_AMOUNT'); uint256 balanceOfUser = balanceOf(onBehalfOf); uint256 accruedRewards = _updateUserAssetInternal(onBehalfOf, address(this), balanceOfUser, totalSupply()); if (accruedRewards != 0) { emit RewardsAccrued(onBehalfOf, accruedRewards); stakerRewardsToClaim[onBehalfOf] = stakerRewardsToClaim[onBehalfOf].add(accruedRewards); } stakersCooldowns[onBehalfOf] = getNextCooldownTimestamp(0, amount, onBehalfOf, balanceOfUser); _mint(onBehalfOf, amount); IERC20(STAKED_TOKEN).safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, onBehalfOf, amount); } /** * @dev Redeems staked tokens, and stop earning rewards * @param to Address to redeem to * @param amount Amount to redeem **/ function redeem(address to, uint256 amount) external virtual override { require(amount != 0, 'INVALID_ZERO_AMOUNT'); //solium-disable-next-line uint256 cooldownStartTimestamp = stakersCooldowns[msg.sender]; require( block.timestamp > cooldownStartTimestamp.add(COOLDOWN_SECONDS), 'INSUFFICIENT_COOLDOWN' ); require( block.timestamp.sub(cooldownStartTimestamp.add(COOLDOWN_SECONDS)) <= UNSTAKE_WINDOW, 'UNSTAKE_WINDOW_FINISHED' ); uint256 balanceOfMessageSender = balanceOf(msg.sender); uint256 amountToRedeem = (amount > balanceOfMessageSender) ? balanceOfMessageSender : amount; _updateCurrentUnclaimedRewards(msg.sender, balanceOfMessageSender, true); _burn(msg.sender, amountToRedeem); if (balanceOfMessageSender.sub(amountToRedeem) == 0) { stakersCooldowns[msg.sender] = 0; } IERC20(STAKED_TOKEN).safeTransfer(to, amountToRedeem); emit Redeem(msg.sender, to, amountToRedeem); } /** * @dev Activates the cooldown period to unstake * - It can't be called if the user is not staking **/ function cooldown() external override { require(balanceOf(msg.sender) != 0, 'INVALID_BALANCE_ON_COOLDOWN'); //solium-disable-next-line stakersCooldowns[msg.sender] = block.timestamp; emit Cooldown(msg.sender); } /** * @dev Claims an `amount` of `REWARD_TOKEN` to the address `to` * @param to Address to stake for * @param amount Amount to stake **/ function claimRewards(address to, uint256 amount) external virtual override { uint256 newTotalRewards = _updateCurrentUnclaimedRewards(msg.sender, balanceOf(msg.sender), false); uint256 amountToClaim = (amount == type(uint256).max) ? newTotalRewards : amount; stakerRewardsToClaim[msg.sender] = newTotalRewards.sub(amountToClaim, 'INVALID_AMOUNT'); REWARD_TOKEN.safeTransferFrom(REWARDS_VAULT, to, amountToClaim); emit RewardsClaimed(msg.sender, to, amountToClaim); } /** * @dev Internal ERC20 _transfer of the tokenized staked tokens * @param from Address to transfer from * @param to Address to transfer to * @param amount Amount to transfer **/ function _transfer( address from, address to, uint256 amount ) internal override { uint256 balanceOfFrom = balanceOf(from); // Sender _updateCurrentUnclaimedRewards(from, balanceOfFrom, true); // Recipient if (from != to) { uint256 balanceOfTo = balanceOf(to); _updateCurrentUnclaimedRewards(to, balanceOfTo, true); uint256 previousSenderCooldown = stakersCooldowns[from]; stakersCooldowns[to] = getNextCooldownTimestamp( previousSenderCooldown, amount, to, balanceOfTo ); // if cooldown was set and whole balance of sender was transferred - clear cooldown if (balanceOfFrom == amount && previousSenderCooldown != 0) { stakersCooldowns[from] = 0; } } super._transfer(from, to, amount); } /** * @dev Updates the user state related with his accrued rewards * @param user Address of the user * @param userBalance The current balance of the user * @param updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user * @return The unclaimed rewards that were added to the total accrued **/ function _updateCurrentUnclaimedRewards( address user, uint256 userBalance, bool updateStorage ) internal returns (uint256) { uint256 accruedRewards = _updateUserAssetInternal(user, address(this), userBalance, totalSupply()); uint256 unclaimedRewards = stakerRewardsToClaim[user].add(accruedRewards); if (accruedRewards != 0) { if (updateStorage) { stakerRewardsToClaim[user] = unclaimedRewards; } emit RewardsAccrued(user, accruedRewards); } return unclaimedRewards; } /** * @dev Calculates the how is gonna be a new cooldown timestamp depending on the sender/receiver situation * - If the timestamp of the sender is "better" or the timestamp of the recipient is 0, we take the one of the recipient * - Weighted average of from/to cooldown timestamps if: * # The sender doesn't have the cooldown activated (timestamp 0). * # The sender timestamp is expired * # The sender has a "worse" timestamp * - If the receiver's cooldown timestamp expired (too old), the next is 0 * @param fromCooldownTimestamp Cooldown timestamp of the sender * @param amountToReceive Amount * @param toAddress Address of the recipient * @param toBalance Current balance of the receiver * @return The new cooldown timestamp **/ function getNextCooldownTimestamp( uint256 fromCooldownTimestamp, uint256 amountToReceive, address toAddress, uint256 toBalance ) public view returns (uint256) { uint256 toCooldownTimestamp = stakersCooldowns[toAddress]; if (toCooldownTimestamp == 0) { return 0; } uint256 minimalValidCooldownTimestamp = block.timestamp.sub(COOLDOWN_SECONDS).sub(UNSTAKE_WINDOW); if (minimalValidCooldownTimestamp > toCooldownTimestamp) { toCooldownTimestamp = 0; } else { uint256 fromCooldownTimestamp = (minimalValidCooldownTimestamp > fromCooldownTimestamp) ? block.timestamp : fromCooldownTimestamp; if (fromCooldownTimestamp < toCooldownTimestamp) { return toCooldownTimestamp; } else { toCooldownTimestamp = ( amountToReceive.mul(fromCooldownTimestamp).add(toBalance.mul(toCooldownTimestamp)) ) .div(amountToReceive.add(toBalance)); } } return toCooldownTimestamp; } /** * @dev Return the total rewards pending to claim by an staker * @param staker The staker address * @return The rewards */ function getTotalRewardsBalance(address staker) external view returns (uint256) { DistributionTypes.UserStakeInput[] memory userStakeInputs = new DistributionTypes.UserStakeInput[](1); userStakeInputs[0] = DistributionTypes.UserStakeInput({ underlyingAsset: address(this), stakedByUser: balanceOf(staker), totalStaked: totalSupply() }); return stakerRewardsToClaim[staker].add(_getUnclaimedRewards(staker, userStakeInputs)); } /** * @dev returns the revision of the implementation contract * @return The revision */ function getRevision() internal pure virtual override returns (uint256) { return REVISION(); } /** * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner the owner of the funds * @param spender the spender * @param value the amount * @param deadline the deadline timestamp, type(uint256).max for no deadline * @param v signature param * @param s signature param * @param r signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), 'INVALID_OWNER'); //solium-disable-next-line require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @dev Writes a snapshot before any operation involving transfer of value: _transfer, _mint and _burn * - On _transfer, it writes snapshots for both "from" and "to" * - On _mint, only for _to * - On _burn, only for _from * @param from the from address * @param to the to address * @param amount the amount to transfer */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { address votingFromDelegatee = _votingDelegates[from]; address votingToDelegatee = _votingDelegates[to]; if (votingFromDelegatee == address(0)) { votingFromDelegatee = from; } if (votingToDelegatee == address(0)) { votingToDelegatee = to; } _moveDelegatesByType( votingFromDelegatee, votingToDelegatee, amount, DelegationType.VOTING_POWER ); address propPowerFromDelegatee = _propositionPowerDelegates[from]; address propPowerToDelegatee = _propositionPowerDelegates[to]; if (propPowerFromDelegatee == address(0)) { propPowerFromDelegatee = from; } if (propPowerToDelegatee == address(0)) { propPowerToDelegatee = to; } _moveDelegatesByType( propPowerFromDelegatee, propPowerToDelegatee, amount, DelegationType.PROPOSITION_POWER ); // caching the aave governance address to avoid multiple state loads ITransferHook aaveGovernance = _aaveGovernance; if (aaveGovernance != ITransferHook(0)) { aaveGovernance.onTransfer(from, to, amount); } } function _getDelegationDataByType(DelegationType delegationType) internal view override returns ( mapping(address => mapping(uint256 => Snapshot)) storage, //snapshots mapping(address => uint256) storage, //snapshots count mapping(address => address) storage //delegatees list ) { if (delegationType == DelegationType.VOTING_POWER) { return (_votingSnapshots, _votingSnapshotsCounts, _votingDelegates); } else { return ( _propositionPowerSnapshots, _propositionPowerSnapshotsCounts, _propositionPowerDelegates ); } } /** * @dev Delegates power from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateByTypeBySig( address delegatee, DelegationType delegationType, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 structHash = keccak256( abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry) ); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), 'INVALID_SIGNATURE'); require(nonce == _nonces[signatory]++, 'INVALID_NONCE'); require(block.timestamp <= expiry, 'INVALID_EXPIRATION'); _delegateByType(signatory, delegatee, delegationType); } /** * @dev Delegates power from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), 'INVALID_SIGNATURE'); require(nonce == _nonces[signatory]++, 'INVALID_NONCE'); require(block.timestamp <= expiry, 'INVALID_EXPIRATION'); _delegateByType(signatory, delegatee, DelegationType.VOTING_POWER); _delegateByType(signatory, delegatee, DelegationType.PROPOSITION_POWER); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; library DistributionTypes { struct AssetConfigInput { uint128 emissionPerSecond; uint256 totalStaked; address underlyingAsset; } struct UserStakeInput { address underlyingAsset; uint256 stakedByUser; uint256 totalStaked; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {SafeMath} from '../lib/SafeMath.sol'; import {DistributionTypes} from '../lib/DistributionTypes.sol'; import {IAaveDistributionManager} from '../interfaces/IAaveDistributionManager.sol'; /** * @title AaveDistributionManager * @notice Accounting contract to manage multiple staking distributions * @author Aave **/ contract AaveDistributionManager is IAaveDistributionManager { using SafeMath for uint256; struct AssetData { uint128 emissionPerSecond; uint128 lastUpdateTimestamp; uint256 index; mapping(address => uint256) users; } uint256 internal immutable _oldDistributionEnd; address public immutable EMISSION_MANAGER; uint8 public constant PRECISION = 18; mapping(address => AssetData) public assets; event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated(address indexed user, address indexed asset, uint256 index); constructor(address emissionManager, uint256 distributionDuration) public { _oldDistributionEnd = block.timestamp.add(distributionDuration); EMISSION_MANAGER = emissionManager; } /** * @dev Configures the distribution of rewards for a list of assets * @param assetsConfigInput The list of configurations to apply **/ function configureAssets(DistributionTypes.AssetConfigInput[] calldata assetsConfigInput) external override { require(msg.sender == EMISSION_MANAGER, 'ONLY_EMISSION_MANAGER'); for (uint256 i = 0; i < assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset]; _updateAssetStateInternal( assetsConfigInput[i].underlyingAsset, assetConfig, assetsConfigInput[i].totalStaked ); assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond; emit AssetConfigUpdated( assetsConfigInput[i].underlyingAsset, assetsConfigInput[i].emissionPerSecond ); } } /** * @dev Updates the state of one distribution, mainly rewards index and timestamp * @param underlyingAsset The address used as key in the distribution, for example sAAVE or the aTokens addresses on Aave * @param assetConfig Storage pointer to the distribution's config * @param totalStaked Current total of staked assets for this distribution * @return The new distribution index **/ function _updateAssetStateInternal( address underlyingAsset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex(oldIndex, assetConfig.emissionPerSecond, lastUpdateTimestamp, totalStaked); if (newIndex != oldIndex) { assetConfig.index = newIndex; emit AssetIndexUpdated(underlyingAsset, newIndex); } assetConfig.lastUpdateTimestamp = uint128(block.timestamp); return newIndex; } /** * @dev Updates the state of an user in a distribution * @param user The user's address * @param asset The address of the reference asset of the distribution * @param stakedByUser Amount of tokens staked by the user in the distribution at the moment * @param totalStaked Total tokens staked in the distribution * @return The accrued rewards for the user until the moment **/ function _updateUserAssetInternal( address user, address asset, uint256 stakedByUser, uint256 totalStaked ) internal returns (uint256) { AssetData storage assetData = assets[asset]; uint256 userIndex = assetData.users[user]; uint256 accruedRewards = 0; uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked); if (userIndex != newIndex) { if (stakedByUser != 0) { accruedRewards = _getRewards(stakedByUser, newIndex, userIndex); } assetData.users[user] = newIndex; emit UserIndexUpdated(user, asset, newIndex); } return accruedRewards; } /** * @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _claimRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { accruedRewards = accruedRewards.add( _updateUserAssetInternal( user, stakes[i].underlyingAsset, stakes[i].stakedByUser, stakes[i].totalStaked ) ); } return accruedRewards; } /** * @dev Return the accrued rewards for an user over a list of distribution * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal view returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { AssetData storage assetConfig = assets[stakes[i].underlyingAsset]; uint256 assetIndex = _getAssetIndex( assetConfig.index, assetConfig.emissionPerSecond, assetConfig.lastUpdateTimestamp, stakes[i].totalStaked ); accruedRewards = accruedRewards.add( _getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user]) ); } return accruedRewards; } /** * @dev Internal function for the calculation of user's rewards on a distribution * @param principalUserBalance Amount staked by the user on a distribution * @param reserveIndex Current index of the distribution * @param userIndex Index stored for the user, representation his staking moment * @return The rewards **/ function _getRewards( uint256 principalUserBalance, uint256 reserveIndex, uint256 userIndex ) internal pure returns (uint256) { return principalUserBalance.mul(reserveIndex.sub(userIndex)).div(10**uint256(PRECISION)); } /** * @dev Calculates the next value of an specific distribution index, with validations * @param currentIndex Current index of the distribution * @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution * @param lastUpdateTimestamp Last moment this distribution was updated * @param totalBalance of tokens considered for the distribution * @return The new index. **/ function _getAssetIndex( uint256 currentIndex, uint256 emissionPerSecond, uint128 lastUpdateTimestamp, uint256 totalBalance ) internal view returns (uint256) { if ( emissionPerSecond == 0 || totalBalance == 0 || lastUpdateTimestamp == block.timestamp || lastUpdateTimestamp >= _getDistributionEnd() ) { return currentIndex; } uint256 currentTimestamp = block.timestamp > _getDistributionEnd() ? _getDistributionEnd() : block.timestamp; uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp); return emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add( currentIndex ); } /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) public view returns (uint256) { return assets[asset].users[user]; } /** * @dev Returns the timestamp of the end of the current distribution * @notice This field remains virtual to extend at AaveDistributionManageV2, keeping V1 logic * @return uint256 unix timestamp **/ function _getDistributionEnd() internal view virtual returns (uint256) { return _oldDistributionEnd; } /** * @dev Keeps interface compatibility. Returns the timestamp of the end of the current distribution * @return uint256 unix timestamp **/ function DISTRIBUTION_END() external view returns (uint256) { return _getDistributionEnd(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {DistributionTypes} from '../lib/DistributionTypes.sol'; interface IAaveDistributionManager { function configureAssets(DistributionTypes.AssetConfigInput[] calldata assetsConfigInput) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {ERC20} from '@aave/aave-token/contracts/open-zeppelin/ERC20.sol'; import {IERC20} from '../interfaces/IERC20.sol'; import {IERC20WithPermit} from '../interfaces/IERC20WithPermit.sol'; import {IStakedToken} from '../interfaces/IStakedToken.sol'; import {IStakedTokenV3} from '../interfaces/IStakedTokenV3.sol'; import {ITransferHook} from '../interfaces/ITransferHook.sol'; import {DistributionTypes} from '../lib/DistributionTypes.sol'; import {SafeMath} from '../lib/SafeMath.sol'; import {SafeERC20} from '../lib/SafeERC20.sol'; import {PercentageMath} from '../lib/PercentageMath.sol'; import {StakedTokenV2} from './StakedTokenV2.sol'; import {VersionedInitializable} from '../utils/VersionedInitializable.sol'; import {AaveDistributionManager} from './AaveDistributionManager.sol'; import {GovernancePowerWithSnapshot} from '../lib/GovernancePowerWithSnapshot.sol'; import {RoleManager} from '../utils/RoleManager.sol'; /** * @title StakedToken * @notice Contract to stake Aave token, tokenize the position and get rewards, inheriting from a distribution manager contract * @author Aave **/ contract StakedTokenV3 is StakedTokenV2, IStakedTokenV3, RoleManager { using SafeMath for uint256; using SafeERC20 for IERC20; using PercentageMath for uint256; uint256 public constant SLASH_ADMIN_ROLE = 0; uint256 public constant COOLDOWN_ADMIN_ROLE = 1; uint256 public constant CLAIM_HELPER_ROLE = 2; function REVISION() public pure virtual override returns (uint256) { return 3; } //maximum percentage of the underlying that can be slashed in a single realization event uint256 internal _maxSlashablePercentage; bool _cooldownPaused; modifier onlySlashingAdmin { require(msg.sender == getAdmin(SLASH_ADMIN_ROLE), 'CALLER_NOT_SLASHING_ADMIN'); _; } modifier onlyCooldownAdmin { require(msg.sender == getAdmin(COOLDOWN_ADMIN_ROLE), 'CALLER_NOT_COOLDOWN_ADMIN'); _; } modifier onlyClaimHelper { require(msg.sender == getAdmin(CLAIM_HELPER_ROLE), 'CALLER_NOT_CLAIM_HELPER'); _; } event Staked(address indexed from, address indexed to, uint256 amount, uint256 sharesMinted); event Redeem( address indexed from, address indexed to, uint256 amount, uint256 underlyingTransferred ); event CooldownPauseChanged(bool pause); event MaxSlashablePercentageChanged(uint256 newPercentage); event Slashed(address indexed destination, uint256 amount); event CooldownPauseAdminChanged(address indexed newAdmin); event SlashingAdminChanged(address indexed newAdmin); constructor( IERC20 stakedToken, IERC20 rewardToken, uint256 cooldownSeconds, uint256 unstakeWindow, address rewardsVault, address emissionManager, uint128 distributionDuration, string memory name, string memory symbol, uint8 decimals, address governance ) public StakedTokenV2( stakedToken, rewardToken, cooldownSeconds, unstakeWindow, rewardsVault, emissionManager, distributionDuration, name, symbol, decimals, governance ) {} /** * @dev Inherited from StakedTokenV2, deprecated **/ function initialize() external override { revert('DEPRECATED'); } /** * @dev Called by the proxy contract **/ function initialize( address slashingAdmin, address cooldownPauseAdmin, address claimHelper, uint256 maxSlashablePercentage, string calldata name, string calldata symbol, uint8 decimals ) external initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(super.name())), keccak256(EIP712_REVISION), chainId, address(this) ) ); if (REVISION() == 1) { _name = name; _symbol = symbol; _setupDecimals(decimals); } address[] memory adminsAddresses = new address[](3); uint256[] memory adminsRoles = new uint256[](3); adminsAddresses[0] = slashingAdmin; adminsAddresses[1] = cooldownPauseAdmin; adminsAddresses[2] = claimHelper; adminsRoles[0] = SLASH_ADMIN_ROLE; adminsRoles[1] = COOLDOWN_ADMIN_ROLE; adminsRoles[2] = CLAIM_HELPER_ROLE; _initAdmins(adminsRoles, adminsAddresses); _maxSlashablePercentage = maxSlashablePercentage; } /** * @dev Allows a from to stake STAKED_TOKEN * @param to Address of the from that will receive stake token shares * @param amount The amount to be staked **/ function stake(address to, uint256 amount) external override(IStakedToken, StakedTokenV2) { _stake(msg.sender, to, amount, true); } /** * @dev Allows a from to stake STAKED_TOKEN with gasless approvals (permit) * @param to Address of the from that will receive stake token shares * @param amount The amount to be staked * @param deadline The permit execution deadline * @param v The v component of the signed message * @param r The r component of the signed message * @param s The s component of the signed message **/ function stakeWithPermit( address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { IERC20WithPermit(address(STAKED_TOKEN)).permit(from, address(this), amount, deadline, v, r, s); _stake(from, to, amount, true); } /** * @dev Redeems staked tokens, and stop earning rewards * @param to Address to redeem to * @param amount Amount to redeem **/ function redeem(address to, uint256 amount) external override(IStakedToken, StakedTokenV2) { _redeem(msg.sender, to, amount); } /** * @dev Redeems staked tokens for a user. Only the claim helper contract is allowed to call this function * @param from Address to redeem from * @param to Address to redeem to * @param amount Amount to redeem **/ function redeemOnBehalf( address from, address to, uint256 amount ) external override onlyClaimHelper { _redeem(from, to, amount); } /** * @dev Claims an `amount` of `REWARD_TOKEN` to the address `to` * @param to Address to send the claimed rewards * @param amount Amount to stake **/ function claimRewards(address to, uint256 amount) external override(IStakedToken, StakedTokenV2) { _claimRewards(msg.sender, to, amount); } /** * @dev Claims an `amount` of `REWARD_TOKEN` to the address `to` on behalf of the user. Only the claim helper contract is allowed to call this function * @param from The address of the user from to claim * @param to Address to send the claimed rewards * @param amount Amount to claim **/ function claimRewardsOnBehalf( address from, address to, uint256 amount ) external override onlyClaimHelper returns (uint256) { return _claimRewards(from, to, amount); } /** * @dev Claims an `amount` of `REWARD_TOKEN` amd restakes * @param to Address to stake to * @param amount Amount to claim **/ function claimRewardsAndStake(address to, uint256 amount) external override returns (uint256) { require(REWARD_TOKEN == STAKED_TOKEN, 'REWARD_TOKEN_IS_NOT_STAKED_TOKEN'); uint256 rewardsClaimed = _claimRewards(msg.sender, address(this), amount); if (rewardsClaimed != 0) { _stake(address(this), to, rewardsClaimed, false); } return rewardsClaimed; } /** * @dev Claims an `amount` of `REWARD_TOKEN` and restakes. Only the claim helper contract is allowed to call this function * @param from The address of the from from which to claim * @param to Address to stake to * @param amount Amount to claim **/ function claimRewardsAndStakeOnBehalf( address from, address to, uint256 amount ) external override onlyClaimHelper returns (uint256) { require(REWARD_TOKEN == STAKED_TOKEN, 'REWARD_TOKEN_IS_NOT_STAKED_TOKEN'); uint256 rewardsClaimed = _claimRewards(from, address(this), amount); _stake(address(this), to, rewardsClaimed, false); return (rewardsClaimed); } /** * @dev Claims an `amount` of `REWARD_TOKEN` amd redeem * @param claimAmount Amount to claim * @param redeemAmount Amount to redeem * @param to Address to claim and unstake to **/ function claimRewardsAndRedeem( address to, uint256 claimAmount, uint256 redeemAmount ) external override { _claimRewards(msg.sender, to, claimAmount); _redeem(msg.sender, to, redeemAmount); } /** * @dev Claims an `amount` of `REWARD_TOKEN` and redeem. Only the claim helper contract is allowed to call this function * @param from The address of the from * @param to Address to claim and unstake to * @param claimAmount Amount to claim * @param redeemAmount Amount to redeem **/ function claimRewardsAndRedeemOnBehalf( address from, address to, uint256 claimAmount, uint256 redeemAmount ) external override onlyClaimHelper { _claimRewards(from, to, claimAmount); _redeem(from, to, redeemAmount); } /** * @dev Calculates the exchange rate between the amount of STAKED_TOKEN and the the StakeToken total supply. * Slashing will reduce the exchange rate. Supplying STAKED_TOKEN to the stake contract * can replenish the slashed STAKED_TOKEN and bring the exchange rate back to 1 **/ function exchangeRate() public view override returns (uint256) { uint256 currentSupply = totalSupply(); if (currentSupply == 0) { return 1e18; //initial exchange rate is 1:1 } return STAKED_TOKEN.balanceOf(address(this)).mul(1e18).div(currentSupply); } /** * @dev Executes a slashing of the underlying of a certain amount, transferring the seized funds * to destination. Decreasing the amount of underlying will automatically adjust the exchange rate * @param destination the address where seized funds will be transferred * @param amount the amount **/ function slash(address destination, uint256 amount) external override onlySlashingAdmin { uint256 balance = STAKED_TOKEN.balanceOf(address(this)); uint256 maxSlashable = balance.percentMul(_maxSlashablePercentage); require(amount <= maxSlashable, 'INVALID_SLASHING_AMOUNT'); STAKED_TOKEN.safeTransfer(destination, amount); emit Slashed(destination, amount); } /** * @dev returns true if the unstake cooldown is paused */ function getCooldownPaused() external view override returns (bool) { return _cooldownPaused; } /** * @dev sets the state of the cooldown pause * @param paused true if the cooldown needs to be paused, false otherwise */ function setCooldownPause(bool paused) external override onlyCooldownAdmin { _cooldownPaused = paused; emit CooldownPauseChanged(paused); } /** * @dev sets the admin of the slashing pausing function * @param percentage the new maximum slashable percentage */ function setMaxSlashablePercentage(uint256 percentage) external override onlySlashingAdmin { require(percentage <= PercentageMath.PERCENTAGE_FACTOR, 'INVALID_SLASHING_PERCENTAGE'); _maxSlashablePercentage = percentage; emit MaxSlashablePercentageChanged(percentage); } /** * @dev returns the current maximum slashable percentage of the stake */ function getMaxSlashablePercentage() external view override returns (uint256) { return _maxSlashablePercentage; } /** * @dev returns the revision of the implementation contract * @return The revision */ function getRevision() internal pure virtual override returns (uint256) { return REVISION(); } function _claimRewards( address from, address to, uint256 amount ) internal returns (uint256) { uint256 newTotalRewards = _updateCurrentUnclaimedRewards(from, balanceOf(from), false); uint256 amountToClaim = (amount == type(uint256).max) ? newTotalRewards : amount; stakerRewardsToClaim[from] = newTotalRewards.sub(amountToClaim, 'INVALID_AMOUNT'); REWARD_TOKEN.safeTransferFrom(REWARDS_VAULT, to, amountToClaim); emit RewardsClaimed(from, to, amountToClaim); return (amountToClaim); } function _stake( address from, address to, uint256 amount, bool pullFunds ) internal { require(amount != 0, 'INVALID_ZERO_AMOUNT'); uint256 balanceOfUser = balanceOf(to); uint256 accruedRewards = _updateUserAssetInternal(to, address(this), balanceOfUser, totalSupply()); if (accruedRewards != 0) { emit RewardsAccrued(to, accruedRewards); stakerRewardsToClaim[to] = stakerRewardsToClaim[to].add(accruedRewards); } stakersCooldowns[to] = getNextCooldownTimestamp(0, amount, to, balanceOfUser); uint256 sharesToMint = amount.mul(1e18).div(exchangeRate()); _mint(to, sharesToMint); if (pullFunds) { STAKED_TOKEN.safeTransferFrom(from, address(this), amount); } emit Staked(from, to, amount, sharesToMint); } /** * @dev Redeems staked tokens, and stop earning rewards * @param to Address to redeem to * @param amount Amount to redeem **/ function _redeem( address from, address to, uint256 amount ) internal { require(amount != 0, 'INVALID_ZERO_AMOUNT'); //solium-disable-next-line uint256 cooldownStartTimestamp = stakersCooldowns[from]; require( !_cooldownPaused && block.timestamp > cooldownStartTimestamp.add(COOLDOWN_SECONDS), 'INSUFFICIENT_COOLDOWN' ); require( block.timestamp.sub(cooldownStartTimestamp.add(COOLDOWN_SECONDS)) <= UNSTAKE_WINDOW, 'UNSTAKE_WINDOW_FINISHED' ); uint256 balanceOfFrom = balanceOf(from); uint256 amountToRedeem = (amount > balanceOfFrom) ? balanceOfFrom : amount; _updateCurrentUnclaimedRewards(from, balanceOfFrom, true); uint256 underlyingToRedeem = amountToRedeem.mul(exchangeRate()).div(1e18); _burn(from, amountToRedeem); if (balanceOfFrom.sub(amountToRedeem) == 0) { stakersCooldowns[from] = 0; } IERC20(STAKED_TOKEN).safeTransfer(to, underlyingToRedeem); emit Redeem(from, to, amountToRedeem, underlyingToRedeem); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; import {IERC20} from './IERC20.sol'; interface IERC20WithPermit is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; import {IStakedToken} from './IStakedToken.sol'; interface IStakedTokenV3 is IStakedToken { function exchangeRate() external view returns (uint256); function getCooldownPaused() external view returns (bool); function setCooldownPause(bool paused) external; function slash(address destination, uint256 amount) external; function getMaxSlashablePercentage() external view returns (uint256); function setMaxSlashablePercentage(uint256 percentage) external; function stakeWithPermit( address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function claimRewardsOnBehalf( address from, address to, uint256 amount ) external returns (uint256); function redeemOnBehalf( address from, address to, uint256 amount ) external; function claimRewardsAndStake(address to, uint256 amount) external returns (uint256); function claimRewardsAndRedeem( address to, uint256 claimAmount, uint256 redeemAmount ) external; function claimRewardsAndStakeOnBehalf( address from, address to, uint256 amount ) external returns (uint256); function claimRewardsAndRedeemOnBehalf( address from, address to, uint256 claimAmount, uint256 redeemAmount ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, "MATH_MULTIPLICATION_OVERFLOW" ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, "MATH_DIVISION_BY_ZERO"); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, "MATH_MULTIPLICATION_OVERFLOW" ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } pragma solidity ^0.7.5; /** * @title RoleManager * @notice Generic role manager to manage slashing and cooldown admin in StakedAaveV3. * It implements a claim admin role pattern to safely migrate between different admin addresses * @author Aave **/ contract RoleManager { mapping(uint256 => address) private _admins; mapping(uint256 => address) private _pendingAdmins; event PendingAdminChanged(address indexed newPendingAdmin); event RoleClaimed(address indexed newAdming, uint256 role); modifier onlyRoleAdmin(uint256 role) { require(_admins[role] == msg.sender, 'CALLER_NOT_ROLE_ADMIN'); _; } modifier onlyPendingRoleAdmin(uint256 role) { require(_pendingAdmins[role] == msg.sender, 'CALLER_NOT_PENDING_ROLE_ADMIN'); _; } /** * @dev returns the admin associated with the specific role * @param role the role associated with the admin being returned **/ function getAdmin(uint256 role) public view returns (address) { return _admins[role]; } /** * @dev returns the pending admin associated with the specific role * @param role the role associated with the pending admin being returned **/ function getPendingAdmin(uint256 role) public view returns (address) { return _pendingAdmins[role]; } /** * @dev sets the pending admin for a specific role * @param role the role associated with the new pending admin being set * @param newPendingAdmin the address of the new pending admin **/ function setPendingAdmin(uint256 role, address newPendingAdmin) public onlyRoleAdmin(role) { _pendingAdmins[role] = newPendingAdmin; emit PendingAdminChanged(newPendingAdmin); } /** * @dev allows the caller to become a specific role admin * @param role the role associated with the admin claiming the new role **/ function claimRoleAdmin(uint256 role) external onlyPendingRoleAdmin(role) { _admins[role] = msg.sender; emit RoleClaimed(msg.sender, role); } function _initAdmins(uint256[] memory roles, address[] memory admins) internal { require(roles.length == admins.length, 'INCONSISTENT_INITIALIZATION'); for (uint256 i = 0; i < roles.length; i++) { require(_admins[i] == address(0), 'ADMIN_ALREADY_INITIALIZED'); _admins[roles[i]] = admins[i]; emit RoleClaimed(admins[i], roles[i]); } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Proxy.sol'; import './Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev From https://github.com/OpenZeppelin/openzeppelin-sdk/tree/solc-0.6/packages/lib/contracts/upgradeability * This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal view override returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), 'Cannot set a proxy implementation to a non-contract address' ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @title Proxy * @dev From https://github.com/OpenZeppelin/openzeppelin-sdk/tree/solc-0.6/packages/lib/contracts/upgradeability * Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './BaseUpgradeabilityProxy.sol'; /** * @title InitializableUpgradeabilityProxy * @dev From https://github.com/OpenZeppelin/openzeppelin-sdk/tree/solc-0.6/packages/lib/contracts/upgradeability * Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev From https://github.com/OpenZeppelin/openzeppelin-sdk/tree/solc-0.6/packages/lib/contracts/upgradeability * Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize( address _logic, address _admin, bytes memory _data ) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev From https://github.com/OpenZeppelin/openzeppelin-sdk/tree/solc-0.6/packages/lib/contracts/upgradeability * This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), 'Cannot change the admin of a proxy to the zero address'); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != _admin(), 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev From https://github.com/OpenZeppelin/openzeppelin-sdk/tree/solc-0.6/packages/lib/contracts/upgradeability * Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } import '@aave/aave-stake/contracts/lib/InitializableAdminUpgradeabilityProxy.sol'; pragma solidity 0.7.5; import {IStakedTokenWithConfig} from '../interfaces/IStakedTokenWithConfig.sol'; import {IERC20} from '@aave/aave-stake/contracts/interfaces/IERC20.sol'; contract StakeMock is IStakedTokenWithConfig { address public immutable override STAKED_TOKEN; constructor(address stakedToken) { STAKED_TOKEN = stakedToken; } function stake(address to, uint256 amount) external override { IERC20(STAKED_TOKEN).transferFrom(msg.sender, address(this), amount); } function redeem(address to, uint256 amount) external override {} function cooldown() external override {} function claimRewards(address to, uint256 amount) external override {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {IERC20} from '../interfaces/IERC20.sol'; import {StakedTokenV3} from './StakedTokenV3.sol'; /** * @title StakedAaveV3 * @notice StakedTokenV3 with AAVE token as staked token * @author Aave **/ contract StakedAaveV3 is StakedTokenV3 { string internal constant NAME = 'Staked Aave'; string internal constant SYMBOL = 'stkAAVE'; uint8 internal constant DECIMALS = 18; constructor( IERC20 stakedToken, IERC20 rewardToken, uint256 cooldownSeconds, uint256 unstakeWindow, address rewardsVault, address emissionManager, uint128 distributionDuration, address governance ) public StakedTokenV3( stakedToken, rewardToken, cooldownSeconds, unstakeWindow, rewardsVault, emissionManager, distributionDuration, NAME, SYMBOL, DECIMALS, governance ) {} } import '@aave/aave-stake/contracts/stake/StakedAaveV3.sol';
Redeems staked tokens, and stop earning rewards to Address to redeem to amount Amount to redeem/solium-disable-next-line
function _redeem( address from, address to, uint256 amount ) internal { require(amount != 0, 'INVALID_ZERO_AMOUNT'); uint256 cooldownStartTimestamp = stakersCooldowns[from]; require( !_cooldownPaused && block.timestamp > cooldownStartTimestamp.add(COOLDOWN_SECONDS), 'INSUFFICIENT_COOLDOWN' ); require( block.timestamp.sub(cooldownStartTimestamp.add(COOLDOWN_SECONDS)) <= UNSTAKE_WINDOW, 'UNSTAKE_WINDOW_FINISHED' ); uint256 balanceOfFrom = balanceOf(from); uint256 amountToRedeem = (amount > balanceOfFrom) ? balanceOfFrom : amount; _updateCurrentUnclaimedRewards(from, balanceOfFrom, true); uint256 underlyingToRedeem = amountToRedeem.mul(exchangeRate()).div(1e18); _burn(from, amountToRedeem); if (balanceOfFrom.sub(amountToRedeem) == 0) { stakersCooldowns[from] = 0; } IERC20(STAKED_TOKEN).safeTransfer(to, underlyingToRedeem); emit Redeem(from, to, amountToRedeem, underlyingToRedeem); }
14,847,142
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {IERC165Upgradeable, IERC2981Upgradeable} from "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import {IRoyaltyFeeManager} from "./interfaces/IRoyaltyFeeManager.sol"; /** * @title RoyaltyFeeManager * @notice It handles the logic to check and transfer royalty fees (if any). */ contract RoyaltyFeeManager is IRoyaltyFeeManager, OwnableUpgradeable { // https://eips.ethereum.org/EIPS/eip-2981 bytes4 public constant INTERFACE_ID_ERC2981 = 0x2a55205a; struct FeeInfo { address setter; address receiver; uint256 fee; } // Limit (if enforced for fee royalty in percentage (10,000 = 100%) uint256 public royaltyFeeLimit; mapping(address => FeeInfo) private _royaltyFeeInfoCollection; event NewRoyaltyFeeLimit(uint256 royaltyFeeLimit); event RoyaltyFeeUpdate(address indexed collection, address indexed setter, address indexed receiver, uint256 fee); /** * @notice initializer * @param _royaltyFeeLimit new royalty fee limit (500 = 5%, 1,000 = 10%) */ function initialize(uint256 _royaltyFeeLimit) public initializer { __Ownable_init(); require(_royaltyFeeLimit <= 5000, "Owner: Royalty fee limit too high"); royaltyFeeLimit = _royaltyFeeLimit; } /** * @notice Update royalty info for collection * @param _royaltyFeeLimit new royalty fee limit (500 = 5%, 1,000 = 10%) */ function updateRoyaltyFeeLimit(uint256 _royaltyFeeLimit) external override onlyOwner { require(_royaltyFeeLimit <= 5000, "Owner: Royalty fee limit too high"); royaltyFeeLimit = _royaltyFeeLimit; emit NewRoyaltyFeeLimit(_royaltyFeeLimit); } /** * @notice Update royalty info for collection * @param collection address of the NFT contract * @param setter address that sets the receiver * @param receiver receiver for the royalty fee * @param fee fee (500 = 5%, 1,000 = 10%) */ function updateRoyaltyInfoForCollection( address collection, address setter, address receiver, uint256 fee ) external override onlyOwner { require(fee <= royaltyFeeLimit, "Registry: Royalty fee too high"); _royaltyFeeInfoCollection[collection] = FeeInfo({setter: setter, receiver: receiver, fee: fee}); emit RoyaltyFeeUpdate(collection, setter, receiver, fee); } /** * @notice Calculate royalty info for a collection address and a sale gross amount * @param collection collection address * @param amount amount * @return receiver address and amount received by royalty recipient */ function royaltyInfo(address collection, uint256 amount) public view override returns (address, uint256) { return ( _royaltyFeeInfoCollection[collection].receiver, (amount * _royaltyFeeInfoCollection[collection].fee) / 10000 ); } /** * @notice View royalty info for a collection address * @param collection collection address */ function royaltyFeeInfoCollection(address collection) external view override returns ( address, address, uint256 ) { return ( _royaltyFeeInfoCollection[collection].setter, _royaltyFeeInfoCollection[collection].receiver, _royaltyFeeInfoCollection[collection].fee ); } /** * @notice Calculate royalty fee and get recipient * @param collection address of the NFT contract * @param tokenId tokenId * @param amount amount to transfer */ function calculateRoyaltyFeeAndGetRecipient( address collection, uint256 tokenId, uint256 amount ) external view override returns (address, uint256) { // 1. Check if there is a royalty info in the system (address receiver, uint256 royaltyAmount) = royaltyInfo(collection, amount); // 2. If the receiver is address(0), fee is null, check if it supports the ERC2981 interface if ((receiver == address(0)) || (royaltyAmount == 0)) { if (IERC165Upgradeable(collection).supportsInterface(INTERFACE_ID_ERC2981)) { (receiver, royaltyAmount) = IERC2981Upgradeable(collection).royaltyInfo(tokenId, amount); } } return (receiver, royaltyAmount); } }
Calculate royalty info for a collection address and a sale gross amount collection collection address amount amount return receiver address and amount received by royalty recipient/
function royaltyInfo(address collection, uint256 amount) public view override returns (address, uint256) { return ( _royaltyFeeInfoCollection[collection].receiver, (amount * _royaltyFeeInfoCollection[collection].fee) / 10000 ); }
12,673,095
./full_match/1313161554/0x8A7feB26ee5b202804AC11Dd5a739A945C5De11d/sources/contracts/StakedAuroraVault.sol
FLOW 1: Use the stAUR in the Liquidity Pool. FLOW 2: Stake with the depositor to mint more stAUR.
function _deposit( address _caller, address _receiver, uint256 _assets, uint256 _shares ) internal override { IERC20 auroraToken = IERC20(asset()); IStakingManager manager = IStakingManager(stakingManager); auroraToken.safeTransferFrom(_caller, address(this), _assets); ILiquidityPool _pool = liquidityPool; if (_pool.isStAurBalanceAvailable(_shares)) { auroraToken.safeIncreaseAllowance(address(_pool), _assets); _pool.transferStAur(_receiver, _shares, _assets); address depositor = manager.nextDepositor(); auroraToken.safeIncreaseAllowance(depositor, _assets); IDepositor(depositor).stake(_assets); manager.setNextDepositor(); _mint(_receiver, _shares); } emit Deposit(_caller, _receiver, _assets, _shares); }
13,234,737
./partial_match/97/0x330b589C208aAD7a710827D74Fd9D88C87527BAB/sources/X2Money.sol
checking conditionsuint64 fct=1;updating variables
function swapBuyLevel(address _user, uint64 _level) public payable returns(bool) { require(!swapComplete, "swap is already finished"); address msgSender = _user; require(userInfos[msgSender].joined, 'User not exist'); require(_level >= 1 && _level <= 10, 'Incorrect level'); address _origRef = userAddressByID[userInfos[msgSender].origRef]; totalGainInMainNetwork[owner] += systemDistPart ; netTotalUserWithdrawable[owner] += systemDistPart ; totalGainDirect[_origRef] += globalDivDistPart[_level] * 4; totalDirectLifeTime[_origRef] += globalDivDistPart[_level] * 4; netTotalUserWithdrawable[_origRef] += globalDivDistPart[_level] * 4; emit dividendSentEv(msgSender, globalDivDistPart[_level] ); if(thisMonthEnd < now) startNextMonth(); if(_level == 1) { userInfos[msgSender].levelExpired[1] += levelLifeTime; } else { for(uint64 l =_level - 1; l > 0; l--) require(userInfos[msgSender].levelExpired[l] >= now, 'Buy the previous level'); if(userInfos[msgSender].levelExpired[_level] == 0) userInfos[msgSender].levelExpired[_level] = uint64(now) + levelLifeTime; else userInfos[msgSender].levelExpired[_level] += levelLifeTime; } require(payForLevel(_level, msgSender),"pay for level fail"); emit levelBuyEv(msgSender, _level, priceOfLevel[_level] , uint64(now)); require(updateNPayAutoPool(_level,msgSender),"auto pool update fail"); return true; }
11,396,848
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.6; pragma abicoder v2; import "@chainlink/contracts/src/v0.7/interfaces/KeeperRegistryInterface.sol"; import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol"; import "./LimitOrderMonitor.sol"; /// @title LimitOrderMonitorChainlink contract LimitOrderMonitorChainlinkV2 is LimitOrderMonitor { /// @dev fast gas AggregatorV3Interface public FAST_GAS_FEED; function initialize(IOrderManager _orderManager, IUniswapV3Factory _factory, IERC20 _KROM, address _keeper, uint256 _batchSize, uint256 _monitorSize, uint256 _upkeepInterval, AggregatorV3Interface fastGasFeed) public initializer { super.initialize( _orderManager, _factory, _KROM, _keeper, _batchSize, _monitorSize, _upkeepInterval ); FAST_GAS_FEED = fastGasFeed; } function _getGasPrice(uint256 _txnGasPrice) internal view virtual override returns (uint256 gasPrice) { if (_txnGasPrice > 0) { return _txnGasPrice; } uint256 timestamp; int256 feedValue; (,feedValue,,timestamp,) = FAST_GAS_FEED.latestRoundData(); gasPrice = uint256(feedValue); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.6; interface IOrderMonitor { function startMonitor(uint256 _tokenId) external; function stopMonitor(uint256 _tokenId) external; function getTokenIdsLength() external view returns (uint256); function monitorSize() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.6; pragma abicoder v2; interface IOrderManager { struct LimitOrderParams { address _token0; address _token1; uint24 _fee; uint160 _sqrtPriceX96; uint128 _amount0; uint128 _amount1; uint256 _amount0Min; uint256 _amount1Min; } function placeLimitOrder(LimitOrderParams calldata params) external payable returns (uint256 tokenId); function processLimitOrder( uint256 _tokenId, uint256 _serviceFee, uint256 _monitorFee ) external returns (uint128, uint128); function canProcess(uint256 _tokenId, uint256 gasPrice) external returns (bool, uint256, uint256); function quoteKROM(uint256 weiAmount) external returns (uint256 quote); function funding(address owner) external view returns (uint256 balance); function feeAddress() external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@chainlink/contracts/src/v0.7/interfaces/KeeperCompatibleInterface.sol"; import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol"; import "@chainlink/contracts/src/v0.7/KeeperBase.sol"; import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol"; import "./interfaces/IOrderMonitor.sol"; import "./interfaces/IOrderManager.sol"; /// @title LimitOrderMonitor contract LimitOrderMonitor is Initializable, IOrderMonitor, KeeperCompatibleInterface, KeeperBase { using SafeMath for uint256; uint256 private constant MAX_INT = 2**256 - 1; uint256 private constant MAX_BATCH_SIZE = 100; uint256 private constant MAX_MONITOR_SIZE = 10000; event BatchProcessed(uint256 batchSize, uint256 gasUsed, uint256 paymentPaid, bytes data); /// @dev when batch size have changed event BatchSizeChanged(address from, uint256 newValue); /// @dev when monitor size have changed event MonitorSizeChanged(address from, uint256 newValue); /// @dev when upkeep interval changed event UpkeepIntervalChanged(address from, uint256 newValue); /// @dev when controller has changed event ControllerChanged(address from, address newValue); /// @dev when keeper has changed event KeeperChanged(address from, address newValue); /// @dev when monitor is started event MonitorStarted(uint256 tokenId); /// @dev when monitor is stopped event MonitorStopped(uint256 tokenId); /// @dev tokenIds index per token id mapping (uint256 => uint256) public tokenIndexPerTokenId; /// @dev tokens to monitor uint256[] public tokenIds; /// @dev controller address; could be DAO address public controller; /// @dev keeper address; can do upkeep address public keeper; /// @dev order manager IOrderManager public orderManager; /// @dev univ3 factory IUniswapV3Factory public factory; /// @dev krom token IERC20 public KROM; /// @dev last upkeep block uint256 public lastUpkeep; /// @dev max batch size uint256 public batchSize; /// @dev max monitor size uint256 public override monitorSize; /// @dev interval between 2 upkeeps, in blocks uint256 public upkeepInterval; constructor () initializer {} function initialize (IOrderManager _orderManager, IUniswapV3Factory _factory, IERC20 _KROM, address _keeper, uint256 _batchSize, uint256 _monitorSize, uint256 _upkeepInterval) public initializer { require(_batchSize <= MAX_BATCH_SIZE, "INVALID_BATCH_SIZE"); require(_monitorSize <= MAX_MONITOR_SIZE, "INVALID_MONITOR_SIZE"); require(_batchSize <= _monitorSize, "SIZE_MISMATCH"); orderManager = _orderManager; factory = _factory; KROM = _KROM; batchSize = _batchSize; monitorSize = _monitorSize; upkeepInterval = _upkeepInterval; controller = msg.sender; keeper = _keeper; require(KROM.approve(address(orderManager), MAX_INT)); } function startMonitor(uint256 _tokenId) external override { isAuthorizedTradeManager(); require(tokenIds.length < monitorSize, "MONITOR_FULL"); tokenIds.push(_tokenId); tokenIndexPerTokenId[_tokenId] = tokenIds.length; emit MonitorStarted(_tokenId); } function stopMonitor(uint256 _tokenId) external override { isAuthorizedTradeManager(); _stopMonitor(_tokenId); emit MonitorStopped(_tokenId); } function checkUpkeep( bytes calldata ) external override cannotExecute returns ( bool upkeepNeeded, bytes memory performData ) { if (upkeepNeeded = (_getBlockNumber() - lastUpkeep) > upkeepInterval) { uint256 _tokenId; uint256[] memory batchTokenIds = new uint256[](batchSize); uint256 count; // iterate through all active tokens; for (uint256 i = 0; i < tokenIds.length; i++) { _tokenId = tokenIds[i]; (upkeepNeeded,,) = orderManager.canProcess( _tokenId, _getGasPrice(tx.gasprice) ); if (upkeepNeeded) { batchTokenIds[count] = _tokenId; count++; } if (count >= batchSize) { break; } } upkeepNeeded = count > 0; if (upkeepNeeded) { performData = abi.encode(batchTokenIds, count); } } } function performUpkeep( bytes calldata performData ) external override { uint256 _gasUsed = gasleft(); (uint256[] memory _tokenIds, uint256 _count) = abi.decode( performData, (uint256[], uint256) ); uint256 serviceFeePaid; uint256 monitorFeePaid; uint256 validCount; { bool validTrade; uint256 _serviceFee; uint256 _monitorFee; uint256 _tokenId; require(_count <= _tokenIds.length, "LOC_CL"); require(_count <= batchSize, "LOC_BS"); for (uint256 i = 0; i < _count; i++) { _tokenId = _tokenIds[i]; (validTrade, _serviceFee, _monitorFee) = orderManager.canProcess(_tokenId, _getGasPrice(tx.gasprice)); if (validTrade) { validCount++; _stopMonitor(_tokenId); orderManager.processLimitOrder( _tokenId, _serviceFee, _monitorFee ); serviceFeePaid = serviceFeePaid.add(_serviceFee); monitorFeePaid = monitorFeePaid.add(_monitorFee); } } } require(validCount > 0, "LOC_VC"); _gasUsed = _gasUsed - gasleft(); lastUpkeep = _getBlockNumber(); // send the paymentPaid to the keeper _transferFees(monitorFeePaid, keeper); // send the diff to the fee address _transferFees(serviceFeePaid.sub(monitorFeePaid), orderManager.feeAddress()); emit BatchProcessed( validCount, _gasUsed, serviceFeePaid, performData ); } function setBatchSize(uint256 _batchSize) external { isAuthorizedController(); require(_batchSize <= MAX_BATCH_SIZE, "INVALID_BATCH_SIZE"); require(_batchSize <= monitorSize, "SIZE_MISMATCH"); batchSize = _batchSize; emit BatchSizeChanged(msg.sender, _batchSize); } function setMonitorSize(uint256 _monitorSize) external { isAuthorizedController(); require(_monitorSize <= MAX_MONITOR_SIZE, "INVALID_MONITOR_SIZE"); require(_monitorSize >= batchSize, "SIZE_MISMATCH"); monitorSize = _monitorSize; emit MonitorSizeChanged(msg.sender, _monitorSize); } function setUpkeepInterval(uint256 _upkeepInterval) external { isAuthorizedController(); upkeepInterval = _upkeepInterval; emit UpkeepIntervalChanged(msg.sender, _upkeepInterval); } function changeController(address _controller) external { isAuthorizedController(); controller = _controller; emit ControllerChanged(msg.sender, _controller); } function changeKeeper(address _keeper) external { isAuthorizedController(); keeper = _keeper; emit KeeperChanged(msg.sender, _keeper); } function _stopMonitor(uint256 _tokenId) internal { uint256 tokenIndexToRemove = tokenIndexPerTokenId[_tokenId] - 1; uint256 lastTokenId = tokenIds[tokenIds.length - 1]; removeElementFromArray(tokenIndexToRemove, tokenIds); if (tokenIds.length == 0) { delete tokenIndexPerTokenId[lastTokenId]; } else if (tokenIndexToRemove != tokenIds.length) { tokenIndexPerTokenId[lastTokenId] = tokenIndexToRemove + 1; delete tokenIndexPerTokenId[_tokenId]; } } // TODO override for chainlink (use fast gas) function _getGasPrice(uint256 _txnGasPrice) internal virtual view returns (uint256 gasPrice) { gasPrice = _txnGasPrice > 0 ? _txnGasPrice : 0; } // TODO (override block numbers for L2) function _getBlockNumber() internal virtual view returns (uint256 blockNumber) { blockNumber = block.number; } function _transferFees(uint256 _amount, address _owner) internal virtual { if (_amount > 0) { TransferHelper.safeTransfer(address(KROM), _owner, _amount); } } function getTokenIdsLength() external view override returns (uint256) { return tokenIds.length; } function isAuthorizedController() internal view { require(msg.sender == controller, "LOC_AC"); } function isAuthorizedTradeManager() internal view { require(msg.sender == address(orderManager), "LOC_ATM"); } /// @notice Removes index element from the given array. /// @param index index to remove from the array /// @param array the array itself function removeElementFromArray(uint256 index, uint256[] storage array) private { if (index == array.length - 1) { array.pop(); } else { array[index] = array[array.length - 1]; array.pop(); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity >=0.7.5; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. 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"); (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 (proxy/utils/Initializable.sol) pragma solidity >=0.7.5; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * 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 pragma solidity ^0.7.0; interface KeeperRegistryBaseInterface { function registerUpkeep( address target, uint32 gasLimit, address admin, bytes calldata checkData ) external returns ( uint256 id ); function performUpkeep( uint256 id, bytes calldata performData ) external returns ( bool success ); function cancelUpkeep( uint256 id ) external; function addFunds( uint256 id, uint96 amount ) external; function getUpkeep(uint256 id) external view returns ( address target, uint32 executeGas, bytes memory checkData, uint96 balance, address lastKeeper, address admin, uint64 maxValidBlocknumber ); function getUpkeepCount() external view returns (uint256); function getCanceledUpkeepList() external view returns (uint256[] memory); function getKeeperList() external view returns (address[] memory); function getKeeperInfo(address query) external view returns ( address payee, bool active, uint96 balance ); function getConfig() external view returns ( uint32 paymentPremiumPPB, uint24 checkFrequencyBlocks, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, uint256 fallbackGasPrice, uint256 fallbackLinkPrice ); } /** * @dev The view methods are not actually marked as view in the implementation * but we want them to be easily queried off-chain. Solidity will not compile * if we actually inherrit from this interface, so we document it here. */ interface KeeperRegistryInterface is KeeperRegistryBaseInterface { function checkUpkeep( uint256 upkeepId, address from ) external view returns ( bytes memory performData, uint256 maxLinkPayment, uint256 gasLimit, int256 gasWei, int256 linkEth ); } interface KeeperRegistryExecutableInterface is KeeperRegistryBaseInterface { function checkUpkeep( uint256 upkeepId, address from ) external returns ( bytes memory performData, uint256 maxLinkPayment, uint256 gasLimit, uint256 adjustedGasWei, uint256 linkEth ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface KeeperCompatibleInterface { /** * @notice method that is simulated by the keepers to see if any work actually * needs to be performed. This method does does not actually need to be * executable, and since it is only ever simulated it can consume lots of gas. * @dev To ensure that it is never called, you may want to add the * cannotExecute modifier from KeeperBase to your implementation of this * method. * @param checkData specified in the upkeep registration so it is always the * same for a registered upkeep. This can easilly be broken down into specific * arguments using `abi.decode`, so multiple upkeeps can be registered on the * same contract and easily differentiated by the contract. * @return upkeepNeeded boolean to indicate whether the keeper should call * performUpkeep or not. * @return performData bytes that the keeper should call performUpkeep with, if * upkeep is needed. If you would like to encode data to decode later, try * `abi.encode`. */ function checkUpkeep( bytes calldata checkData ) external returns ( bool upkeepNeeded, bytes memory performData ); /** * @notice method that is actually executed by the keepers, via the registry. * The data returned by the checkUpkeep simulation will be passed into * this method to actually be executed. * @dev The input to this method should not be trusted, and the caller of the * method should not even be restricted to any single registry. Anyone should * be able call it, and the input should be validated, there is no guarantee * that the data passed in is the performData returned from checkUpkeep. This * could happen due to malicious keepers, racing keepers, or simply a state * change while the performUpkeep transaction is waiting for confirmation. * Always validate the data passed in. * @param performData is the data which was passed back from the checkData * simulation. If it is encoded, it can easily be decoded into other types by * calling `abi.decode`. This data should not be trusted, and should be * validated against the contract's current state. */ function performUpkeep( bytes calldata performData ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; contract KeeperBase { /** * @notice method that allows it to be simulated via eth_call by checking that * the sender is the zero address. */ function preventExecution() internal view { require(tx.origin == address(0), "only for simulated backend"); } /** * @notice modifier that allows it to be simulated via eth_call by checking * that the sender is the zero address. */ modifier cannotExecute() { preventExecution(); _; } }
iterate through all active tokens;
function checkUpkeep( bytes calldata ) external override cannotExecute returns ( bool upkeepNeeded, bytes memory performData ) { if (upkeepNeeded = (_getBlockNumber() - lastUpkeep) > upkeepInterval) { uint256 _tokenId; uint256[] memory batchTokenIds = new uint256[](batchSize); uint256 count; for (uint256 i = 0; i < tokenIds.length; i++) { _tokenId = tokenIds[i]; (upkeepNeeded,,) = orderManager.canProcess( _tokenId, _getGasPrice(tx.gasprice) ); if (upkeepNeeded) { batchTokenIds[count] = _tokenId; count++; } if (count >= batchSize) { break; } } upkeepNeeded = count > 0; if (upkeepNeeded) { performData = abi.encode(batchTokenIds, count); } } }
6,078,675
pragma solidity ^0.4.23; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn'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; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; mapping(address => bool) _frozenAccount; // FreezableToken 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]); require(balances[_to].add(_value) >= balances[_to]); // Check for overflows require(!_frozenAccount[msg.sender]); require(!_frozenAccount[_to]); 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 balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken, Ownable { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param target address * @param value The amount of token to be burned. */ function burn(address target, uint256 value) onlyOwner public { require(value <= balances[target]); // 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[target] = balances[target].sub(value); totalSupply_ = totalSupply_.sub(value); emit Burn(target, value); emit Transfer(target, address(0), value); } } /** * @title Freezable Token * @dev Token that can be frozen and unfrozen. */ contract FreezableToken is BasicToken, Ownable { event FrozenFunds(address target, bool frozen); /** * @dev Freeze or unfreeze specified account * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) onlyOwner public { _frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * @dev Gets account frozen status. * @param _owner The address to query the frozen status. * @return Boolean status: frozen - true or 1, unfrozen - false or 0. */ function frozenAccount(address _owner) public view returns (bool) { return _frozenAccount[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens to array of address * @param _value uint256 the amount of tokens to be transferred for each address * @param _to array of address transfer to (max 100 address) */ function multiTransfer(uint256 _value, address[] _to) public returns (bool) { require(_to.length <= 100); require(_value.mul(_to.length) <= balances[msg.sender]); for(uint i = 0; i < _to.length; i++) { require(transfer(_to[i], _value)); } return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(balances[_to].add(_value) >= balances[_to]); // Check for overflows require(!_frozenAccount[_from]); require(!_frozenAccount[_to]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title Get Achieve token * @dev GAT Smart Contract */ contract GAToken is DetailedERC20, StandardToken, BurnableToken, FreezableToken, PausableToken { /** * Init token by setting its total supply * * @param totalSupply total token supply */ constructor( uint256 totalSupply ) DetailedERC20( "Get Achieve token v2 official", "GAT", 18 ) public { totalSupply_ = totalSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balances[msg.sender] = totalSupply_; emit Transfer(0x0, msg.sender, totalSupply_); } /** * Refund if someone sent ETH to this contract (GAS also will be refunded) */ function() public payable { revert(); } }
Transfer tokens to array of address _value uint256 the amount of tokens to be transferred for each address _to array of address transfer to (max 100 address)/
function multiTransfer(uint256 _value, address[] _to) public returns (bool) { require(_to.length <= 100); require(_value.mul(_to.length) <= balances[msg.sender]); for(uint i = 0; i < _to.length; i++) { require(transfer(_to[i], _value)); } return true; }
1,057,274
//Address: 0x82c7a0c5e9c8c435df21e00eecea76106054fbf8 //Contract name: KimContract //Balance: 0.344643620094497854 Ether //Verification Date: 2/15/2018 //Transacion Count: 299 // CODE STARTS HERE pragma solidity ^0.4.18; contract KimAccessControl { // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// @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 _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; } } contract KimContract is KimAccessControl{ // DECLARING BASIC VARIABLES, TOKEN SYMBOLS, AND CONSTANTS // Public variables of the token string public name; string public symbol; // total supply of kims ever to be in circulation uint256 public totalSupply; // Total Kims "released" into the market uint256 public kimsCreated; // Total Kims on sale at any given time uint256 public kimsOnAuction; // This is the cut each seller will take on the sale of a KIM uint256 public sellerCut; // A variable to house mathematic function used in _computeCut function uint constant feeDivisor = 100; // Map an owners address to the total amount of KIMS that they own mapping (address => uint256) public balanceOf; // Map the KIM to the owner, "Who owns this Kim?" mapping (uint => address) public tokenToOwner; // This creates a mapping of the tokenId to an Auction mapping (uint256 => TokenAuction) public tokenAuction; // How much ether does this wallet have to withdraw? mapping (address => uint) public pendingWithdrawals; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); event TokenAuctionCreated(uint256 tokenIndex, address seller, uint256 sellPrice); event TokenAuctionCompleted(uint256 tokenIndex, address seller, address buyer, uint256 sellPrice); event Withdrawal(address to, uint256 amount); /* Initializes contract with initial supply tokens to the creator of the contract */ function KimContract() public { // 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; // Initiate the contract with inital supply of Kims totalSupply = 5000; // Give all initial kims to the contract itself balanceOf[this] = totalSupply; // Give the creator all initial tokens // This is what we will call KIMs name = "KimJongCrypto"; symbol = "KJC"; // Declaring seller cut on initalization of the contract sellerCut = 95; } // contstruct the array struct struct TokenAuction { bool isForSale; uint256 tokenIndex; address seller; uint256 sellPrice; uint256 startedAt; } // Only the COO can release new KIMS into the market // We do not have power over the MAXIMUM amount of KIMS that will exist in the future // That was declared when we created the contract // KIMJONGCRYPTO.COM will release KIMS periodically to maintain a healthy market flow function releaseSomeKims(uint256 howMany) external onlyCOO { // We promise not to manipulate the markets, so we take an // average of all the KIMS on sale at any given time uint256 marketAverage = averageKimSalePrice(); for(uint256 counter = 0; counter < howMany; counter++) { // map the token to the tokenOwner tokenToOwner[counter] = this; // Put the KIM out on the market for sale _tokenAuction(kimsCreated, this, marketAverage); // Record the amount of KIMS released kimsCreated++; } } // Don't want to keep this KIM? // Sell KIM then... function sellToken(uint256 tokenIndex, uint256 sellPrice) public { // Which KIM are you selling? TokenAuction storage tokenOnAuction = tokenAuction[tokenIndex]; // Who's selling the KIM, stored into seller variable address seller = msg.sender; // Do you own this kim? require(_owns(seller, tokenIndex)); // Is the KIM already on sale? Can't sell twice! require(tokenOnAuction.isForSale == false); // CLEAR! Send that KIM to Auction! _tokenAuction(tokenIndex, seller, sellPrice); } // INTERNAL FUNCTION, USED ONLY FROM WITHIN THE CONTRACT function _tokenAuction(uint256 tokenIndex, address seller, uint256 sellPrice) internal { // Set the Auction Struct to ON SALE tokenAuction[tokenIndex] = TokenAuction(true, tokenIndex, seller, sellPrice, now); // Fire the Auction Created Event, tell the whole wide world! TokenAuctionCreated(tokenIndex, seller, sellPrice); // Increase the amount of KIMS being sold! kimsOnAuction++; } // Like a KIM? // BUY IT! function buyKim(uint256 tokenIndex) public payable { // Store the KIM in question into tokenOnAuction variable TokenAuction storage tokenOnAuction = tokenAuction[tokenIndex]; // How much is this KIM on sale for? uint256 sellPrice = tokenOnAuction.sellPrice; // Is the KIM even on sale? No monkey business! require(tokenOnAuction.isForSale == true); // You are going to have to pay for this KIM! make sure you send enough ether! require(msg.value >= sellPrice); // Who's selling their KIM? address seller = tokenOnAuction.seller; // Who's trying to buy this KIM? address buyer = msg.sender; // CLEAR! // Complete the auction! And transfer the KIM! _completeAuction(tokenIndex, seller, buyer, sellPrice); } // INTERNAL FUNCTION, USED ONLY FROM WITHIN THE CONTRACT function _completeAuction(uint256 tokenIndex, address seller, address buyer, uint256 sellPrice) internal { // Store the contract address address thisContract = this; // How much commision will the Auction House take? uint256 auctioneerCut = _computeCut(sellPrice); // How much will the seller take home? uint256 sellerProceeds = sellPrice - auctioneerCut; // If the KIM is being sold by the Auction House, then do this... if (seller == thisContract) { // Give the funds to the House pendingWithdrawals[seller] += sellerProceeds + auctioneerCut; // Close the Auction tokenAuction[tokenIndex] = TokenAuction(false, tokenIndex, 0, 0, 0); // Anounce it to the world! TokenAuctionCompleted(tokenIndex, seller, buyer, sellPrice); } else { // If the KIM is being sold by an Individual, then do this... // Give the funds to the seller pendingWithdrawals[seller] += sellerProceeds; // Give the funds to the House pendingWithdrawals[this] += auctioneerCut; // Close the Auction tokenAuction[tokenIndex] = TokenAuction(false, tokenIndex, 0, 0, 0); // Anounce it to the world! TokenAuctionCompleted(tokenIndex, seller, buyer, sellPrice); } _transfer(seller, buyer, tokenIndex); kimsOnAuction--; } // Don't want to sell KIM anymore? // Cancel Auction function cancelKimAuction(uint kimIndex) public { require(_owns(msg.sender, kimIndex)); // Store the KIM in question into tokenOnAuction variable TokenAuction storage tokenOnAuction = tokenAuction[kimIndex]; // Is the KIM even on sale? No monkey business! require(tokenOnAuction.isForSale == true); // Close the Auction tokenAuction[kimIndex] = TokenAuction(false, kimIndex, 0, 0, 0); } // INTERNAL FUNCTION, USED ONLY FROM WITHIN THE CONTRACT // Use this function to find out how much the AuctionHouse will take from this Transaction // All funds go to KIMJONGCRYPTO BCD(BLOCKCHAIN DEVS)! function _computeCut(uint256 sellPrice) internal view returns (uint) { return sellPrice * sellerCut / 1000; } // INTERNAL FUNCTION, USED ONLY FROM WITHIN THE CONTRACT function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Subtract from the sender balanceOf[_from]--; // Add to the reciever balanceOf[_to]++; // map the token to the tokenOwner tokenToOwner[_value] = _to; Transfer(_from, _to, 1); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ // Go ahead and give away a KIM as a gift! function transfer(address _to, uint256 _value) public { require(_owns(msg.sender, _value)); _transfer(msg.sender, _to, _value); } // this function returns bool of owenrship over the token. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return tokenToOwner[_tokenId] == _claimant; } // How much are KIMS really going for now a days? // Run this function and find out! function averageKimSalePrice() public view returns (uint256) { uint256 sumOfAllKimAuctions = 0; if (kimsOnAuction == 0){ return 0; } else { for (uint256 i = 0; i <= kimsOnAuction; i++) { sumOfAllKimAuctions += tokenAuction[i].sellPrice; } return sumOfAllKimAuctions / kimsOnAuction; } } // this function serves for users to withdraw their ethereum function withdraw() { uint amount = pendingWithdrawals[msg.sender]; require(amount > 0); // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); Withdrawal(msg.sender, amount); } // @dev Allows the CFO to capture the balance available to the contract. function withdrawBalance() external onlyCFO { uint balance = pendingWithdrawals[this]; pendingWithdrawals[this] = 0; cfoAddress.transfer(balance); Withdrawal(cfoAddress, balance); } }
this function serves for users to withdraw their ethereum Remember to zero the pending refund before sending to prevent re-entrancy attacks
function withdraw() { uint amount = pendingWithdrawals[msg.sender]; require(amount > 0); pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); Withdrawal(msg.sender, amount); }
12,761,695
./full_match/333000333/0xD5f447E44C5Cc501aF226A71346db8873A643211/sources/contracts/TorusNFT.sol
Overrides ERC721A function for retrieving the ERC2771 message sender/
function _msgSenderERC721A() internal view override returns (address signer) { signer = msg.sender; if (msg.data.length >= 20 && isTrustedForwarder(signer)) { assembly { signer := shr(96, calldataload(sub(calldatasize(), 20))) } } }
9,556,011
contract ChequeOperator { using SafeMath for uint256; using ECRecovery for bytes32; struct Agreement { uint256 totalPaid; address token; address payer; address beneficiary; bytes data; } mapping(bytes => Agreement) internal agreements; mapping(address => mapping(uint256 => bool)) public usedNonces; // For simple sendByCheque /* Simple send by Checque */ function signerOfSimpleCheque(address _token, address _to, uint256 _amount, bytes _data, uint256 _nonce, bytes _sig) private pure returns (address) { return keccak256(abi.encodePacked(_token, _to, _amount, _data, _nonce)).toEthSignedMessageHash().recover(_sig); } function sendByCheque(address _token, address _to, uint256 _amount, bytes _data, uint256 _nonce, bytes _sig) public { require(_to != address(this)); // Check if signature is valid and get signer's address address signer = signerOfSimpleCheque(_token, _to, _amount, _data, _nonce, _sig); require(signer != address(0)); // Mark this cheque as used require (!usedNonces[signer][_nonce]); usedNonces[signer][_nonce] = true; // Send tokens ERC777Token token = ERC777Token(_token); token.operatorSend(signer, _to, _amount, _data, ""); } /* Send by Aggreement */ function signerOfAgreementCheque(bytes _agreementId, uint256 _amount, uint256 _fee, bytes _sig) private pure returns (address) { return keccak256(abi.encodePacked(_agreementId, _amount, _fee)).toEthSignedMessageHash().recover(_sig); } function createAgreement(bytes _id, address _token, address _payer, address _beneficiary, bytes _data) public { require(_beneficiary != address(0)); require(_payer != address(0)); //require(ERC777Token(_token)); require(agreements[_id].beneficiary == address(0)); agreements[_id] = Agreement({ totalPaid: 0, token: _token, payer: _payer, beneficiary: _beneficiary, data: _data }); } function sendByAgreement(bytes _agreementId, uint256 _amount, uint256 _fee, bytes _sig) public returns (bool) { // Check if agreement exists Agreement storage agreement = agreements[_agreementId]; require(agreement.beneficiary != address(0)); // Check if signature is valid, remember last running sum address signer = signerOfAgreementCheque(_agreementId, _amount, _fee, _sig); require(signer == agreement.payer); // Calculate amount of tokens to be send uint256 amount = _amount.sub(agreement.totalPaid).sub(_fee); require(amount > 0); // If signer has less tokens that asked to transfer, we can transfer as much as he has already // and rest tokens can be transferred via same cheque but in another tx // when signer will top up his balance. ERC777Token token = ERC777Token(agreement.token); if (amount > token.balanceOf(signer)) { amount = token.balanceOf(signer).sub(_fee); } // Increase already paid amount agreement.totalPaid = agreement.totalPaid.add(amount); // Send tokens token.operatorSend(signer, agreement.beneficiary, amount, agreement.data, ""); if (_fee > 0) { token.operatorSend(signer, msg.sender, _fee, "", ""); } return true; } } contract MyToken is ERC777Token { using ECRecovery for bytes32; mapping (address => mapping (uint256 => bool)) private usedNonces; constructor(address _checqueOperator) public { // Setting checquieOperator as default operator //require(ChequeOperator(_checqueOperator)); mDefaultOperators.push(_checqueOperator); mIsDefaultOperator[_checqueOperator] = true; } }
Check if signature is valid and get signer's address Mark this cheque as used Send tokens
function sendByCheque(address _token, address _to, uint256 _amount, bytes _data, uint256 _nonce, bytes _sig) public { require(_to != address(this)); address signer = signerOfSimpleCheque(_token, _to, _amount, _data, _nonce, _sig); require(signer != address(0)); require (!usedNonces[signer][_nonce]); usedNonces[signer][_nonce] = true; ERC777Token token = ERC777Token(_token); token.operatorSend(signer, _to, _amount, _data, ""); }
7,237,096
// SPDX-License-Identifier:MIT pragma solidity 0.8.10; import "./IERC20.sol"; contract CredefiToken is IERC20 { // bytes32 private constant EIP712DOMAIN_HASH = // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") bytes32 private constant EIP712DOMAIN_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; // bytes32 private constant NAME_HASH = keccak256("Credi") bytes32 private constant NAME_HASH = 0x3c5eac0879bc46be0fe2a2701e57d8e6edcaa427c79074f4513eb9572ff50507; // bytes32 private constant VERSION_HASH = keccak256("1") bytes32 private constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6; // bytes32 public constant PERMIT_TYPEHASH = // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; // bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)"); bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; string public constant name = "CREDI"; string public constant symbol = "CREDI"; uint8 public constant decimals = 18; address public timelock; uint256 public override totalSupply; mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) public override allowance; // ERC-2612, ERC-3009 state mapping(address => uint256) public nonces; mapping(address => mapping(bytes32 => bool)) public authorizationState; event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event TimelockUpdated(address indexed timelock); modifier onlyTimelock() { require(msg.sender == address(timelock), "CREDI:NOT_TIMELOCK"); _; } constructor(address _timelock) { _changeTimelock(_timelock); } function changeTimelock(address _timelock) external onlyTimelock { _changeTimelock(_timelock); } function mint(address to, uint256 value) external onlyTimelock returns (bool) { _mint(to, value); return true; } function burn(uint256 value) external returns (bool) { _burn(msg.sender, value); return true; } function approve(address spender, uint256 value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom( address from, address to, uint256 value ) external override returns (bool) { uint256 fromAllowance = allowance[from][msg.sender]; if (fromAllowance != type(uint256).max) { // Allowance is implicitly checked with Solidity's underflow protection allowance[from][msg.sender] = fromAllowance - value; } _transfer(from, to, value); return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, "CREDI:AUTH_EXPIRED"); bytes32 encodeData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner], deadline)); nonces[owner] = nonces[owner] + 1; _validateSignedData(owner, encodeData, v, r, s); _approve(owner, spender, value); } function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { require(block.timestamp > validAfter, "CREDI:AUTH_NOT_YET_VALID"); require(block.timestamp < validBefore, "CREDI:AUTH_EXPIRED"); require(!authorizationState[from][nonce], "CREDI:AUTH_ALREADY_USED"); bytes32 encodeData = keccak256( abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce) ); _validateSignedData(from, encodeData, v, r, s); authorizationState[from][nonce] = true; emit AuthorizationUsed(from, nonce); _transfer(from, to, value); } function getChainId() public view returns (uint256 chainId) { // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } function getDomainSeparator() public view returns (bytes32) { return keccak256(abi.encode(EIP712DOMAIN_HASH, NAME_HASH, VERSION_HASH, getChainId(), address(this))); } function _changeTimelock(address _timelock) internal { timelock = _timelock; emit TimelockUpdated(_timelock); } function _validateSignedData( address signer, bytes32 encodeData, uint8 v, bytes32 r, bytes32 s ) internal view { bytes32 digest = keccak256(abi.encodePacked("\x19\x01", getDomainSeparator(), encodeData)); address recoveredAddress = ecrecover(digest, v, r, s); // Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages require(recoveredAddress != address(0) && recoveredAddress == signer, "CREDI:INVALID_SIGNATURE"); } function _mint(address to, uint256 value) internal { totalSupply = totalSupply + value; balanceOf[to] = balanceOf[to] + value; emit Transfer(address(0), to, value); } function _burn(address from, uint256 value) internal { // Balance is implicitly checked with Solidity's underflow protection balanceOf[from] = balanceOf[from] - value; totalSupply = totalSupply - value; emit Transfer(from, address(0), value); } function _approve( address owner, address spender, uint256 value ) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer( address from, address to, uint256 value ) private { require(to != address(this) && to != address(0), "CREDI:RECEIVER_IS_TOKEN_OR_ZERO"); // Balance is implicitly checked with Solidity's underflow protection balanceOf[from] = balanceOf[from] - value; balanceOf[to] = balanceOf[to] + value; emit Transfer(from, to, value); } }
solhint-disable-next-line no-inline-assembly
function getChainId() public view returns (uint256 chainId) { assembly { chainId := chainid() } }
199,465
./partial_match/42/0xdF6c055ff856fd42d13DAF5bCa489E267AAB0376/sources/MasterChef.sol
Deposit LP tokens to MasterChef for PICKLE allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accTokenPerShare) .div(1e12) .sub(user.rewardDebt); if (pending > 0) { safeTokenTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.transferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
8,944,232
/** *Submitted for verification at Etherscan.io on 2021-02-23 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC165 { /** * @dev Returns true ifa 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); } 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; } 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); } 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); } 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); } abstract contract ERC165 is IERC165 { /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(type(IERC165).interfaceId); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library 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)); } } library EnumerableMap { // 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 MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @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) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @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) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry 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. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @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._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.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) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @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) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @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) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @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) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // 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)))); } } library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits; temp = value; while (temp != 0) { buffer[--index] = bytes1(uint8(48 + uint256(temp % 10))); temp /= 10; } return string(buffer); } } 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; } } } contract Ownable { address private owner; event OwnerSet(address indexed oldOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner, "Caller is not owner"); _; } constructor() { owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor emit OwnerSet(address(0), owner); } function changeOwner(address newOwner) public onlyOwner { emit OwnerSet(owner, newOwner); owner = newOwner; } function getOwner() external view returns (address) { return owner; } } contract ERC721 is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; using Counters for Counters.Counter; // Map the selling contracts that can mint tokens mapping (address => bool) public minters; // Contract that calculates the stake profits address public profitsContract; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; struct Coin { address tokenAddress; string symbol; string name; } mapping (uint256 => Coin) public tradeCoins; struct assetType { uint64 maxAmount; uint64 mintedAmount; uint64 coinIndex; string copyright; } mapping (uint256 => assetType) public assetsByType; struct assetDetail { uint256 value; uint32 lastTrade; uint32 lastPayment; uint32 typeDetail; uint32 customDetails; } mapping (uint256 => assetDetail) assetsDetails; address public sellingContract; uint256 public polkaCitizens = 0; // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; Counters.Counter private _tokenIdTracker; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor () { _name ="Polka City 3D Asset"; _symbol = "PC3D"; _baseURI = "https://polkacity.app/3dnftassets/"; // include ETH as coin tradeCoins[1].tokenAddress = address(0x0); tradeCoins[1].symbol = "ETH"; tradeCoins[1].name = "Ethereum"; // include POLC as coin tradeCoins[2].tokenAddress = 0x0daD676DA510e71e31464A765a8548b47f47bdad; tradeCoins[2].symbol = "POLC"; tradeCoins[2].name = "Polka City Token"; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(type(IERC721).interfaceId); _registerInterface(type(IERC721Metadata).interfaceId); _registerInterface(type(IERC721Enumerable).interfaceId); } function initAssets(uint64 _assetType, uint64 _maxAmount, uint64 _coinIndex, string memory _copyright) private { assetsByType[_assetType].maxAmount = _maxAmount; assetsByType[_assetType].mintedAmount = 0; assetsByType[_assetType].coinIndex = _coinIndex; assetsByType[_assetType].copyright = _copyright; } /** * @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 _holderTokens[_owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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 base = baseURI(); return string(abi.encodePacked(base,( uint256(assetsDetails[tokenId].customDetails).toString()))); } function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address _owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[_owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return (tokenId); } function getTokenDetails(uint256 index) public view returns (uint32 aType, uint32 customDetails, uint32 lastTx, uint32 lastPayment, uint256 initialvalue, string memory coin) { uint256 coinIndex = uint256(assetsByType[(assetsDetails[index].typeDetail)].coinIndex); return ( assetsDetails[index].typeDetail, assetsDetails[index].customDetails, assetsDetails[index].lastTrade, assetsDetails[index].lastPayment, assetsDetails[index].value, tradeCoins[coinIndex].symbol ); } /** * @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(msg.sender == _owner || ERC721.isApprovedForAll(_owner, msg.sender), "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 != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, 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(msg.sender, 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(msg.sender, 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 _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address _owner = ERC721.ownerOf(tokenId); return (spender == _owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(_owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, 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"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); assetsDetails[tokenId].lastTrade = uint32(block.timestamp); assetsDetails[tokenId].lastPayment = uint32(block.timestamp); checkCitizen(to, true); checkCitizen(from, false); emit Transfer(from, to, tokenId); } function setBaseURI(string memory baseURI_) public onlyOwner { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } function checkCitizen(address _citizen, bool _addAsset) private { uint256 citizenBalance = _holderTokens[_citizen].length(); if (citizenBalance > 0) { if (_addAsset == true && citizenBalance == 1) { polkaCitizens++; } } else { polkaCitizens--; } } function mint(address to, uint32 _assetType, uint256 _value, uint32 _customDetails) public virtual returns (bool success) { require(minters[msg.sender] == true, "Not allowed"); require(assetsByType[_assetType].maxAmount > assetsByType[_assetType].mintedAmount, "Max mintable amount reached for this asset" ); uint256 curIndex = _tokenIdTracker.current(); _mint(to, curIndex); assetsDetails[curIndex].typeDetail = _assetType; assetsDetails[curIndex].value = _value; assetsDetails[curIndex].lastTrade = uint32(block.timestamp); assetsDetails[curIndex].lastPayment = uint32(block.timestamp); assetsDetails[curIndex].customDetails = _customDetails; assetsByType[_assetType].mintedAmount += 1; _tokenIdTracker.increment(); checkCitizen(to, true); return true; } function setMinter(address _minterAddress, bool _canMint) public onlyOwner { minters[_minterAddress] = _canMint; } function setProfitsContract(address _contract) public onlyOwner { profitsContract = _contract; } function setPaymentDate(uint256 _asset) public { require(msg.sender == profitsContract); assetsDetails[_asset].lastPayment = uint32(block.timestamp); } function addAssetType(uint64 _assetType, uint64 _maxAmount, uint64 _coinIndex, string memory _copyright) public onlyOwner { require(_maxAmount > 0); initAssets( _assetType, _maxAmount, _coinIndex, _copyright); } function modifyAssetType(uint64 _typeId, uint64 _maxAmount, uint64 _coinIndex, string memory _copyright) public onlyOwner { assetsByType[_typeId].copyright = _copyright; assetsByType[_typeId].maxAmount = _maxAmount; assetsByType[_typeId].coinIndex = _coinIndex; } function fixAsset(uint256 _assetId, uint32 _customDetails) public { require(minters[msg.sender] == true, "Not allowed"); assetsDetails[_assetId].customDetails = _customDetails; } function addCoin(uint256 _coinIndex, address _tokenAddress, string memory _tokenSymbol, string memory _tokenName) public onlyOwner { tradeCoins[_coinIndex].tokenAddress = _tokenAddress; tradeCoins[_coinIndex].symbol = _tokenSymbol; tradeCoins[_coinIndex].name = _tokenName; } }
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 base = baseURI(); return string(abi.encodePacked(base,( uint256(assetsDetails[tokenId].customDetails).toString()))); }
334,682
pragma solidity ^0.4.24; // Token name: HyperChipToken // Symbol: HYCT // Decimals: 8 // Twitter : @HyperChipToken interface tokenRecipient { function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; 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); } contract HyperChipToken { // Public variables of the token string public name = "HyperChipToken"; string public symbol = "HYCT"; uint8 public decimals = 8; uint256 public unitsOneEthCanBuy = 10000000000000; uint256 public totalEthInWei = 5000000; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply = 500; address public fundsWallet; // 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); function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOf[_owner]; } /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function Constructor(uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balanceOf[fundsWallet] >= amount); balanceOf[fundsWallet] = balanceOf[fundsWallet] - amount; balanceOf[msg.sender] = balanceOf[msg.sender] + amount; emit Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender&#39;s allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
Transfer ether to fundsWallet
function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balanceOf[fundsWallet] >= amount); balanceOf[fundsWallet] = balanceOf[fundsWallet] - amount; balanceOf[msg.sender] = balanceOf[msg.sender] + amount; fundsWallet.transfer(msg.value); }
6,590,670
// SPDX-License-Identifier: MIT pragma solidity ^0.6.6; contract Review { // deployer address address payable public author; constructor() public { author = msg.sender; } // holds some useful pieces of information related to an item which can be // reviewed by registered reviewers present in dApp ecosystem struct Thing { bytes32 id; string name; string description; uint8 rate; uint256 rateCount; mapping(address => uint8) rates; uint256 reviewCount; mapping(address => string) reviews; } // holding some useful pieces of information related to one // registered user in dApp ecosystem // // All {things} created by this user, to be reviewed by dApp participants, stored in blockchain // // All reviews & rating done by user to be stored on blockchain struct User { string name; bool created; uint256 thingCount; mapping(uint256 => bytes32) things; uint256 rateCount; mapping(uint256 => bytes32) rates; uint256 reviewCount; mapping(uint256 => bytes32) reviews; } uint256 thingCount; mapping(bytes32 => Thing) things; uint256 userCount; mapping(address => User) users; mapping(bytes32 => address) thingsToUser; // access control to certain ops modifier onlyAuthor() { require(msg.sender == author, "You're not author !"); _; } // checks whether a given address is registered in dApp or not function isAddressRegistered(address _addr) public view onlyAuthor returns (bool) { return users[_addr].created; } // checks whether function invoker i.e. msg.sender is registered or not function amIRegistered() public view returns (bool) { return users[msg.sender].created; } modifier addressRegistered(address _addr) { require(users[_addr].created, "Address not registered yet !"); _; } // given that a certain account ( _addr ) already registered, // it'll lookup user name by address // // person looking up information, also must be registered in dApp function userNameByAddress(address _addr) public view addressRegistered(msg.sender) addressRegistered(_addr) returns (string memory) { return users[_addr].name; } // looks up user name of msg.sender function myUserName() public view returns (string memory) { return userNameByAddress(msg.sender); } // given address of account holder, #-of things to // be reviewed created by user gets returned function thingCountByAddress(address _addr) public view addressRegistered(_addr) addressRegistered(msg.sender) returns (uint256) { return users[_addr].thingCount; } // returns #-of items to be reviewed, created by msg.sender function myThingCount() public view returns (uint256) { return thingCountByAddress(msg.sender); } // given address of account holder & index of thing we want to look up, // we'll return unique identifier for that thing function thingByAddressAndIndex(address _addr, uint256 _index) public view addressRegistered(_addr) addressRegistered(msg.sender) returns (bytes32) { require( _index >= 0 && _index < users[_addr].thingCount, "Invalid id of thing !" ); return users[_addr].things[_index]; } // returns thing identifier, given index of that thing, from msg.sender's account function myThingByIndex(uint256 _index) public view returns (bytes32) { return thingByAddressAndIndex(msg.sender, _index); } // given address of account holder, returns #-of things // rated by user function rateCountByAddress(address _addr) public view addressRegistered(_addr) addressRegistered(msg.sender) returns (uint256) { return users[_addr].rateCount; } // returns #-of items rated by user, where user == msg.sender function myRateCount() public view returns (uint256) { return rateCountByAddress(msg.sender); } // given address of account holder & index of rated thing, // we'll look up unique identifier associated with rated item // for given user with address `_addr` function ratedThingByAddressAndIndex(address _addr, uint256 _index) public view addressRegistered(_addr) addressRegistered(msg.sender) returns (bytes32) { require( _index >= 0 && _index < users[_addr].rateCount, "Invalid id of rated thing !" ); return users[_addr].rates[_index]; } // returns rated thing identifier, given index of that thing, // from msg.sender's account function myRatedThingByIndex(uint256 _index) public view returns (bytes32) { return ratedThingByAddressAndIndex(msg.sender, _index); } // given address of account holder, returns #-of things // reviewed by user function reviewCountByAddress(address _addr) public view addressRegistered(_addr) addressRegistered(msg.sender) returns (uint256) { return users[_addr].reviewCount; } // returns #-of items reviewed by user, where user == msg.sender function myReviewCount() public view returns (uint256) { return reviewCountByAddress(msg.sender); } // given address of account holder & index of rated thing, // we'll look up unique identifier associated with reviewed item // for given user with address `_addr` function reviewedThingByAddressAndIndex(address _addr, uint256 _index) public view addressRegistered(_addr) addressRegistered(msg.sender) returns (bytes32) { require( _index >= 0 && _index < users[_addr].reviewCount, "Invalid id of reviewed thing !" ); return users[_addr].reviews[_index]; } // returns reviewed thing identifier, given index of that thing, // from msg.sender's account function myReviewedThingByIndex(uint256 _index) public view returns (bytes32) { return reviewedThingByAddressAndIndex(msg.sender, _index); } }
looks up user name of msg.sender
function myUserName() public view returns (string memory) { return userNameByAddress(msg.sender); }
12,868,324
// 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/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/cryptography/ECDSA.sol pragma solidity ^0.5.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * (.note) This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * (.warning) `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise) * be too long), and then calling `toEthSignedMessageHash` on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 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) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * [`eth_sign`](https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign) * JSON-RPC method. * * See `recover`. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: contracts/ColendiScore.sol pragma solidity ^0.5.11; contract ColendiScore is Ownable{ using ECDSA for bytes32; /*** EVENTS ***/ event LogScoreUpdate(bytes32 queryId); /*** DATA TYPES ***/ struct ScoreQuery { address requestor; address user; uint32 score; uint256 updateTime; bytes32 IPFSHash; } struct OwnScoreQuery { address user; uint32 score; uint256 updateTime; } /*** STORAGE ***/ /// @dev Addres of Colendi Controller Account address public scoreController; /// @dev User to Current Nonces mapping(address => uint256) currentNonce; /// @dev IPFS Hashes to Score Query mapping(bytes32 => ScoreQuery) scoreQueries; /// @dev IPFS Hashes to Score Query mapping(bytes32 => OwnScoreQuery) ownScoreQueries; /// @dev Cost of score query in terms of COD. Initially 10 COD uint256 public queryCost = 10**19; /// @dev Colendi Token Contract ERC20 colendiToken; /*** MODIFIER ***/ modifier onlyScoreController(){ require(msg.sender == scoreController, "Only colendi score controller can execute this transaction"); _; } /// @dev Modifier that checks validity of signature modifier hasValidProof(bytes memory sig, address userAddr, uint256 nonce){ require(nonce == currentNonce[userAddr], "Not a valid nonce"); // recover address from signed message address recoveredUserAddr = recoverSigner(userAddr,nonce,sig); // compare recover address and request address require(recoveredUserAddr == userAddr, "Unmatched signature"); _; } /*** FUNCTIONS ***/ /// @dev Method that returns the address of signer /// @param userAddr Address of the user /// @param nonce Current nonce of user /// @param signature Complete value of signature as 65 bytes /// @return Address of the signer function recoverSigner(address userAddr, uint256 nonce, bytes memory signature) public view returns(address recoveredAddress){ bytes32 _hashOfMsg = calculateHashWithPrefix(userAddr,nonce); recoveredAddress = _hashOfMsg.recover(signature); } /// @dev Method that returns the address of signer /// @param userAddr Address of the user whose score is being requested /// @param nonce Current nonce of user /// @return Hash of the message with append of ethereum prefixed message function calculateHashWithPrefix(address userAddr, uint256 nonce) public view returns(bytes32 prefixedHash) { prefixedHash = keccak256(abi.encodePacked(address(this),userAddr,nonce)).toEthSignedMessageHash(); } /// @dev Method that returns query details /// @param queryID Hash of the userAddress and nonce as encoded /// @return All fields of scoreQuery struct function getScoreQuery(bytes32 queryID) external view returns(address requestor, address user, uint32 score, uint256 updateTime, bytes32 IPFSHash){ ScoreQuery memory scoreQuery = scoreQueries[queryID]; requestor = scoreQuery.requestor; user = scoreQuery.user; score = scoreQuery.score; updateTime = scoreQuery.updateTime; IPFSHash = scoreQuery.IPFSHash; } function getOwnScoreQuery(bytes32 queryID) external view returns(address user, uint32 score, uint256 updateTime){ OwnScoreQuery memory ownScoreQuery = ownScoreQueries[queryID]; user = ownScoreQuery.user; score = ownScoreQuery.score; updateTime = ownScoreQuery.updateTime; } /// @dev Method that gets signature, checks the validity of signature and generates oraclize query to get Score of others /// @param signature Complete value of signature as 65 bytes. /// @param userAddr Address of the user whose score is being requested /// @param nonce Current nonce of user to guarentee each signature is used once. /// @param IPFSHash Hash of IPFS which includes Sharee's data as encrypted by Requestee's public key and Requestee's data as encrypted by Sharee's public key. function updateScore(bytes memory signature, address requestor, address userAddr, uint256 nonce, uint32 _score, bytes32 IPFSHash) public hasValidProof(signature, userAddr, nonce) onlyScoreController { require(colendiToken.transferFrom(requestor, address(this), queryCost), "Failed Token Transfer"); bytes32 queryID = keccak256(abi.encodePacked(userAddr, nonce)); scoreQueries[queryID].requestor = requestor; scoreQueries[queryID].user = userAddr; scoreQueries[queryID].score = _score; scoreQueries[queryID].updateTime = now; scoreQueries[queryID].IPFSHash = IPFSHash; currentNonce[userAddr] = nonce + 1; emit LogScoreUpdate(queryID); } /// @dev Method that gets signature as splitted into r,s and v values. Checks the validity of signature and generates oraclize query to get Score of your own. /// @param userAddr Address of the user whose score is being requested /// @param signature Complete value of signature as 65 bytes. /// @param nonce Current nonce of user to guarentee each signature is used once. function updateOwnScore(bytes memory signature, address userAddr, uint256 nonce, uint32 _score) public hasValidProof(signature, userAddr, nonce) onlyScoreController { require(colendiToken.transferFrom(userAddr, address(this), queryCost), "Failed Token Transfer"); bytes32 queryID = keccak256(abi.encodePacked(userAddr, nonce)); ownScoreQueries[queryID].updateTime = now; ownScoreQueries[queryID].user = userAddr; ownScoreQueries[queryID].score = _score; currentNonce[userAddr] = nonce + 1; emit LogScoreUpdate(queryID); } /// @dev Method that gets the current nonce of the user /// @param userAddr Address of the user /// @return Returns the current nonce of the user function getNonceOfUser(address userAddr) external view returns(uint256 nonce){ nonce = currentNonce[userAddr]; } function updateQueryCost(uint256 _queryCost) public onlyScoreController returns(bool) { queryCost = _queryCost; } /// @dev Method no-name which will accept ethers transferred to this contract function () external payable{ } /// @dev Method that transfer CODs back to owner function getCODBack() external onlyScoreController { require(colendiToken.transfer(msg.sender,colendiToken.balanceOf(address(this))), "Unsuccessful COD Transfer"); } /// @dev Method that transfer ethers back to owner function getEthBack() external onlyScoreController { msg.sender.transfer(address(this).balance); } function transferColendiController(address _colendiController) public onlyOwner{ scoreController = _colendiController; } /// @dev Constructor for Score Contract /// @param CODToken Address of COD Token constructor(address CODToken) public { colendiToken = ERC20(CODToken); scoreController = msg.sender; } }
Method that gets signature, checks the validity of signature and generates oraclize query to get Score of others signature Complete value of signature as 65 bytes. userAddr Address of the user whose score is being requested nonce Current nonce of user to guarentee each signature is used once. IPFSHash Hash of IPFS which includes Sharee's data as encrypted by Requestee's public key and Requestee's data as encrypted by Sharee's public key.
function updateScore(bytes memory signature, address requestor, address userAddr, uint256 nonce, uint32 _score, bytes32 IPFSHash) public hasValidProof(signature, userAddr, nonce) onlyScoreController { require(colendiToken.transferFrom(requestor, address(this), queryCost), "Failed Token Transfer"); bytes32 queryID = keccak256(abi.encodePacked(userAddr, nonce)); scoreQueries[queryID].requestor = requestor; scoreQueries[queryID].user = userAddr; scoreQueries[queryID].score = _score; scoreQueries[queryID].updateTime = now; scoreQueries[queryID].IPFSHash = IPFSHash; currentNonce[userAddr] = nonce + 1; emit LogScoreUpdate(queryID); }
5,426,272
// DEPRECATED - This contract is no longer used in production pragma solidity 0.5.11; /** * @title OUSD MixOracle Contract * @notice The MixOracle pulls exchange rate from multiple oracles and returns * min and max values. * @author Origin Protocol Inc */ import { IPriceOracle } from "../interfaces/IPriceOracle.sol"; import { IEthUsdOracle } from "../interfaces/IEthUsdOracle.sol"; import { IMinMaxOracle } from "../interfaces/IMinMaxOracle.sol"; import { Governable } from "../governance/Governable.sol"; contract MixOracle is IMinMaxOracle, Governable { event DriftsUpdated(uint256 _minDrift, uint256 _maxDrift); event EthUsdOracleRegistered(address _oracle); event EthUsdOracleDeregistered(address _oracle); event TokenOracleRegistered( string symbol, address[] ethOracles, address[] usdOracles ); address[] public ethUsdOracles; struct MixConfig { address[] usdOracles; address[] ethOracles; } mapping(bytes32 => MixConfig) configs; uint256 constant MAX_INT = 2**256 - 1; uint256 public maxDrift; uint256 public minDrift; constructor(uint256 _maxDrift, uint256 _minDrift) public { maxDrift = _maxDrift; minDrift = _minDrift; emit DriftsUpdated(_minDrift, _maxDrift); } function setMinMaxDrift(uint256 _minDrift, uint256 _maxDrift) public onlyGovernor { minDrift = _minDrift; maxDrift = _maxDrift; emit DriftsUpdated(_minDrift, _maxDrift); } /** * @notice Adds an oracle to the list of oracles to pull data from. * @param oracle Address of an oracle that implements the IEthUsdOracle interface. **/ function registerEthUsdOracle(address oracle) public onlyGovernor { for (uint256 i = 0; i < ethUsdOracles.length; i++) { require(ethUsdOracles[i] != oracle, "Oracle already registered."); } ethUsdOracles.push(oracle); emit EthUsdOracleRegistered(oracle); } /** * @notice Removes an oracle to the list of oracles to pull data from. * @param oracle Address of an oracle that implements the IEthUsdOracle interface. **/ function unregisterEthUsdOracle(address oracle) public onlyGovernor { for (uint256 i = 0; i < ethUsdOracles.length; i++) { if (ethUsdOracles[i] == oracle) { // swap with the last element of the array, and then delete last element (could be itself) ethUsdOracles[i] = ethUsdOracles[ethUsdOracles.length - 1]; delete ethUsdOracles[ethUsdOracles.length - 1]; emit EthUsdOracleDeregistered(oracle); ethUsdOracles.pop(); return; } } revert("Oracle not found"); } /** * @notice Adds an oracle to the list of oracles to pull data from. * @param ethOracles Addresses of oracles that implements the IEthUsdOracle interface and answers for this asset * @param usdOracles Addresses of oracles that implements the IPriceOracle interface and answers for this asset **/ function registerTokenOracles( string calldata symbol, address[] calldata ethOracles, address[] calldata usdOracles ) external onlyGovernor { MixConfig storage config = configs[keccak256(abi.encodePacked(symbol))]; config.ethOracles = ethOracles; config.usdOracles = usdOracles; emit TokenOracleRegistered(symbol, ethOracles, usdOracles); } /** * @notice Returns the min price of an asset in USD. * @return symbol Asset symbol. Example: "DAI" * @return price Min price from all the oracles, in USD with 8 decimal digits. **/ function priceMin(string calldata symbol) external view returns (uint256 price) { MixConfig storage config = configs[keccak256(abi.encodePacked(symbol))]; uint256 ep; uint256 p; //holder variables price = MAX_INT; if (config.ethOracles.length > 0) { ep = MAX_INT; for (uint256 i = 0; i < config.ethOracles.length; i++) { p = IEthUsdOracle(config.ethOracles[i]).tokEthPrice(symbol); if (ep > p) { ep = p; } } price = ep; ep = MAX_INT; for (uint256 i = 0; i < ethUsdOracles.length; i++) { p = IEthUsdOracle(ethUsdOracles[i]).ethUsdPrice(); if (ep > p) { ep = p; } } if (price != MAX_INT && ep != MAX_INT) { // tokEthPrice has precision of 8 which ethUsdPrice has precision of 6 // we want precision of 8 price = (price * ep) / 1e6; } } if (config.usdOracles.length > 0) { for (uint256 i = 0; i < config.usdOracles.length; i++) { // upscale by 2 since price oracles are precision 6 p = IPriceOracle(config.usdOracles[i]).price(symbol) * 1e2; if (price > p) { price = p; } } } require(price <= maxDrift, "Price exceeds maxDrift"); require(price >= minDrift, "Price below minDrift"); require( price != MAX_INT, "None of our oracles returned a valid min price!" ); } /** * @notice Returns max price of an asset in USD. * @return symbol Asset symbol. Example: "DAI" * @return price Max price from all the oracles, in USD with 8 decimal digits. **/ function priceMax(string calldata symbol) external view returns (uint256 price) { MixConfig storage config = configs[keccak256(abi.encodePacked(symbol))]; uint256 ep; uint256 p; //holder variables price = 0; if (config.ethOracles.length > 0) { ep = 0; for (uint256 i = 0; i < config.ethOracles.length; i++) { p = IEthUsdOracle(config.ethOracles[i]).tokEthPrice(symbol); if (ep < p) { ep = p; } } price = ep; ep = 0; for (uint256 i = 0; i < ethUsdOracles.length; i++) { p = IEthUsdOracle(ethUsdOracles[i]).ethUsdPrice(); if (ep < p) { ep = p; } } if (price != 0 && ep != 0) { // tokEthPrice has precision of 8 which ethUsdPrice has precision of 6 // we want precision of 8 price = (price * ep) / 1e6; } } if (config.usdOracles.length > 0) { for (uint256 i = 0; i < config.usdOracles.length; i++) { // upscale by 2 since price oracles are precision 6 p = IPriceOracle(config.usdOracles[i]).price(symbol) * 1e2; if (price < p) { price = p; } } } require(price <= maxDrift, "Price exceeds maxDrift"); require(price >= minDrift, "Price below minDrift"); require(price != 0, "None of our oracles returned a valid max price!"); } /** * @notice Returns the length of the usdOracles array for a given token * @param symbol Asset symbol. Example: "DAI" * @return length of the USD oracles array **/ function getTokenUSDOraclesLength(string calldata symbol) external view returns (uint256) { MixConfig storage config = configs[keccak256(abi.encodePacked(symbol))]; return config.usdOracles.length; } /** * @notice Returns the address of a specific USD oracle * @param symbol Asset symbol. Example: "DAI" * @param idx Index of the array value to return * @return address of the oracle **/ function getTokenUSDOracle(string calldata symbol, uint256 idx) external view returns (address) { MixConfig storage config = configs[keccak256(abi.encodePacked(symbol))]; return config.usdOracles[idx]; } /** * @notice Returns the length of the ethOracles array for a given token * @param symbol Asset symbol. Example: "DAI" * @return length of the ETH oracles array **/ function getTokenETHOraclesLength(string calldata symbol) external view returns (uint256) { MixConfig storage config = configs[keccak256(abi.encodePacked(symbol))]; return config.ethOracles.length; } /** * @notice Returns the address of a specific ETH oracle * @param symbol Asset symbol. Example: "DAI" * @param idx Index of the array value to return * @return address of the oracle **/ function getTokenETHOracle(string calldata symbol, uint256 idx) external view returns (address) { MixConfig storage config = configs[keccak256(abi.encodePacked(symbol))]; return config.ethOracles[idx]; } }
Returns the min price of an asset in USD. return symbol Asset symbol. Example: "DAI" return price Min price from all the oracles, in USD with 8 decimal digits./ tokEthPrice has precision of 8 which ethUsdPrice has precision of 6 we want precision of 8 upscale by 2 since price oracles are precision 6
function priceMin(string calldata symbol) external view returns (uint256 price) { MixConfig storage config = configs[keccak256(abi.encodePacked(symbol))]; uint256 ep; price = MAX_INT; if (config.ethOracles.length > 0) { ep = MAX_INT; for (uint256 i = 0; i < config.ethOracles.length; i++) { p = IEthUsdOracle(config.ethOracles[i]).tokEthPrice(symbol); if (ep > p) { ep = p; } } price = ep; ep = MAX_INT; for (uint256 i = 0; i < ethUsdOracles.length; i++) { p = IEthUsdOracle(ethUsdOracles[i]).ethUsdPrice(); if (ep > p) { ep = p; } } if (price != MAX_INT && ep != MAX_INT) { price = (price * ep) / 1e6; } } if (config.usdOracles.length > 0) { for (uint256 i = 0; i < config.usdOracles.length; i++) { p = IPriceOracle(config.usdOracles[i]).price(symbol) * 1e2; if (price > p) { price = p; } } } require(price <= maxDrift, "Price exceeds maxDrift"); require(price >= minDrift, "Price below minDrift"); require( price != MAX_INT, "None of our oracles returned a valid min price!" ); }
914,871
./full_match/80001/0x2d3B52Ab8233f29c7F189B6AAbD4AF8de3036cC4/sources/contracts/mixins/MixinLockMetadata.sol
Gets the token symbol return string representing the token name/
function symbol() external view returns (string memory) { if (bytes(lockSymbol).length == 0) { return unlockProtocol.globalTokenSymbol(); return lockSymbol; } }
9,435,293
./full_match/28/0x65b840CdEFc7e10B1839E52aFB54b8F7daA1C55D/sources/contracts/MToken/MToken.sol
The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator. borrower The borrower of this MToken to be liquidated mTokenCollateral The market in which to seize collateral from the borrower repayAmount The amount of the underlying borrowed asset to repay return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount./ accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
function liquidateBorrowInternal( address borrower, uint256 repayAmount, MTokenInterface mTokenCollateral ) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { return ( fail( Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED ), 0 ); } error = mTokenCollateral.accrueInterest(); if (error != uint256(Error.NO_ERROR)) { return ( fail( Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED ), 0 ); } liquidateBorrowFresh( msg.sender, borrower, repayAmount, mTokenCollateral ); }
16,364,637
pragma solidity ^0.5.3; pragma solidity ^0.5.3; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } contract KittyCoreInterface is ERC721 { uint256 public autoBirthFee; address public saleAuction; address public siringAuction; function breedWithAuto(uint256 _matronId, uint256 _sireId) public payable; function createSaleAuction(uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external; function createSiringAuction(uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external; function supportsInterface(bytes4 _interfaceID) external view returns (bool); } contract AuctionInterface { function cancelAuction(uint256 _tokenId) external; } contract Ownable { address payable public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor(address payable _owner) public { if(_owner == address(0)) { owner = msg.sender; } else { owner = _owner; } } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address payable _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function destroy() public onlyOwner { selfdestruct(owner); } function destroyAndSend(address payable _recipient) public onlyOwner { selfdestruct(_recipient); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; constructor(address payable _owner) Ownable(_owner) public {} modifier whenNotPaused() { require(!paused, "Contract paused"); _; } modifier whenPaused() { require(paused, "Contract should be paused"); _; } function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } contract CKProxy is Pausable { KittyCoreInterface public kittyCore; AuctionInterface public saleAuction; AuctionInterface public siringAuction; constructor(address payable _owner, address _kittyCoreAddress) Pausable(_owner) public { require(_kittyCoreAddress != address(0)); kittyCore = KittyCoreInterface(_kittyCoreAddress); require(kittyCore.supportsInterface(0x9a20483d)); saleAuction = AuctionInterface(kittyCore.saleAuction()); siringAuction = AuctionInterface(kittyCore.siringAuction()); } /** * Owner can transfer kitty */ function transferKitty(address _to, uint256 _kittyId) external onlyOwner { kittyCore.transfer(_to, _kittyId); } /** * Owner can transfer kitty */ function transferKittyBulk(address _to, uint256[] calldata _kittyIds) external onlyOwner { for(uint256 i = 0; i < _kittyIds.length; i++) { kittyCore.transfer(_to, _kittyIds[i]); } } /** * Owner can transferFrom kitty */ function transferKittyFrom(address _from, address _to, uint256 _kittyId) external onlyOwner { kittyCore.transferFrom(_from, _to, _kittyId); } /** * Owner can approve kitty */ function approveKitty(address _to, uint256 _kittyId) external onlyOwner { kittyCore.approve(_to, _kittyId); } /** * Owner can start sales auction for kitty owned by contract */ function createSaleAuction(uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external onlyOwner { kittyCore.createSaleAuction(_kittyId, _startingPrice, _endingPrice, _duration); } /** * Owner can cancel sales auction for kitty owned by contract */ function cancelSaleAuction(uint256 _kittyId) external onlyOwner { saleAuction.cancelAuction(_kittyId); } /** * Owner can start siring auction for kitty owned by contract */ function createSiringAuction(uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external onlyOwner { kittyCore.createSiringAuction(_kittyId, _startingPrice, _endingPrice, _duration); } /** * Owner can cancel siring auction for kitty owned by contract */ function cancelSiringAuction(uint256 _kittyId) external onlyOwner { siringAuction.cancelAuction(_kittyId); } } /** * @title SimpleBreeding * @dev Simple breeding contract allows dedicated breeder to breed kitties on behalf of owner, while owner retains control over funds and kitties. * Breeder gets reward per each successful breed. Breeder can breed when contract is not paused. * Owner should transfer kitties and funds to contact to breeding starts and withdraw afterwards. * Breeder can only breed kitties owned by contract and cannot transfer funds or kitties itself. */ contract SimpleBreeding is CKProxy { address payable public breeder; uint256 public breederReward; uint256 public originalBreederReward; uint256 public maxBreedingFee; event Breed(address breeder, uint256 matronId, uint256 sireId, uint256 reward); event MaxBreedingFeeChange(uint256 oldBreedingFee, uint256 newBreedingFee); event BreederRewardChange(uint256 oldBreederReward, uint256 newBreederReward); constructor(address payable _owner, address payable _breeder, address _kittyCoreAddress, uint256 _breederReward) CKProxy(_owner, _kittyCoreAddress) public { require(_breeder != address(0)); breeder = _breeder; maxBreedingFee = kittyCore.autoBirthFee(); breederReward = _breederReward; originalBreederReward = _breederReward; } /** * Contract funds are used to cover breeding fees and pay callee */ function () external payable {} /** * Owner can withdraw funds from contract */ function withdraw(uint256 amount) external onlyOwner { owner.transfer(amount); } /** * Owner can adjust breedering fee if needed */ function setMaxBreedingFee( uint256 _maxBreedingFee ) external onlyOwner { emit MaxBreedingFeeChange(maxBreedingFee, _maxBreedingFee); maxBreedingFee = _maxBreedingFee; } /** * Owner or breeder can change breeder's reward if needed. * Breeder can lower reward to make more attractive offer, it cannot set more than was originally agreed. * Owner can increase reward to motivate breeder to breed during high gas price, it cannot set less than was set by breeder. */ function setBreederReward( uint256 _breederReward ) external { require(msg.sender == breeder || msg.sender == owner); if(msg.sender == owner) { require(_breederReward >= originalBreederReward || _breederReward > breederReward, 'Reward value is less than required'); } else if(msg.sender == breeder) { require(_breederReward <= originalBreederReward, 'Reward value is more than original'); } emit BreederRewardChange(breederReward, _breederReward); breederReward = _breederReward; } /** * Breeder can call this function to breed kitties on behalf of owner * Owner can breed as well */ function breed(uint256 _matronId, uint256 _sireId) external whenNotPaused { require(msg.sender == breeder || msg.sender == owner); uint256 fee = kittyCore.autoBirthFee(); require(fee <= maxBreedingFee); kittyCore.breedWithAuto.value(fee)(_matronId, _sireId); uint256 reward = 0; // breeder can reenter but that's OK, since breeder is payed per successful breed if(msg.sender == breeder) { reward = breederReward; breeder.transfer(reward); } emit Breed(msg.sender, _matronId, _sireId, reward); } function destroy() public onlyOwner { require(kittyCore.balanceOf(address(this)) == 0, 'Contract has tokens'); selfdestruct(owner); } function destroyAndSend(address payable _recipient) public onlyOwner { require(kittyCore.balanceOf(address(this)) == 0, 'Contract has tokens'); selfdestruct(_recipient); } } contract SimpleBreedingFactory is Pausable { using SafeMath for uint256; KittyCoreInterface public kittyCore; uint256 public breederReward = 0.001 ether; uint256 public commission = 0 wei; uint256 public provisionFee; mapping (bytes32 => address) public breederToContract; event ContractCreated(address contractAddress, address breeder, address owner); event ContractRemoved(address contractAddress); constructor(address _kittyCoreAddress) Pausable(address(0)) public { provisionFee = commission + breederReward; kittyCore = KittyCoreInterface(_kittyCoreAddress); require(kittyCore.supportsInterface(0x9a20483d), "Invalid contract"); } /** * Owner can adjust breeder reward * Factory contract does not use breeder reward directly, but sets it to Breeding contracts during contract creation * Existing contracts won't be affected by the change */ function setBreederReward(uint256 _breederReward) external onlyOwner { require(_breederReward > 0, "Breeder reward must be greater than 0"); breederReward = _breederReward; provisionFee = uint256(commission).add(breederReward); } /** * Owner can set flat fee for contract creation */ function setCommission(uint256 _commission) external onlyOwner { commission = _commission; provisionFee = uint256(commission).add(breederReward); } /** * Just in case owner can change address of Kitty Core contract * Factory contract does not user Kitty Core directly, but sets it to Breeding contracts during contract creation * Existing contracts won't be affected by the change */ function setKittyCore(address _kittyCore) external onlyOwner { kittyCore = KittyCoreInterface(_kittyCore); require(kittyCore.supportsInterface(0x9a20483d), "Invalid contract"); } function () external payable { revert("Do not send funds to contract"); } /** * Owner can withdraw funds from contracts, if any * Contract can only gets funds from contraction creation commission */ function withdraw(uint256 amount) external onlyOwner { owner.transfer(amount); } /** * Create new breeding contract for breeder. This function should be called by user during breeder enrollment process. * Message value should be greater than breeder reward + commission. Value excess wil be transfered to created contract. * Breeder reward amount is transfered to breeder's address so it can start sending transactions * Comission amount stays in the contract * When contract is created, provisioning script can get address its address from breederToContract mapping */ function createContract(address payable _breederAddress) external payable whenNotPaused { require(msg.value >= provisionFee, "Invalid value"); // owner's address and breeder's address should uniquely identify contract // also we need to avoid situation when existing contract address is overwritten by enrolling breeder by same owner twice, // or enrolling same breeder by different owner bytes32 key = keccak256(abi.encodePacked(_breederAddress, msg.sender)); require(breederToContract[key] == address(0), "Breeder already enrolled"); //transfer value excess to new contract, owner can widthdraw later or use it for breeding uint256 excess = uint256(msg.value).sub(provisionFee); SimpleBreeding newContract = new SimpleBreeding(msg.sender, _breederAddress, address(kittyCore), breederReward); breederToContract[key] = address(newContract); if(excess > 0) { address(newContract).transfer(excess); } //transfer 1st breeder reward to breeder _breederAddress.transfer(breederReward); emit ContractCreated(address(newContract), _breederAddress, msg.sender); } /** * In most cases it does not make sense to delete contract's address. If needed it can be done by owner of factory contract. * This will not destroy breeding contract, just remove it address from the mapping, so user can deploy new contract for same breeder */ function removeContract(address _breederAddress, address _ownerAddress) external onlyOwner { bytes32 key = keccak256(abi.encodePacked(_breederAddress, _ownerAddress)); address contractAddress = breederToContract[key]; require(contractAddress != address(0), "Breeder not enrolled"); delete breederToContract[key]; emit ContractRemoved(contractAddress); } }
Owner can transferFrom kitty/
function transferKittyFrom(address _from, address _to, uint256 _kittyId) external onlyOwner { kittyCore.transferFrom(_from, _to, _kittyId); }
12,785,625
./full_match/43113/0x685f551D1d172087e5493E835907317038542068/sources/test.sol
Batch add new token grants recipients The addresses that are receiving grants amounts The amounts of tokens being granted totalTokens The total tokens being granted (checksum)/
function addTokenGrants( uint[] calldata recipients, uint256[] calldata amounts, uint256 totalTokens ) external { require(recipients.length == amounts.length, "Claim::addTokenGrants: different lengths"); for (uint256 i = 0; i < recipients.length; i++) { totalTokens = totalTokens.sub(amounts[i]); tokenGrants[recipients[i]] = tokenGrants[recipients[i]].add(amounts[i]); emit Added(recipients[i], amounts[i]); } require(totalTokens == 0, "Claim::addTokenGrants: wrong output"); }
13,176,441
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.6; import "./CToken.sol"; interface CompLike { function delegate(address delegatee) external; } /** * @title Compound's CErc20 Contract * @notice CTokens which wrap an EIP-20 underlying * @author Compound */ contract CErc20 is CToken, CErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) override external returns (uint) { mintInternal(mintAmount); return NO_ERROR; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) override external returns (uint) { redeemInternal(redeemTokens); return NO_ERROR; } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) override external returns (uint) { redeemUnderlyingInternal(redeemAmount); return NO_ERROR; } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) override external returns (uint) { borrowInternal(borrowAmount); return NO_ERROR; } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay, or -1 for the full outstanding amount * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) override external returns (uint) { repayBorrowInternal(repayAmount); return NO_ERROR; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay, or -1 for the full outstanding amount * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) override external returns (uint) { repayBorrowBehalfInternal(borrower, repayAmount); return NO_ERROR; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) override external returns (uint) { liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); return NO_ERROR; } /** * @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock) * @param token The address of the ERC-20 token to sweep */ function sweepToken(EIP20NonStandardInterface token) override external { require(msg.sender == admin, "CErc20::sweepToken: only admin can sweep tokens"); require(address(token) != underlying, "CErc20::sweepToken: can not sweep underlying token"); uint256 balance = token.balanceOf(address(this)); token.transfer(admin, balance); } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) override external returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() virtual override internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) virtual override internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of override external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) virtual override internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of override external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } /** * @notice Admin call to delegate the votes of the COMP-like underlying * @param compLikeDelegatee The address to delegate votes to * @dev CTokens whose underlying are not CompLike should revert here */ function _delegateCompLikeTo(address compLikeDelegatee) external { require(msg.sender == admin, "only the admin may set the comp-like delegate"); CompLike(underlying).delegate(compLikeDelegatee); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.6; import "./CErc20.sol"; /** * @title Compound's CErc20Delegate Contract * @notice CTokens which wrap an EIP-20 underlying and are delegated to * @author Compound */ contract CErc20Delegate is CErc20, CDelegateInterface { /** * @notice Construct an empty delegate */ constructor() {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) virtual override public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _becomeImplementation"); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() virtual override public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _resignImplementation"); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.6; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./EIP20Interface.sol"; import "./InterestRateModel.sol"; import "./ExponentialNoError.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ abstract contract CToken is CTokenInterface, ExponentialNoError, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == NO_ERROR, "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == NO_ERROR, "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return 0 if the transfer succeeded, else revert */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { revert TransferComptrollerRejection(allowed); } /* Do not allow self-transfers */ if (src == dst) { revert TransferNotAllowed(); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = type(uint).max; } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ uint allowanceNew = startingAllowance - tokens; uint srcTokensNew = accountTokens[src] - tokens; uint dstTokensNew = accountTokens[dst] + tokens; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != type(uint).max) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); // unused function // comptroller.transferVerify(address(this), src, dst, tokens); return NO_ERROR; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) override external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == NO_ERROR; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) override external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == NO_ERROR; } /** * @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 (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) override external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) override external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) override external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) override external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) override external view returns (uint, uint, uint, uint) { return ( NO_ERROR, accountTokens[account], borrowBalanceStoredInternal(account), exchangeRateStoredInternal() ); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() virtual internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() override external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() override external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() override external nonReentrant returns (uint) { require(accrueInterest() == NO_ERROR, "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) override external nonReentrant returns (uint) { require(accrueInterest() == NO_ERROR, "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) override public view returns (uint) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (uint) { /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint principalTimesIndex = borrowSnapshot.principal * borrowIndex; return principalTimesIndex / borrowSnapshot.interestIndex; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() override public nonReentrant returns (uint) { require(accrueInterest() == NO_ERROR, "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() override public view returns (uint) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() virtual internal view returns (uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves = totalCash + totalBorrows - totalReserves; Exp memory exchangeRate = Exp({mantissa: cashPlusBorrowsMinusReserves * expScale / _totalSupply}); return exchangeRate.mantissa; } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() override external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() virtual override public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return NO_ERROR; } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ uint blockDelta = currentBlockNumber - accrualBlockNumberPrior; /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta); uint interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior); uint totalBorrowsNew = interestAccumulated + borrowsPrior; uint totalReservesNew = mul_ScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); uint borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return NO_ERROR; } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply */ function mintInternal(uint mintAmount) internal nonReentrant { uint error = accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed revert MintAccrueInterestFailed(error); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to mintFresh(msg.sender, mintAmount); } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply */ function mintFresh(address minter, uint mintAmount) internal { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { revert MintComptrollerRejection(allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { revert MintFreshnessCheck(); } Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal()}); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ uint actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ uint mintTokens = div_(actualMintAmount, exchangeRate); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens * And write them into storage */ totalSupply = totalSupply + mintTokens; accountTokens[minter] = accountTokens[minter] + mintTokens; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, actualMintAmount, mintTokens); emit Transfer(address(this), minter, mintTokens); /* We call the defense hook */ // unused function // comptroller.mintVerify(address(this), minter, actualMintAmount, mintTokens); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying */ function redeemInternal(uint redeemTokens) internal nonReentrant { uint error = accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed revert RedeemAccrueInterestFailed(error); } // redeemFresh emits redeem-specific logs on errors, so we don't need to redeemFresh(payable(msg.sender), redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant { uint error = accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed revert RedeemAccrueInterestFailed(error); } // redeemFresh emits redeem-specific logs on errors, so we don't need to redeemFresh(payable(msg.sender), 0, redeemAmount); } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); /* exchangeRate = invoke Exchange Rate Stored() */ Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal() }); uint redeemTokens; uint redeemAmount; /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ redeemTokens = redeemTokensIn; redeemAmount = mul_ScalarTruncate(exchangeRate, redeemTokensIn); } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ redeemTokens = div_(redeemAmountIn, exchangeRate); redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, redeemTokens); if (allowed != 0) { revert RedeemComptrollerRejection(allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { revert RedeemFreshnessCheck(); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < redeemAmount) { revert RedeemTransferOutNotPossible(); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We write the previously calculated values into storage. * Note: Avoid token reentrancy attacks by writing reduced supply before external transfer. */ totalSupply = totalSupply - redeemTokens; accountTokens[redeemer] = accountTokens[redeemer] - redeemTokens; /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, redeemAmount); /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), redeemTokens); emit Redeem(redeemer, redeemAmount, redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, redeemAmount, redeemTokens); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow */ function borrowInternal(uint borrowAmount) internal nonReentrant { uint error = accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed revert BorrowAccrueInterestFailed(error); } // borrowFresh emits borrow-specific logs on errors, so we don't need to borrowFresh(payable(msg.sender), borrowAmount); } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow */ function borrowFresh(address payable borrower, uint borrowAmount) internal { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { revert BorrowComptrollerRejection(allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { revert BorrowFreshnessCheck(); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { revert BorrowCashNotAvailable(); } /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowNew = accountBorrow + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ uint accountBorrowsPrev = borrowBalanceStoredInternal(borrower); uint accountBorrowsNew = accountBorrowsPrev + borrowAmount; uint totalBorrowsNew = totalBorrows + borrowAmount; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We write the previously calculated values into storage. * Note: Avoid token reentrancy attacks by writing increased borrow before external transfer. `*/ accountBorrows[borrower].principal = accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, accountBorrowsNew, totalBorrowsNew); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay, or -1 for the full outstanding amount */ function repayBorrowInternal(uint repayAmount) internal nonReentrant { uint error = accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed revert RepayBorrowAccrueInterestFailed(error); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay, or -1 for the full outstanding amount */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant { uint error = accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed revert RepayBehalfAccrueInterestFailed(error); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to repayBorrowFresh(msg.sender, borrower, repayAmount); } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of underlying tokens being returned, or -1 for the full outstanding amount * @return (uint) the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { revert RepayBorrowComptrollerRejection(allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { revert RepayBorrowFreshnessCheck(); } /* We fetch the amount the borrower owes, with accumulated interest */ uint accountBorrowsPrev = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ uint repayAmountFinal = repayAmount == type(uint).max ? accountBorrowsPrev : repayAmount; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ uint actualRepayAmount = doTransferIn(payer, repayAmountFinal); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ uint accountBorrowsNew = accountBorrowsPrev - actualRepayAmount; uint totalBorrowsNew = totalBorrows - actualRepayAmount; /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, actualRepayAmount, accountBorrowsNew, totalBorrowsNew); return actualRepayAmount; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant { uint error = accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed revert LiquidateAccrueBorrowInterestFailed(error); } error = cTokenCollateral.accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed revert LiquidateAccrueCollateralInterestFailed(error); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { revert LiquidateComptrollerRejection(allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { revert LiquidateFreshnessCheck(); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { revert LiquidateCollateralFreshnessCheck(); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { revert LiquidateLiquidatorIsBorrower(); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { revert LiquidateCloseAmountIsZero(); } /* Fail if repayAmount = -1 */ if (repayAmount == type(uint).max) { revert LiquidateCloseAmountIsUintMax(); } /* Fail if repayBorrow fails */ uint actualRepayAmount = repayBorrowFresh(liquidator, borrower, repayAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == NO_ERROR, "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call if (address(cTokenCollateral) == address(this)) { seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { require(cTokenCollateral.seize(liquidator, borrower, seizeTokens) == NO_ERROR, "token seizure failed"); } /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) override external nonReentrant returns (uint) { seizeInternal(msg.sender, liquidator, borrower, seizeTokens); return NO_ERROR; } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { revert LiquidateSeizeComptrollerRejection(allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { revert LiquidateSeizeLiquidatorIsBorrower(); } /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ uint protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa})); uint liquidatorSeizeTokens = seizeTokens - protocolSeizeTokens; Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal()}); uint protocolSeizeAmount = mul_ScalarTruncate(exchangeRate, protocolSeizeTokens); uint totalReservesNew = totalReserves + protocolSeizeAmount; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the calculated values into storage */ totalReserves = totalReservesNew; totalSupply = totalSupply - protocolSeizeTokens; accountTokens[borrower] = accountTokens[borrower] - seizeTokens; accountTokens[liquidator] = accountTokens[liquidator] + liquidatorSeizeTokens; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, liquidatorSeizeTokens); emit Transfer(borrower, address(this), protocolSeizeTokens); emit ReservesAdded(address(this), protocolSeizeAmount, totalReservesNew); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. 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. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) override external returns (uint) { // Check caller = admin if (msg.sender != admin) { revert SetPendingAdminOwnerCheck(); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return 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() override external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { revert AcceptAdminPendingAdminCheck(); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = payable(address(0)); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return NO_ERROR; } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) override public returns (uint) { // Check caller is admin if (msg.sender != admin) { revert SetComptrollerOwnerCheck(); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return NO_ERROR; } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) override external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. revert SetReserveFactorAccrueInterestFailed(error); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { revert SetReserveFactorAdminCheck(); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { revert SetReserveFactorFreshCheck(); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { revert SetReserveFactorBoundsCheck(); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return NO_ERROR; } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. revert AddReservesAccrueInterestFailed(error); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { revert AddReservesFactorFreshCheck(actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (NO_ERROR, actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) override external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. revert ReduceReservesAccrueInterestFailed(error); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { revert ReduceReservesAdminCheck(); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { revert ReduceReservesFreshCheck(); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { revert ReduceReservesCashNotAvailable(); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { revert ReduceReservesCashValidation(); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return NO_ERROR; } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) override public returns (uint) { uint error = accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed revert SetInterestRateModelAccrueInterestFailed(error); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { revert SetInterestRateModelOwnerCheck(); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { revert SetInterestRateModelFreshCheck(); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return NO_ERROR; } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() virtual internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) virtual internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) virtual internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.6; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; import "./EIP20NonStandardInterface.sol"; import "./ErrorReporter.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; // Maximum borrow rate that can ever be applied (.0005% / block) uint internal constant borrowRateMaxMantissa = 0.0005e16; // Maximum fraction of interest that can be set aside for reserves uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; // Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; // Official record of token balances for each account mapping (address => uint) internal accountTokens; // Approved token transfer amounts on behalf of others mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } // Mapping of account addresses to outstanding borrow balances mapping(address => BorrowSnapshot) internal accountBorrows; /** * @notice Share of seized collateral that is added to reserves */ uint public constant protocolSeizeShareMantissa = 2.8e16; //2.8% } abstract contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /*** User Interface ***/ function transfer(address dst, uint amount) virtual external returns (bool); function transferFrom(address src, address dst, uint amount) virtual external returns (bool); function approve(address spender, uint amount) virtual external returns (bool); function allowance(address owner, address spender) virtual external view returns (uint); function balanceOf(address owner) virtual external view returns (uint); function balanceOfUnderlying(address owner) virtual external returns (uint); function getAccountSnapshot(address account) virtual external view returns (uint, uint, uint, uint); function borrowRatePerBlock() virtual external view returns (uint); function supplyRatePerBlock() virtual external view returns (uint); function totalBorrowsCurrent() virtual external returns (uint); function borrowBalanceCurrent(address account) virtual external returns (uint); function borrowBalanceStored(address account) virtual external view returns (uint); function exchangeRateCurrent() virtual external returns (uint); function exchangeRateStored() virtual external view returns (uint); function getCash() virtual external view returns (uint); function accrueInterest() virtual external returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) virtual external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) virtual external returns (uint); function _acceptAdmin() virtual external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) virtual external returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) virtual external returns (uint); function _reduceReserves(uint reduceAmount) virtual external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) virtual external returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } abstract contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) virtual external returns (uint); function redeem(uint redeemTokens) virtual external returns (uint); function redeemUnderlying(uint redeemAmount) virtual external returns (uint); function borrow(uint borrowAmount) virtual external returns (uint); function repayBorrow(uint repayAmount) virtual external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) virtual external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) virtual external returns (uint); function sweepToken(EIP20NonStandardInterface token) virtual external; /*** Admin Functions ***/ function _addReserves(uint addAmount) virtual external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } abstract contract CDelegatorInterface is CDelegationStorage { /** * @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) virtual external; } abstract contract CDelegateInterface is CDelegationStorage { /** * @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) virtual external; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() virtual external; } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.6; abstract contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) virtual external returns (uint[] memory); function exitMarket(address cToken) virtual external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) virtual external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) virtual external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) virtual external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) virtual external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) virtual external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) virtual external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) virtual external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) virtual external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) virtual external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) virtual external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) virtual external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) virtual external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) virtual external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) virtual external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) virtual external view returns (uint, uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.6; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @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 (-1 means infinite) * @return success Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.6; /** * @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 */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @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 * @return success Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.6; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @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(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { uint public constant NO_ERROR = 0; // support legacy return codes error TransferComptrollerRejection(uint256 errorCode); error TransferNotAllowed(); error TransferNotEnough(); error TransferTooMuch(); error MintComptrollerRejection(uint256 errorCode); error MintFreshnessCheck(); error MintAccrueInterestFailed(uint256 errorCode); error RedeemComptrollerRejection(uint256 errorCode); error RedeemFreshnessCheck(); error RedeemAccrueInterestFailed(uint256 errorCode); error RedeemTransferOutNotPossible(); error BorrowComptrollerRejection(uint256 errorCode); error BorrowFreshnessCheck(); error BorrowAccrueInterestFailed(uint256 errorCode); error BorrowCashNotAvailable(); error RepayBorrowComptrollerRejection(uint256 errorCode); error RepayBorrowFreshnessCheck(); error RepayBorrowAccrueInterestFailed(uint256 errorCode); error RepayBehalfAccrueInterestFailed(uint256 errorCode); error LiquidateComptrollerRejection(uint256 errorCode); error LiquidateFreshnessCheck(); error LiquidateCollateralFreshnessCheck(); error LiquidateAccrueBorrowInterestFailed(uint256 errorCode); error LiquidateAccrueCollateralInterestFailed(uint256 errorCode); error LiquidateLiquidatorIsBorrower(); error LiquidateCloseAmountIsZero(); error LiquidateCloseAmountIsUintMax(); error LiquidateRepayBorrowFreshFailed(uint256 errorCode); error LiquidateSeizeComptrollerRejection(uint256 errorCode); error LiquidateSeizeLiquidatorIsBorrower(); error AcceptAdminPendingAdminCheck(); error SetComptrollerOwnerCheck(); error SetPendingAdminOwnerCheck(); error SetReserveFactorAccrueInterestFailed(uint256 errorCode); error SetReserveFactorAdminCheck(); error SetReserveFactorFreshCheck(); error SetReserveFactorBoundsCheck(); error AddReservesAccrueInterestFailed(uint256 errorCode); error AddReservesFactorFreshCheck(uint256 actualAddAmount); error ReduceReservesAccrueInterestFailed(uint256 errorCode); error ReduceReservesAdminCheck(); error ReduceReservesFreshCheck(); error ReduceReservesCashNotAvailable(); error ReduceReservesCashValidation(); error SetInterestRateModelAccrueInterestFailed(uint256 errorCode); error SetInterestRateModelOwnerCheck(); error SetInterestRateModelFreshCheck(); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.6; /** * @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 { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // 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, uint scalar) pure internal returns (uint) { 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, uint scalar, uint addend) pure internal returns (uint) { 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) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return a + b; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return a * b; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.6; /** * @title Compound's InterestRateModel Interface * @author Compound */ abstract contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) virtual external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) virtual external view returns (uint); }
Borrows are repaid by another user (possibly the borrower). payer the account paying off the borrow borrower the account with the debt being payed off repayAmount the amount of underlying tokens being returned, or -1 for the full outstanding amount return (uint) the actual repayment amount./ Fail if repayBorrow not allowed / Verify market's block number equals current block number /
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) { uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { revert RepayBorrowComptrollerRejection(allowed); } if (accrualBlockNumber != getBlockNumber()) { revert RepayBorrowFreshnessCheck(); } uint totalBorrowsNew = totalBorrows - actualRepayAmount; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = totalBorrowsNew; return actualRepayAmount; }
1,632,549
/* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../errors/LibTransformERC20RichErrors.sol"; import "./IERC20Transformer.sol"; /// @dev Abstract base class for transformers. abstract contract Transformer is IERC20Transformer { using LibRichErrorsV06 for bytes; /// @dev The address of the deployer. address public immutable deployer; /// @dev The original address of this contract. address internal immutable _implementation; /// @dev Create this contract. constructor() public { deployer = msg.sender; _implementation = address(this); } /// @dev Destruct this contract. Only callable by the deployer and will not /// succeed in the context of a delegatecall (from another contract). /// @param ethRecipient The recipient of ETH held in this contract. function die(address payable ethRecipient) external virtual { // Only the deployer can call this. if (msg.sender != deployer) { LibTransformERC20RichErrors .OnlyCallableByDeployerError(msg.sender, deployer) .rrevert(); } // Must be executing our own context. if (address(this) != _implementation) { LibTransformERC20RichErrors .InvalidExecutionContextError(address(this), _implementation) .rrevert(); } selfdestruct(ethRecipient); } }
Destruct this contract. Only callable by the deployer and will not succeed in the context of a delegatecall (from another contract). ethRecipient The recipient of ETH held in this contract. Only the deployer can call this. Must be executing our own context.
function die(address payable ethRecipient) external virtual { if (msg.sender != deployer) { LibTransformERC20RichErrors .OnlyCallableByDeployerError(msg.sender, deployer) .rrevert(); } if (address(this) != _implementation) { LibTransformERC20RichErrors .InvalidExecutionContextError(address(this), _implementation) .rrevert(); } selfdestruct(ethRecipient); }
1,820,438
pragma solidity ^0.4.23; import "./General.sol"; contract Presale is Ownable, Pausable { uint256 public constant MAX_PACKAGES = 5000; uint256 public constant PRICE_START = 0.2 ether; uint256 public constant PRICE_INCREMENT = 0.00008 ether; uint256 public constant PRICE_MAX = PRICE_START + MAX_PACKAGES * PRICE_INCREMENT; // price(n) = 0.2 + n * 0.00008; (price(5000) = 0.6 ether) uint256 public remainingPackages = MAX_PACKAGES; uint256 public constant PACKAGES_MAX_PER_USER = 25; event SoldOutOfPackages(); event Purchased(address buyer, uint256 pkgsBought, uint256 spend); mapping (address => uint) private packagesOwnedByUser; uint256 public constant PACKAGES_GIFTS = 100; mapping (address => uint) public giftPackagesForUser; constructor() public { //set aside packages for gift packages packagesOwnedByUser[owner] = PACKAGES_GIFTS; remainingPackages -= PACKAGES_GIFTS; } // Convenient purchase of as many packages as possible with given ether (excess refunded) function () public payable whenNotPaused { purchasePackages(); } // EXTERNAL FUNCTIONS // For people who have been gifted packages from the owner function claimPackages() external { uint256 claimable = giftPackagesForUser[msg.sender]; require(claimable > 0, "No packages to claim"); giftPackagesForUser[msg.sender] = 0; packagesOwnedByUser[msg.sender] += claimable; } // Owner returning gift packages to supply function returnGiftPackages(uint256 packagesToReturn) external onlyOwner { require(packagesToReturn > 0, "No packages to return"); require(packagesToReturn <= packagesOwnedByUser[msg.sender], "Can''t return more than you have"); packagesOwnedByUser[msg.sender] -= packagesToReturn; remainingPackages += packagesToReturn; } // PUBLIC FUNCTIONS // Return how many packages are owned by given user function packagesOwned(address _user) public view returns (uint256) { require(_user != address(0), "NA: Packages owned by address(0)"); return packagesOwnedByUser[_user]; } // Purchase as many as possible with given ether (excess refunded) function purchasePackages() public payable whenNotPaused { purchasePackagesUpto(remainingPackages); } // execute function only if packages can be bought modifier presaleOpen() { if (remainingPackages == 0) { emit SoldOutOfPackages(); } require(remainingPackages > 0, "No remainingPackages"); _; } //Purchase upto given number of packages, fail if not enough eth function purchasePackagesUpto(uint256 _maxPkgs) public presaleOpen payable whenNotPaused { // Can't request more than the max if (_maxPkgs > PACKAGES_MAX_PER_USER) { _maxPkgs = PACKAGES_MAX_PER_USER; } // How much does the next package cost? uint256 unitPrice = nextPrice(); // How many can be bought at this price? uint256 pkgs = msg.value / unitPrice; // Don't buy more than you want if (pkgs > _maxPkgs) { pkgs = _maxPkgs; } // Don't buy more than you can have require(packagesOwnedByUser[msg.sender] <= PACKAGES_MAX_PER_USER, "Package limit exceeded"); if (pkgs + packagesOwnedByUser[msg.sender] > PACKAGES_MAX_PER_USER) { pkgs = PACKAGES_MAX_PER_USER - packagesOwnedByUser[msg.sender]; } // Still be buying something require(pkgs > 0, "Unable to purchase packages with given ether"); // Don't buy more than there is left if (pkgs >= remainingPackages) { pkgs = remainingPackages; emit LuckyLast(msg.sender); // ;) } purchase(pkgs, pkgs * unitPrice); } event LuckyLast(address); // Price increases linearly as packages are sold function nextPrice() public view returns (uint256) { //y = mx + b where x = packagesSold (ie, max - remaining) return PRICE_INCREMENT * (MAX_PACKAGES-remainingPackages) + PRICE_START; } // OWNER FUNCTIONS // Only owner can give 1 gift package per user in given addresses function giveGiftPackagePerUser(address[] _users) public onlyOwner { for (uint256 i = 0; i < _users.length; i++) { giveGiftPackages(1, _users[i]); } } // Only owner can give gift packages set aside for this purpose function giveGiftPackages(uint256 _amt, address _user) public onlyOwner { require(packagesOwnedByUser[msg.sender] >= _amt, "Not enough packages owned to gift"); packagesOwnedByUser[msg.sender] -= _amt; giftPackagesForUser[_user] += _amt; } // Overrides ownership transfer to include package movement function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0), "Unable to transfer to address(0)"); giveGiftPackages(packagesOwnedByUser[owner], _newOwner); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } // Transfer amount to owner function withdraw(uint256 _amt) public onlyOwner { owner.transfer(_amt); } //INTERNAL/PRIVATE FUNCTIONS // Execute a valid purchase of packages, refund excess. function purchase(uint256 _pkgs, uint256 _totalCost) internal { // Double-check amount paid require(msg.value >= _totalCost, "Not enough ether for purchase"); remainingPackages -= _pkgs; packagesOwnedByUser[msg.sender] += _pkgs; // Refund any overpayment uint256 refund = msg.value - _totalCost; if (refund > 0) { msg.sender.transfer(refund); } emit Purchased(msg.sender, _pkgs, _totalCost); } }
Overrides ownership transfer to include package movement
function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0), "Unable to transfer to address(0)"); giveGiftPackages(packagesOwnedByUser[owner], _newOwner); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; }
325,997
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; struct FrozenWallet { address wallet; uint totalAmount; uint releaseDay; bool scheduled; } struct LorcVestingType { uint cliffDays; bool vesting; } contract LandOrc is Initializable, ERC20Upgradeable, ERC20BurnableUpgradeable, PausableUpgradeable, AccessControlEnumerableUpgradeable, UUPSUpgradeable { using SafeMath for uint256; bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE"); mapping (address => bool) public isBlackListed; mapping (address => FrozenWallet) public frozenWallets; address public landNFTAddress; address public rewardVaultAddress; address public exchangeAddress; uint public rewardPercentage; uint public releaseTime; LorcVestingType[] public vestingTypes; function initialize(string memory _name, string memory _symbol) initializer public { __ERC20_init(_name, _symbol); __ERC20Burnable_init(); __Pausable_init(); __AccessControlEnumerable_init(); __UUPSUpgradeable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(PAUSER_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); _setupRole(UPGRADER_ROLE, msg.sender); rewardVaultAddress = msg.sender; exchangeAddress = msg.sender; rewardPercentage = 4500; // 45% of minted token goes to reward vault _mint(msg.sender, 21000000 * 10 ** uint(decimals())); // 21 Million initial token supply releaseTime = block.timestamp; // 1628985600; //"Sunday, 15 August 2021 00:00:00" vestingTypes.push(LorcVestingType(360 days, true)); // Advisor - vesitng duration 360 Days vestingTypes.push(LorcVestingType(540 days, true)); // Seed - vesitng duration 540 Days vestingTypes.push(LorcVestingType(540 days, true)); // Founder - vesitng duration 720 Days vestingTypes.push(LorcVestingType(90 days, true)); // Private A - vesitng duration 90 Days vestingTypes.push(LorcVestingType(30 days, true)); // Private B - vesitng duration 30 Days } /// @dev Throws if called by any account other than the LandNFT Contract. modifier onlyNFTContract() { require(landNFTAddress == msg.sender, "LandOrc: Caller is not the LandNFT Contract"); _; } /// @dev Throws if argument address is blacklisted modifier notBlacklisted(address _address) { require(isBlackListed[_address] == false, "transaction blacklisted!"); _; } /// @dev Set LandNFT contract address function setLandNFTAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) returns (bool){ address _oldAddress = landNFTAddress; landNFTAddress = _address; emit UpdateLandNFTAddress(_oldAddress, _address); return true; } /// @dev Set Reward Vault address function setRewardVaultAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) returns (bool){ address _oldAddress = rewardVaultAddress; rewardVaultAddress = _address; emit UpdateRewardVaultAddress(_oldAddress, _address); return true; } /// @dev Set Exchange account address function setExchangeAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) returns (bool){ address _oldAddress = exchangeAddress; exchangeAddress = _address; emit UpdateExchangeAddress(_oldAddress, _address); return true; } /// @dev Set Reward Percetage for NFT mint function setRewardPercentage(uint _rewardPercentage) external onlyRole(DEFAULT_ADMIN_ROLE) returns (bool){ require(_rewardPercentage > 0 && _rewardPercentage <= 10000, "LandOrc: percentage must be within range of 1 to 10000"); rewardPercentage = _rewardPercentage; return true; } /// @dev add blacklist address function addBlackList (address _address) external onlyRole(DEFAULT_ADMIN_ROLE) { isBlackListed[_address] = true; emit AddedBlackList(_address); } /// @dev remove blacklist address function removeBlackList (address _address) external onlyRole(DEFAULT_ADMIN_ROLE) { isBlackListed[_address] = false; emit RemovedBlackList(_address); } /// @dev check if the Vesting is completed function isVestingCompleted(uint releaseDay) public view returns (bool) { if (block.timestamp < releaseTime || block.timestamp < releaseDay) { return false; } return true; } /// @dev Add funds Allocations for vesting wallet addresses function addAllocations(address[] memory addresses, uint[] memory totalAmounts, uint vestingTypeIndex) external payable onlyRole(DEFAULT_ADMIN_ROLE) returns (bool) { require(addresses.length == totalAmounts.length, "LandOrc: Address and totalAmounts length must be same"); require(vestingTypes[vestingTypeIndex].vesting, "LandOrc: Vesting type isn't found"); LorcVestingType memory vestingType = vestingTypes[vestingTypeIndex]; uint addressesLength = addresses.length; for(uint i = 0; i < addressesLength; i++) { address _address = addresses[i]; uint256 totalAmount = totalAmounts[i]; uint256 cliffDay = vestingType.cliffDays; addFrozenWallet(_address, totalAmount, cliffDay); } return true; } /// @dev Add frozen wallet function addFrozenWallet(address wallet, uint totalAmount, uint cliffDays) internal { if (!frozenWallets[wallet].scheduled) { // Transfer funds to wallet super._transfer(msg.sender, wallet, totalAmount); } // Create frozen wallets FrozenWallet memory frozenWallet = FrozenWallet( wallet, totalAmount, releaseTime.add(cliffDays), true ); // Add wallet to frozen wallets frozenWallets[wallet] = frozenWallet; } /// @dev get transferable amount on frozen wallet address function getTransferableAmount(address sender) public view returns (uint256) { if (block.timestamp < frozenWallets[sender].releaseDay) { return 0; } return frozenWallets[sender].totalAmount; } /// @dev get frozen amount on the wallet address function getFrozenAmount(address sender) public view returns (uint256) { uint256 transferableAmount = getTransferableAmount(sender); uint256 frozenAmount = frozenWallets[sender].totalAmount.sub(transferableAmount); return frozenAmount; } /// @dev validate if the adddress can transfer amount function canTransfer(address sender, uint256 amount) public view returns (bool) { // Control is scheduled wallet if (!frozenWallets[sender].scheduled) { return true; } uint256 balance = balanceOf(sender); uint256 frozenAmount = getFrozenAmount(sender); if (balance > frozenWallets[sender].totalAmount && balance.sub(frozenWallets[sender].totalAmount) >= amount) { return true; } if (!isVestingCompleted(frozenWallets[sender].releaseDay) || balance.sub(amount) < frozenAmount) { return false; } return true; } /// @dev Mint new LORC for LandNFT function mintNFTReward( uint256 _amount) external whenNotPaused onlyNFTContract { require(_amount > 0, "LandOrc: amount must be greater than 0"); uint _rewardAmount = _amount.mul(rewardPercentage).div(10000); uint _exchangeAmount = _amount.sub(_rewardAmount); if(rewardVaultAddress != address(0) && _rewardAmount > 0){ _mint(rewardVaultAddress, _rewardAmount); } if(exchangeAddress != address(0) && _exchangeAmount > 0){ _mint(exchangeAddress, _exchangeAmount); } } /// @dev pause contract function pause() external onlyRole(PAUSER_ROLE) { _pause(); } /// @dev unpause contract function unpause() external onlyRole(PAUSER_ROLE) { _unpause(); } /// @dev mint new LORC function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) { _mint(to, amount); } /// @dev Override _beforeTokenTransfer function _beforeTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused notBlacklisted(from) notBlacklisted(to) notBlacklisted(msg.sender) override { require(canTransfer(msg.sender, amount), "LandOrc: Wait for vesting day!"); super._beforeTokenTransfer(from, to, amount); } function _authorizeUpgrade(address newImplementation) internal onlyRole(UPGRADER_ROLE) override {} event UpdateRewardVaultAddress(address oldAddress, address newAddress); event UpdateExchangeAddress(address oldAddress, address newAddress); event UpdateLandNFTAddress(address oldAddress, address newAddress); event AddedBlackList(address _address); event RemovedBlackList(address _address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "./LandOrc.sol"; contract LandOrcNFT is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, PausableUpgradeable, AccessControlUpgradeable, ERC721BurnableUpgradeable, UUPSUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; CountersUpgradeable.Counter private _tokenIdCounter; bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE"); address public lorcAddress; /// Events event NewLandNFTToken(uint tokenId, string tokenURI, uint256 valuation); event UpdateTokenURI(uint tokenId, string oldTokenURI, string newTokenURI); function initialize(string memory _name, string memory _symbol) initializer public { __ERC721_init(_name, _symbol); __ERC721Enumerable_init(); __ERC721URIStorage_init(); __Pausable_init(); __AccessControl_init(); __ERC721Burnable_init(); __UUPSUpgradeable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(PAUSER_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); _setupRole(UPGRADER_ROLE, msg.sender); // Increment to start tokenID with 1 _tokenIdCounter.increment(); } /// @dev Mint new NFT tokens function safeMint(address to, string memory _tokenURI, uint256 _valuation) external onlyRole(MINTER_ROLE) { uint256 _id = _tokenIdCounter.current(); _safeMint(to, _id); _setTokenURI(_id, _tokenURI); LandOrc(lorcAddress).mintNFTReward(_valuation); emit NewLandNFTToken(_id, _tokenURI, _valuation); _tokenIdCounter.increment(); } /// @dev Update NFT token URI function updateTokenURI(uint256 _tokenId, string memory _tokenURI) external onlyRole(MINTER_ROLE) { string memory _oldTokenURI = super.tokenURI(_tokenId); _setTokenURI(_tokenId, _tokenURI); emit UpdateTokenURI(_tokenId, _oldTokenURI, _tokenURI); } /// @dev Pause contract function pause() external onlyRole(PAUSER_ROLE) { _pause(); } /// @dev release contract function unpause() external onlyRole(PAUSER_ROLE) { _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal override(ERC721Upgradeable, ERC721URIStorageUpgradeable) { super._burn(tokenId); } function tokenURI(uint256 _tokenId) public view override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { return super.tokenURI(_tokenId); } function setLorcAddress(address _lorcAddress) external onlyRole(DEFAULT_ADMIN_ROLE) { lorcAddress = _lorcAddress; } function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function _authorizeUpgrade(address newImplementation) internal onlyRole(UPGRADER_ROLE) override {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 override returns (address) { return _roleMembers[role].at(index); } /** * @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 override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(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]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } 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); } } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/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, IERC20MetadataUpgradeable { 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. */ 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_; } /** * @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 {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // 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 IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal initializer { } /** * @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); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable { function __ERC721URIStorage_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721URIStorage_init_unchained(); } function __ERC721URIStorage_init_unchained() internal initializer { } using StringsUpgradeable for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 CountersUpgradeable { 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; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; 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]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.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; } } }
Update NFT token URI
function updateTokenURI(uint256 _tokenId, string memory _tokenURI) external onlyRole(MINTER_ROLE) { string memory _oldTokenURI = super.tokenURI(_tokenId); _setTokenURI(_tokenId, _tokenURI); emit UpdateTokenURI(_tokenId, _oldTokenURI, _tokenURI); }
11,788,969
/** *Submitted for verification at Etherscan.io on 2021-05-28 */ pragma solidity ^0.4.17; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <[email protected]> contract MultiSigWallet { // flag to determine if address is for a real contract or not bool public isMultiSigWallet = false; uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT); require(_required <= ownerCount); require(_required != 0); require(ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function MultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(isOwner[_owners[i]] || _owners[i] != 0); isOwner[_owners[i]] = true; } isMultiSigWallet = true; owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i = 0; i < owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. /// @param index the indx of the owner to be replaced function replaceOwnerIndexed(address owner, address newOwner, uint index) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { require(owners[index] == owner); owners[index] = newOwner; isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) internal notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction tx = transactions[transactionId]; tx.executed = true; if (tx.destination.call.value(tx.value)(tx.data)) Execution(transactionId); else { ExecutionFailure(transactionId); tx.executed = false; } } } /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination : destination, value : value, data : data, executed : false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i = 0; i < transactionCount; i++) if ((pending && !transactions[i].executed) || (executed && transactions[i].executed)) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 0; i < transactionCount; i++) if ((pending && !transactions[i].executed) || (executed && transactions[i].executed)) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } }
Returns array with owner addresses, which confirmed transaction. transactionId Transaction ID. return Returns array of owner addresses.
function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i]; }
7,699,755
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract MekasOfKrupt is ERC721, Ownable { uint internal constant TOKEN_LIMIT = 888; using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; mapping(address => bool) public whitelist; mapping(address => bool) public hasMinted; uint256 internal _mintPrice = 0; address payable internal devTeam; string internal _baseTokenURI; bool internal saleStarted = false; bool internal openToPublic = false; bool internal URISet = false; Counters.Counter private _devSupplyAwarded; /// The sale has not started yet. error SaleNotStarted(); /// Max tokens have been minted. error MaxTokensMinted(); /// You are not on the whitelist error NotOnWhitelist(); /// You have minted your allowance error MintedAllowance(); /// msg.value too low error MintPayableTooLow(); /// Sale has already started error SaleStarted(); /// URI has not been set yet error URINotSet(); /// Mint price set to low error MintPriceTooLow(); /// Dev team award limit reached. error DevTeamAwardLimit(); constructor(string memory name, string memory symbol, address devTeamAddress) ERC721(name, symbol) { devTeam = payable(devTeamAddress); _tokenIdCounter.increment(); // dev: starts tokens at id of 1 } /** * @dev takes a list of addresses and gives each address a allocation of mints */ function addToWhiteList(address[] memory whitelist_addresses) external onlyOwner { for (uint i = 0; i < whitelist_addresses.length; i++) { whitelist[whitelist_addresses[i]] = true; } } /** * @dev Creates a new token. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * */ function safeMint(address to) external payable { if (saleStarted == false) revert SaleNotStarted(); // dev: sale not started if (whitelist[msg.sender] == false && openToPublic == false) revert NotOnWhitelist(); // dev: not on the whitelist if (hasMinted[msg.sender] == true) revert MintedAllowance(); // dev: allowance minted uint256 tokenId = _tokenIdCounter.current(); if (tokenId > TOKEN_LIMIT) revert MaxTokensMinted(); // dev: max token supply minted if (msg.value < _mintPrice) revert MintPayableTooLow(); // dev: msg.value too low hasMinted[msg.sender] = true; _tokenIdCounter.increment(); _safeMint(to, tokenId); } /** * open mint up to the public */ function openMintToPublic() external onlyOwner { openToPublic = true; } /** * Start the sale (cant be stopped later) */ function startSale(uint256 mintPrice) external virtual onlyOwner { if (saleStarted == true) revert SaleStarted(); // dev: sale has already started if (URISet == false) revert URINotSet(); // dev: uri must be set if (mintPrice < 0.09 ether) revert MintPriceTooLow(); // dev: mint price too low _mintPrice = mintPrice; saleStarted = true; } /** * Can only be called twice. Gives 48 total Tokens to devs for giveaways, marketing purposes and team members. */ function devAward() external onlyOwner { uint256 devSupplyAwarded = _devSupplyAwarded.current(); if (devSupplyAwarded >= 2) revert DevTeamAwardLimit(); // dev: dev award limit reached for(uint i = 0; i < 24; i++){ uint256 tokenId = _tokenIdCounter.current(); if (tokenId > TOKEN_LIMIT) break; _tokenIdCounter.increment(); _safeMint(devTeam, tokenId); } _devSupplyAwarded.increment(); } /** * Withdraw contract funds to dev team address */ function withdrawFunds() external virtual onlyOwner { devTeam.transfer(address(this).balance); } function setBaseURI(string memory baseTokenURI) external onlyOwner { _baseTokenURI = baseTokenURI; URISet = true; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { return super.supportsInterface(interfaceId); } function getMaxSupply() external pure returns (uint256) { return TOKEN_LIMIT; } function getMintPrice() external view returns (uint256) { return _mintPrice; } function getSaleStarted() external view returns (bool) { return saleStarted; } function getOpenToPublic() external view returns (bool) { return openToPublic; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; /** * @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; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/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); } }
See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { return super.supportsInterface(interfaceId); }
379,130
// SPDX-License-Identifier: DeFiat and Friends (Zeppelin, MIT...) pragma solidity ^0.6.2; import "./AnyStake_Constants.sol"; import "./AnyStake_Libraries.sol"; //series of pool weighted by token price (using price oracles on chain) contract AnyStakeRegulator is AnyStakeBase, IRegulator { using SafeMath for uint256; using SafeERC20 for IERC20; event Claim(address indexed user, uint256 amount); event Deposit(address indexed user, uint256 amount); struct UserInfo { uint256 amount; uint256 rewardPaid; uint256 lastEntryBlock; } mapping (address => UserInfo) public userInfo; address public Vault; bool public initialized; uint256 public priceMultiplier; // pegs price at DFT_PRICE * (priceMultiplier / 1000) uint256 public exponentialRetry; // exponentially increases burn on each successive attempt uint256 public accDFTPerShare; modifier NoReentrant(address user) { require( block.number > userInfo[user].lastEntryBlock, "No Reentrancy: Must wait 1 block performing this operation" ); _; } modifier activated() { require(initialized, "Contract has not be initialized yet"); _; } constructor(address router, address dft, address dftp) public AnyStakeBase(router, dft, dftp) { priceMultiplier = 2500; // 2.5x, min DFT fee/burn needed to generate 1 DFTP } function initialize(address vault) external governanceLevel(2) { initialized = true; Vault = vault; } function stabilize(uint256 amount) internal { uint256 DFTPrice = IVault(Vault).getTokenPrice(DFT, address(0)); uint256 DFTPPrice = IVault(Vault).getTokenPrice(DFTP, address(0)); if (DFTPPrice > DFTPrice.mul(priceMultiplier.div(1000))) { // sell DFTP, buy DFT. // Raises price of DFT IERC20(DFTP).safeTransfer(Vault, amount); IVault(Vault).buyDFTWithTokens(DFTP, amount); } else { // burn deposited DFTP, burn DFTP from Uniswap proportionally. // Raises price of DFTP uint256 pointsLiquidity = IERC20(DFTP).balanceOf(DFTP_LP); uint256 adjustedSupply = IERC20(DFTP).totalSupply().sub(pointsLiquidity); uint256 burnRatio = amount.div(adjustedSupply); // check math, may need to burn more IPoints(DFTP).overrideLoyaltyPoints(address(this), 0); IPoints(DFTP).overrideLoyaltyPoints(DFTP_LP, pointsLiquidity.mul(burnRatio)); } } // update pool rewards function updatePool() external override { } function claim() external override activated NoReentrant(msg.sender) { _claim(msg.sender); } function _claim(address user) internal { UserInfo storage _user = userInfo[user]; if (_user.amount == 0) { return; } // calculate user.rewards _user.amount = 0; // burn entire stake //_user.rewardPaid = ... _user.lastEntryBlock = block.number; emit Claim(user, 0); } function deposit(uint256 amount) external override activated NoReentrant(msg.sender) { _deposit(msg.sender, amount); } function _deposit(address user, uint256 amount) internal { require(amount > 0, "Deposit: Cannot deposit zero tokens"); UserInfo storage _user = userInfo[user]; IERC20(DFTP).safeTransferFrom(user, address(this), amount); stabilize(amount); // perform stabilization _user.amount = _user.amount.add(amount); //_user.rewardPaid = ... _user.lastEntryBlock = block.number; emit Deposit(user, amount); } }
update pool rewards
function updatePool() external override { }
13,137,240
pragma solidity ^0.6.0; contract initializable5 { //inject NONSTANDARD NAMING bool private initialized; bool private initializing; modifier INITIALIZER65() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); } function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING } function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); __OWNABLE_INIT_UNCHAINED84(); } function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER78(); _owner = msgSender; emit OWNERSHIPTRANSFERRED52(address(0), msgSender); } function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER81() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED52(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED52(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } library safemath14 { //inject NONSTANDARD NAMING function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB60(a, b, "SafeMath: subtraction overflow"); } function SUB60(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 MUL16(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 DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV54(a, b, "SafeMath: division by zero"); } function DIV54(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 MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD56(a, b, "SafeMath: modulo by zero"); } function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface ierc2086 { //inject NONSTANDARD NAMING function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library console87 { //inject NONSTANDARD NAMING address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address36; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG40() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log()")); } function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOG40(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } interface iuniswapv2factory11 { //inject NONSTANDARD NAMING event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO47() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO7(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING } contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING using safemath14 for uint256; function INITIALIZE58( //inject NONSTANDARD NAMING address _NANOCOREAddress, address _WETHAddress, address _uniswapFactory ) public INITIALIZER65 { ownableupgradesafe25.__OWNABLE_INIT13(); nanocoreTokenAddress = _NANOCOREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress); feePercentX100 = 15; paused = false; // We start paused until sync post LGE happens. } address tokenUniswapPair; iuniswapv2factory11 public uniswapFactory; address internal WETHAddress; address nanocoreTokenAddress; address nanocoreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // Pausing transfers of the token function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING paused = _pause; } function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING feePercentX100 = _feeMultiplier; } function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING nanocoreVaultAddress = _nanocoreVaultAddress; } function SYNC99() public { //inject NONSTANDARD NAMING uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console87.LOG40("Normal fee transfer"); transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000); transferToAmount = amount.SUB60(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
inject NONSTANDARD NAMING
function LOG40(uint p0, string memory p1) internal view {
1,018,881
pragma solidity ^0.4.23; import '../core/ScriptExec.sol'; contract RegistryExec is ScriptExec { struct Registry { address index; address implementation; } // Maps execution ids to its registry app metadata mapping (bytes32 => Registry) public registry_instance_info; // Maps address to list of deployed Registry instances mapping (address => Registry[]) public deployed_registry_instances; /// EVENTS /// event RegistryInstanceCreated(address indexed creator, bytes32 indexed execution_id, address index, address implementation); /// APPLICATION EXECUTION /// bytes4 internal constant EXEC_SEL = bytes4(keccak256('exec(address,bytes32,bytes)')); /* Executes an application using its execution id and storage address. @param _exec_id: The instance exec id, which will route the calldata to the appropriate destination @param _calldata: The calldata to forward to the application @return success: Whether execution succeeded or not */ function exec(bytes32 _exec_id, bytes _calldata) external payable returns (bool success) { // Get function selector from calldata - bytes4 sel = getSelector(_calldata); // Ensure no registry functions are being called - require( sel != this.registerApp.selector && sel != this.registerAppVersion.selector && sel != UPDATE_INST_SEL && sel != UPDATE_EXEC_SEL ); // Call 'exec' in AbstractStorage, passing in the sender's address, the app exec id, and the calldata to forward - if (address(app_storage).call.value(msg.value)(abi.encodeWithSelector( EXEC_SEL, msg.sender, _exec_id, _calldata )) == false) { // Call failed - emit error message from storage and return 'false' checkErrors(_exec_id); // Return unspent wei to sender address(msg.sender).transfer(address(this).balance); return false; } // Get returned data success = checkReturn(); // If execution failed, require(success, 'Execution failed'); // Transfer any returned wei back to the sender address(msg.sender).transfer(address(this).balance); } // Returns the first 4 bytes of calldata function getSelector(bytes memory _calldata) internal pure returns (bytes4 selector) { assembly { selector := and( mload(add(0x20, _calldata)), 0xffffffff00000000000000000000000000000000000000000000000000000000 ) } } /// REGISTRY FUNCTIONS /// /* Creates an instance of a registry application and returns its execution id @param _index: The index file of the registry app (holds getters and init functions) @param _implementation: The file implementing the registry's functionality @return exec_id: The execution id under which the registry will store data */ function createRegistryInstance(address _index, address _implementation) external onlyAdmin() returns (bytes32 exec_id) { // Validate input - require(_index != 0 && _implementation != 0, 'Invalid input'); // Creates a registry from storage and returns the registry exec id - exec_id = StorageInterface(app_storage).createRegistry(_index, _implementation); // Ensure a valid execution id returned from storage - require(exec_id != 0, 'Invalid response from storage'); // If there is not already a default registry exec id set, set it if (registry_exec_id == 0) registry_exec_id = exec_id; // Create Registry struct in memory - Registry memory reg = Registry(_index, _implementation); // Set various app metadata values - deployed_by[exec_id] = msg.sender; registry_instance_info[exec_id] = reg; deployed_registry_instances[msg.sender].push(reg); // Emit event - emit RegistryInstanceCreated(msg.sender, exec_id, _index, _implementation); } /* Registers an application as the admin under the provider and registry exec id @param _app_name: The name of the application to register @param _index: The index file of the application - holds the getters and init functions @param _selectors: The selectors of the functions which the app implements @param _implementations: The addresses at which each function is located */ function registerApp(bytes32 _app_name, address _index, bytes4[] _selectors, address[] _implementations) external onlyAdmin() { // Validate input require(_app_name != 0 && _index != 0, 'Invalid input'); require(_selectors.length == _implementations.length && _selectors.length != 0, 'Invalid input'); // Check contract variables for valid initialization require(app_storage != 0 && registry_exec_id != 0 && provider != 0, 'Invalid state'); // Execute registerApp through AbstractStorage - uint emitted; uint paid; uint stored; (emitted, paid, stored) = StorageInterface(app_storage).exec(msg.sender, registry_exec_id, msg.data); // Ensure zero values for emitted and paid, and nonzero value for stored - require(emitted == 0 && paid == 0 && stored != 0, 'Invalid state change'); } /* Registers a version of an application as the admin under the provider and registry exec id @param _app_name: The name of the application under which the version will be registered @param _version_name: The name of the version to register @param _index: The index file of the application - holds the getters and init functions @param _selectors: The selectors of the functions which the app implements @param _implementations: The addresses at which each function is located */ function registerAppVersion(bytes32 _app_name, bytes32 _version_name, address _index, bytes4[] _selectors, address[] _implementations) external onlyAdmin() { // Validate input require(_app_name != 0 && _version_name != 0 && _index != 0, 'Invalid input'); require(_selectors.length == _implementations.length && _selectors.length != 0, 'Invalid input'); // Check contract variables for valid initialization require(app_storage != 0 && registry_exec_id != 0 && provider != 0, 'Invalid state'); // Execute registerApp through AbstractStorage - uint emitted; uint paid; uint stored; (emitted, paid, stored) = StorageInterface(app_storage).exec(msg.sender, registry_exec_id, msg.data); // Ensure zero values for emitted and paid, and nonzero value for stored - require(emitted == 0 && paid == 0 && stored != 0, 'Invalid state change'); } // Update instance selectors, index, and addresses bytes4 internal constant UPDATE_INST_SEL = bytes4(keccak256('updateInstance(bytes32,bytes32,bytes32)')); /* Updates an application's implementations, selectors, and index address. Uses default app provider and registry app. Uses latest app version by default. @param _exec_id: The execution id of the application instance to be updated @return success: The success of the call to the application's updateInstance function */ function updateAppInstance(bytes32 _exec_id) external returns (bool success) { // Validate input. Only the original deployer can update an application - require(_exec_id != 0 && msg.sender == deployed_by[_exec_id], 'invalid sender or input'); // Get instance metadata from exec id - Instance memory inst = instance_info[_exec_id]; // Call 'exec' in AbstractStorage, passing in the sender's address, the execution id, and // the calldata to update the application - if(address(app_storage).call( abi.encodeWithSelector(EXEC_SEL, // 'exec' selector inst.current_provider, // application provider address _exec_id, // execution id to update abi.encodeWithSelector(UPDATE_INST_SEL, // calldata for Registry updateInstance function inst.app_name, // name of the applcation used by the instance inst.version_name, // name of the current version of the application inst.current_registry_exec_id // registry exec id when the instance was instantiated ) ) ) == false) { // Call failed - emit error message from storage and return 'false' checkErrors(_exec_id); return false; } // Check returned data to ensure state was correctly changed in AbstractStorage - success = checkReturn(); // If execution failed, revert state and return an error message - require(success, 'Execution failed'); // If execution was successful, the version was updated. Get the latest version // and set the exec id instance info - address registry_idx = StorageInterface(app_storage).getIndex(inst.current_registry_exec_id); bytes32 latest_version = RegistryInterface(registry_idx).getLatestVersion( app_storage, inst.current_registry_exec_id, inst.current_provider, inst.app_name ); // Ensure nonzero latest version - require(latest_version != 0, 'invalid latest version'); // Set current version - instance_info[_exec_id].version_name = latest_version; } // Update instance script exec contract bytes4 internal constant UPDATE_EXEC_SEL = bytes4(keccak256('updateExec(address)')); /* Updates an application's script executor from this Script Exec to a new address @param _exec_id: The execution id of the application instance to be updated @param _new_exec_addr: The new script exec address for this exec id @returns success: The success of the call to the application's updateExec function */ function updateAppExec(bytes32 _exec_id, address _new_exec_addr) external returns (bool success) { // Validate input. Only the original deployer can migrate the script exec address - require(_exec_id != 0 && msg.sender == deployed_by[_exec_id] && address(this) != _new_exec_addr && _new_exec_addr != 0, 'invalid input'); // Call 'exec' in AbstractStorage, passing in the sender's address, the execution id, and // the calldata to migrate the script exec address - if(address(app_storage).call( abi.encodeWithSelector(EXEC_SEL, // 'exec' selector msg.sender, // sender address _exec_id, // execution id to update abi.encodeWithSelector(UPDATE_EXEC_SEL, _new_exec_addr) // calldata for Registry updateExec ) ) == false) { // Call failed - emit error message from storage and return 'false' checkErrors(_exec_id); return false; } // Check returned data to ensure state was correctly changed in AbstractStorage - success = checkReturn(); // If execution failed, revert state and return an error message - require(success, 'Execution failed'); } }
/ Get function selector from calldata - Ensure no registry functions are being called - Call 'exec' in AbstractStorage, passing in the sender's address, the app exec id, and the calldata to forward - Call failed - emit error message from storage and return 'false' Return unspent wei to sender
function exec(bytes32 _exec_id, bytes _calldata) external payable returns (bool success) { bytes4 sel = getSelector(_calldata); require( sel != this.registerApp.selector && sel != this.registerAppVersion.selector && sel != UPDATE_INST_SEL && sel != UPDATE_EXEC_SEL ); if (address(app_storage).call.value(msg.value)(abi.encodeWithSelector( EXEC_SEL, msg.sender, _exec_id, _calldata )) == false) { checkErrors(_exec_id); address(msg.sender).transfer(address(this).balance); return false; } }
977,464
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "./base/Controllable.sol"; import "sol-temple/src/tokens/ERC721.sol"; import "sol-temple/src/tokens/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title Ape Runners RUN /// @author naomsa <https://twitter.com/naomsa666> contract ApeRunnersRUN is Ownable, Pausable, Controllable, ERC20("Ape Runners", "RUN", 18, "1") { /* -------------------------------------------------------------------------- */ /* Airdrop Details */ /* -------------------------------------------------------------------------- */ /// @notice Ape Runners contract. ERC721 public immutable apeRunners; /// @notice Ape Runner id => claimed airdrop. mapping(uint256 => bool) public airdroped; constructor(address newApeRunners) { apeRunners = ERC721(newApeRunners); } /* -------------------------------------------------------------------------- */ /* Airdrop Logic */ /* -------------------------------------------------------------------------- */ /// @notice Claim pending airdrop for each Ape Runner. /// @param ids Ape Runner token ids to claim airdrop. function claim(uint256[] memory ids) external { uint256 pending; for (uint256 i; i < ids.length; i++) { require(apeRunners.ownerOf(ids[i]) == msg.sender, "Not the token owner"); require(!airdroped[ids[i]], "Airdrop already claimed"); airdroped[ids[i]] = true; pending += 150 ether; } super._mint(msg.sender, pending); } /* -------------------------------------------------------------------------- */ /* Owner Logic */ /* -------------------------------------------------------------------------- */ /// @notice Add or edit contract controllers. /// @param addrs Array of addresses to be added/edited. /// @param state New controller state of addresses. function setControllers(address[] calldata addrs, bool state) external onlyOwner { for (uint256 i; i < addrs.length; i++) super._setController(addrs[i], state); } /// @notice Switch the contract paused state between paused and unpaused. function togglePaused() external onlyOwner { if (paused()) _unpause(); else _pause(); } /* -------------------------------------------------------------------------- */ /* ERC-20 Logic */ /* -------------------------------------------------------------------------- */ /// @notice Mint tokens. /// @param to Address to get tokens minted to. /// @param value Number of tokens to be minted. function mint(address to, uint256 value) external onlyController { super._mint(to, value); } /// @notice Burn tokens. /// @param from Address to get tokens burned from. /// @param value Number of tokens to be burned. function burn(address from, uint256 value) external onlyController { super._burn(from, value); } /// @notice See {ERC20-_beforeTokenTransfer}. /// @dev Overriden to block transactions while the contract is paused (avoiding bugs). function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override whenNotPaused { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /// @title Controllable abstract contract Controllable { /// @notice address => is controller. mapping(address => bool) private _isController; /// @notice Require the caller to be a controller. modifier onlyController() { require( _isController[msg.sender], "Controllable: Caller is not a controller" ); _; } /// @notice Check if `addr` is a controller. function isController(address addr) public view returns (bool) { return _isController[addr]; } /// @notice Set the `addr` controller status to `status`. function _setController(address addr, bool status) internal { _isController[addr] = status; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// @title ERC721 /// @author naomsa <https://twitter.com/naomsa666> /// @notice A complete ERC721 implementation including metadata and enumerable /// functions. Completely gas optimized and extensible. abstract contract ERC721 is IERC165, IERC721, IERC721Metadata, IERC721Enumerable { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'__` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @notice See {ERC721Metadata-name}. string public name; /// @notice See {ERC721Metadata-symbol}. string public symbol; /// @notice See {ERC721Enumerable-totalSupply}. uint256 public totalSupply; /// @notice Array of all owners. mapping(uint256 => address) private _owners; /// @notice Mapping of all balances. mapping(address => uint256) private _balanceOf; /// @notice Mapping from token Id to it's approved address. mapping(uint256 => address) private _tokenApprovals; /// @notice Mapping of approvals between owner and operator. mapping(address => mapping(address => bool)) private _isApprovedForAll; /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ /// @dev Set token's name and symbol. constructor(string memory name_, string memory symbol_) { name = name_; symbol = symbol_; } /// @notice See {ERC721-balanceOf}. function balanceOf(address account_) public view virtual returns (uint256) { require(account_ != address(0), "ERC721: balance query for the zero address"); return _balanceOf[account_]; } /// @notice See {ERC721-ownerOf}. function ownerOf(uint256 tokenId_) public view virtual returns (address) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); address owner = _owners[tokenId_]; return owner; } /// @notice See {ERC721Metadata-tokenURI}. function tokenURI(uint256) public view virtual returns (string memory); /// @notice See {ERC721-approve}. function approve(address to_, uint256 tokenId_) public virtual { address owner = ownerOf(tokenId_); require(to_ != owner, "ERC721: approval to current owner"); require( msg.sender == owner || _isApprovedForAll[owner][msg.sender], "ERC721: caller is not owner nor approved for all" ); _approve(to_, tokenId_); } /// @notice See {ERC721-getApproved}. function getApproved(uint256 tokenId_) public view virtual returns (address) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); return _tokenApprovals[tokenId_]; } /// @notice See {ERC721-setApprovalForAll}. function setApprovalForAll(address operator_, bool approved_) public virtual { _setApprovalForAll(msg.sender, operator_, approved_); } /// @notice See {ERC721-isApprovedForAll}. function isApprovedForAll(address account_, address operator_) public view virtual returns (bool) { return _isApprovedForAll[account_][operator_]; } /// @notice See {ERC721-transferFrom}. function transferFrom( address from_, address to_, uint256 tokenId_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); _transfer(from_, to_, tokenId_); } /// @notice See {ERC721-safeTransferFrom}. function safeTransferFrom( address from_, address to_, uint256 tokenId_ ) public virtual { safeTransferFrom(from_, to_, tokenId_, ""); } /// @notice See {ERC721-safeTransferFrom}. function safeTransferFrom( address from_, address to_, uint256 tokenId_, bytes memory data_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from_, to_, tokenId_, data_); } /// @notice See {ERC721Enumerable.tokenOfOwnerByIndex}. function tokenOfOwnerByIndex(address account_, uint256 index_) public view returns (uint256 tokenId) { require(index_ < balanceOf(account_), "ERC721Enumerable: Index out of bounds"); uint256 count; for (uint256 i; i < totalSupply; ++i) { if (account_ == _owners[i]) { if (count == index_) return i; else count++; } } revert("ERC721Enumerable: Index out of bounds"); } /// @notice See {ERC721Enumerable.tokenByIndex}. function tokenByIndex(uint256 index_) public view virtual returns (uint256) { require(index_ < totalSupply, "ERC721Enumerable: Index out of bounds"); return index_; } /// @notice Returns a list of all token Ids owned by `owner`. function walletOfOwner(address account_) public view returns (uint256[] memory) { uint256 balance = balanceOf(account_); uint256[] memory ids = new uint256[](balance); for (uint256 i = 0; i < balance; i++) ids[i] = tokenOfOwnerByIndex(account_, i); return ids; } /* _ _ */ /* _ ( )_ (_ ) */ /* (_) ___ | ,_) __ _ __ ___ _ _ | | */ /* | |/' _ `\| | /'__`\( '__)/' _ `\ /'__` ) | | */ /* | || ( ) || |_ ( ___/| | | ( ) |( (_| | | | */ /* (_)(_) (_)`\__)`\____)(_) (_) (_)`\__,_)(___) */ /// @notice 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. function _safeTransfer( address from_, address to_, uint256 tokenId_, bytes memory data_ ) internal virtual { _transfer(from_, to_, tokenId_); _checkOnERC721Received(from_, to_, tokenId_, data_); } /// @notice Returns whether `tokenId_` exists. function _exists(uint256 tokenId_) internal view virtual returns (bool) { return tokenId_ < totalSupply && _owners[tokenId_] != address(0); } /// @notice Returns whether `spender_` is allowed to manage `tokenId`. function _isApprovedOrOwner(address spender_, uint256 tokenId_) internal view virtual returns (bool) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); address owner = _owners[tokenId_]; return (spender_ == owner || getApproved(tokenId_) == spender_ || isApprovedForAll(owner, spender_)); } /// @notice Safely mints `tokenId_` and transfers it to `to`. function _safeMint(address to_, uint256 tokenId_) internal virtual { _safeMint(to_, tokenId_, ""); } /// @notice Same as {_safeMint}, but with an additional `data_` parameter which is /// forwarded in {ERC721Receiver-onERC721Received} to contract recipients. function _safeMint( address to_, uint256 tokenId_, bytes memory data_ ) internal virtual { _mint(to_, tokenId_); _checkOnERC721Received(address(0), to_, tokenId_, data_); } /// @notice Mints `tokenId_` and transfers it to `to_`. function _mint(address to_, uint256 tokenId_) internal virtual { require(!_exists(tokenId_), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to_, tokenId_); _owners[tokenId_] = to_; totalSupply++; unchecked { _balanceOf[to_]++; } emit Transfer(address(0), to_, tokenId_); _afterTokenTransfer(address(0), to_, tokenId_); } /// @notice Destroys `tokenId`. The approval is cleared when the token is burned. function _burn(uint256 tokenId_) internal virtual { address owner = ownerOf(tokenId_); _beforeTokenTransfer(owner, address(0), tokenId_); // Clear approvals _approve(address(0), tokenId_); totalSupply--; _balanceOf[owner]--; delete _owners[tokenId_]; emit Transfer(owner, address(0), tokenId_); _afterTokenTransfer(owner, address(0), tokenId_); } /// @notice Transfers `tokenId_` from `from_` to `to`. function _transfer( address from_, address to_, uint256 tokenId_ ) internal virtual { require(_owners[tokenId_] == from_, "ERC721: transfer of token that is not own"); _beforeTokenTransfer(from_, to_, tokenId_); // Clear approvals from the previous owner _approve(address(0), tokenId_); _owners[tokenId_] = to_; unchecked { _balanceOf[from_]--; _balanceOf[to_]++; } emit Transfer(from_, to_, tokenId_); _afterTokenTransfer(from_, to_, tokenId_); } /// @notice Approve `to_` to operate on `tokenId_` function _approve(address to_, uint256 tokenId_) internal virtual { _tokenApprovals[tokenId_] = to_; emit Approval(_owners[tokenId_], to_, tokenId_); } /// @notice Approve `operator_` to operate on all of `account_` tokens. function _setApprovalForAll( address account_, address operator_, bool approved_ ) internal virtual { require(account_ != operator_, "ERC721: approve to caller"); _isApprovedForAll[account_][operator_] = approved_; emit ApprovalForAll(account_, operator_, approved_); } /// @notice ERC721Receiver callback checking and calling helper. function _checkOnERC721Received( address from_, address to_, uint256 tokenId_, bytes memory data_ ) private { if (to_.code.length > 0) { try IERC721Receiver(to_).onERC721Received(msg.sender, from_, tokenId_, data_) returns (bytes4 returned) { require(returned == 0x150b7a02, "ERC721: safe transfer to non ERC721Receiver implementation"); } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: safe transfer to non ERC721Receiver implementation"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } /// @notice Hook that is called before any token transfer. function _beforeTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual {} /// @notice Hook that is called after any token transfer. function _afterTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual {} /* ___ _ _ _ _ __ _ __ */ /* /',__)( ) ( )( '_`\ /'__`\( '__) */ /* \__, \| (_) || (_) )( ___/| | */ /* (____/`\___/'| ,__/'`\____)(_) */ /* | | */ /* (_) */ /// @notice See {ERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId_) public view virtual returns (bool) { return interfaceId_ == type(IERC721).interfaceId || // ERC721 interfaceId_ == type(IERC721Metadata).interfaceId || // ERC721Metadata interfaceId_ == type(IERC721Enumerable).interfaceId || // ERC721Enumerable interfaceId_ == type(IERC165).interfaceId; // ERC165 } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; /** * @title ERC20 * @author naomsa <https://twitter.com/naomsa666> * @notice A complete ERC20 implementation including EIP-2612 permit feature. * Inspired by Solmate's ERC20, aiming at efficiency. */ abstract contract ERC20 is IERC20 { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'_` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @notice See {ERC20-name}. string public name; /// @notice See {ERC20-symbol}. string public symbol; /// @notice See {ERC20-decimals}. uint8 public immutable decimals; /// @notice Used to hash the Domain Separator. string public version; /// @notice See {ERC20-totalSupply}. uint256 public totalSupply; /// @notice See {ERC20-balanceOf}. mapping(address => uint256) public balanceOf; /// @notice See {ERC20-allowance}. mapping(address => mapping(address => uint256)) public allowance; /// @notice See {ERC2612-nonces}. mapping(address => uint256) public nonces; /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ constructor( string memory name_, string memory symbol_, uint8 decimals_, string memory version_ ) { name = name_; symbol = symbol_; decimals = decimals_; version = version_; } /// @notice See {ERC20-transfer}. function transfer(address to_, uint256 value_) public returns (bool) { _transfer(msg.sender, to_, value_); return true; } /// @notice See {ERC20-transferFrom}. function transferFrom( address from_, address to_, uint256 value_ ) public returns (bool) { uint256 allowed = allowance[from_][msg.sender]; require(allowed >= value_, "ERC20: allowance exceeds transfer value"); if (allowed != type(uint256).max) allowance[from_][msg.sender] -= value_; _transfer(from_, to_, value_); return true; } /// @notice See {ERC20-approve}. function approve(address spender_, uint256 value_) public returns (bool) { _approve(msg.sender, spender_, value_); return true; } /// @notice See {ERC2612-DOMAIN_SEPARATOR}. function DOMAIN_SEPARATOR() public view returns (bytes32) { return _hashEIP712Domain(name, version, block.chainid, address(this)); } /// @notice See {ERC2612-permit}. function permit( address owner_, address spender_, uint256 value_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) public { require(deadline_ >= block.timestamp, "ERC20: expired permit deadline"); // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") bytes32 digest = _hashEIP712Message( DOMAIN_SEPARATOR(), keccak256( abi.encode( 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9, owner_, spender_, value_, nonces[owner_]++, deadline_ ) ) ); address signer = ecrecover(digest, v_, r_, s_); require(signer != address(0) && signer == owner_, "ERC20: invalid signature"); _approve(owner_, spender_, value_); } /* _ _ */ /* _ ( )_ (_ ) */ /* (_) ___ | ,_) __ _ __ ___ _ _ | | */ /* | |/' _ `\| | /'__`\( '__)/' _ `\ /'_` ) | | */ /* | || ( ) || |_ ( ___/| | | ( ) |( (_| | | | */ /* (_)(_) (_)`\__)`\____)(_) (_) (_)`\__,_)(___) */ /// @notice Internal transfer helper. Throws if `value_` exceeds `from_` balance. function _transfer( address from_, address to_, uint256 value_ ) internal { require(balanceOf[from_] >= value_, "ERC20: insufficient balance"); _beforeTokenTransfer(from_, to_, value_); unchecked { balanceOf[from_] -= value_; balanceOf[to_] += value_; } emit Transfer(from_, to_, value_); _afterTokenTransfer(from_, to_, value_); } /// @notice Internal approve helper. function _approve( address owner_, address spender_, uint256 value_ ) internal { allowance[owner_][spender_] = value_; emit Approval(owner_, spender_, value_); } /// @notice Internal minting logic. function _mint(address to_, uint256 value_) internal { _beforeTokenTransfer(address(0), to_, value_); totalSupply += value_; unchecked { balanceOf[to_] += value_; } emit Transfer(address(0), to_, value_); _afterTokenTransfer(address(0), to_, value_); } /// @notice Internal burning logic. function _burn(address from_, uint256 value_) internal { _beforeTokenTransfer(from_, address(0), value_); require(balanceOf[from_] >= value_, "ERC20: burn value exceeds balance"); unchecked { balanceOf[from_] -= value_; totalSupply -= value_; } emit Transfer(from_, address(0), value_); _afterTokenTransfer(from_, address(0), value_); } /** * @notice EIP721 domain hashing helper. * @dev Modified from https://github.com/0xProject/0x-monorepo/blob/development/contracts/utils/contracts/src/LibEIP712.sol */ function _hashEIP712Domain( string memory name_, string memory version_, uint256 chainId_, address verifyingContract_ ) private pure returns (bytes32) { bytes32 result; 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, 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f) 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; } /** * @notice EIP721 typed message hashing helper. * @dev Modified from https://github.com/0xProject/0x-monorepo/blob/development/contracts/utils/contracts/src/LibEIP712.sol */ function _hashEIP712Message(bytes32 domainSeparator_, bytes32 hash_) private pure returns (bytes32) { bytes32 result; assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), domainSeparator_) // EIP712 domain hash mstore(add(memPtr, 34), hash_) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } function _beforeTokenTransfer( address from, address to, uint256 value ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 value ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) 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); /** * @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 // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // 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; } }
Mint tokens. to Address to get tokens minted to. value Number of tokens to be minted.
function mint(address to, uint256 value) external onlyController { super._mint(to, value); }
13,632,887
// Sources flattened with hardhat v2.2.1 https://hardhat.org // File contracts/interfaces/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/IPoolFactory.sol pragma solidity >=0.7.1; interface IPoolFactory { function getTier() external view returns (address); } // File contracts/libraries/Ownable.sol pragma solidity ^0.7.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @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 { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File contracts/libraries/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 () { _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 contracts/libraries/SafeMath.sol pragma solidity ^0.7.0; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @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 addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ 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 multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage); 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; } } // File contracts/libraries/Pausable.sol pragma solidity >=0.7.1; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "CONTRACT_PAUSED"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "CONTRACT_NOT_PAUSED"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File openzeppelin-solidity/contracts/cryptography/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File contracts/extensions/RedKiteWhitelist.sol pragma solidity ^0.7.0; // Signature Verification /// @title RedKite Whitelists - Implement off-chain whitelist and on-chain verification /// @author Thang Nguyen Quy <[email protected]> contract RedKiteWhitelist { // Using Openzeppelin ECDSA cryptography library function getMessageHash( address _candidate, uint256 _maxAmount, uint256 _minAmount ) public pure returns (bytes32) { return keccak256(abi.encodePacked(_candidate, _maxAmount, _minAmount)); } function getClaimMessageHash( address _candidate, uint256 _amount ) public pure returns (bytes32) { return keccak256(abi.encodePacked(_candidate, _amount)); } // Verify signature function function verify( address _signer, address _candidate, uint256 _maxAmount, uint256 _minAmount, bytes memory signature ) public pure returns (bool) { bytes32 messageHash = getMessageHash(_candidate, _maxAmount, _minAmount); bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); return getSignerAddress(ethSignedMessageHash, signature) == _signer; } // Verify signature function function verifyClaimToken( address _signer, address _candidate, uint256 _amount, bytes memory signature ) public pure returns (bool) { bytes32 messageHash = getClaimMessageHash(_candidate, _amount); bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); return getSignerAddress(ethSignedMessageHash, signature) == _signer; } function getSignerAddress(bytes32 _messageHash, bytes memory _signature) public pure returns(address signer) { return ECDSA.recover(_messageHash, _signature); } // Split signature to r, s, v function splitSignature(bytes memory _signature) public pure returns ( bytes32 r, bytes32 s, uint8 v ) { require(_signature.length == 65, "invalid signature length"); assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } } function getEthSignedMessageHash(bytes32 _messageHash) public pure returns (bytes32) { return ECDSA.toEthSignedMessageHash(_messageHash); } } // File contracts/presale-pool/PreSalePool.sol pragma solidity ^0.7.1; contract PreSalePool is Ownable, ReentrancyGuard, Pausable, RedKiteWhitelist { using SafeMath for uint256; struct OfferedCurrency { uint256 decimals; uint256 rate; } // The token being sold IERC20 public token; // The address of factory contract address public factory; // The address of signer account address public signer; // Address where funds are collected address public fundingWallet; // Timestamps when token started to sell uint256 public openTime = block.timestamp; // Timestamps when token stopped to sell uint256 public closeTime; // Amount of wei raised uint256 public weiRaised = 0; // Amount of token sold uint256 public tokenSold = 0; // Amount of token sold uint256 public totalUnclaimed = 0; // Number of token user purchased mapping(address => uint256) public userPurchased; // Number of token user claimed mapping(address => uint256) public userClaimed; // Number of token user purchased mapping(address => mapping (address => uint)) public investedAmountOf; // Get offered currencies mapping(address => OfferedCurrency) public offeredCurrencies; // Pool extensions bool public useWhitelist; // ----------------------------------------- // Lauchpad Starter's event // ----------------------------------------- event PresalePoolCreated( address token, uint256 openTime, uint256 closeTime, address offeredCurrency, uint256 offeredCurrencyDecimals, uint256 offeredCurrencyRate, address wallet, address owner ); event TokenPurchaseByEther( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); event TokenPurchaseByToken( address indexed purchaser, address indexed beneficiary, address token, uint256 value, uint256 amount ); event TokenClaimed(address user, uint256 amount); event RefundedIcoToken(address wallet, uint256 amount); event PoolStatsChanged(); // ----------------------------------------- // Constructor // ----------------------------------------- constructor() { factory = msg.sender; } // ----------------------------------------- // Red Kite external interface // ----------------------------------------- /** * @dev fallback function */ fallback() external { revert(); } /** * @dev fallback function */ receive() external payable { revert(); } /** * @param _token Address of the token being sold * @param _duration Duration of ICO Pool * @param _openTime When ICO Started * @param _offeredCurrency Address of offered token * @param _offeredCurrencyDecimals Decimals of offered token * @param _offeredRate Number of currency token units a buyer gets * @param _wallet Address where collected funds will be forwarded to * @param _signer Address where collected funds will be forwarded to */ function initialize( address _token, uint256 _duration, uint256 _openTime, address _offeredCurrency, uint256 _offeredRate, uint256 _offeredCurrencyDecimals, address _wallet, address _signer ) external { require(msg.sender == factory, "POOL::UNAUTHORIZED"); token = IERC20(_token); openTime = _openTime; closeTime = _openTime.add(_duration); fundingWallet = _wallet; owner = tx.origin; paused = false; signer = _signer; offeredCurrencies[_offeredCurrency] = OfferedCurrency({ rate: _offeredRate, decimals: _offeredCurrencyDecimals }); emit PresalePoolCreated( _token, _openTime, closeTime, _offeredCurrency, _offeredCurrencyDecimals, _offeredRate, _wallet, owner ); } /** * @notice Returns the conversion rate when user buy by offered token * @return Returns only a fixed number of rate. */ function getOfferedCurrencyRate(address _token) public view returns (uint256) { return offeredCurrencies[_token].rate; } /** * @notice Returns the conversion rate decimals when user buy by offered token * @return Returns only a fixed number of decimals. */ function getOfferedCurrencyDecimals(address _token) public view returns (uint256) { return offeredCurrencies[_token].decimals; } /** * @notice Return the available tokens for purchase * @return availableTokens Number of total available */ function getAvailableTokensForSale() public view returns (uint256 availableTokens) { return token.balanceOf(address(this)).add(totalUnclaimed).sub(tokenSold); } /** * @notice Owner can set the offered token conversion rate. Receiver tokens = tradeTokens * tokenRate / 10 ** etherConversionRateDecimals * @param _rate Fixed number of ether rate * @param _decimals Fixed number of ether rate decimals */ function setOfferedCurrencyRateAndDecimals(address _token, uint256 _rate, uint256 _decimals) external onlyOwner { offeredCurrencies[_token].rate = _rate; offeredCurrencies[_token].decimals = _decimals; emit PoolStatsChanged(); } /** * @notice Owner can set the offered token conversion rate. Receiver tokens = tradeTokens * tokenRate / 10 ** etherConversionRateDecimals * @param _rate Fixed number of rate */ function setOfferedCurrencyRate(address _token, uint256 _rate) external onlyOwner { require(offeredCurrencies[_token].rate != _rate, "POOL::RATE_INVALID"); offeredCurrencies[_token].rate = _rate; emit PoolStatsChanged(); } /** * @notice Owner can set the offered token conversion rate. Receiver tokens = tradeTokens * tokenRate / 10 ** etherConversionRateDecimals * @param _newSigner Address of new signer */ function setNewSigner(address _newSigner) external onlyOwner { require(signer != _newSigner, "POOL::SIGNER_INVALID"); signer = _newSigner; } /** * @notice Owner can set the offered token conversion rate. Receiver tokens = tradeTokens * tokenRate / 10 ** etherConversionRateDecimals * @param _decimals Fixed number of decimals */ function setOfferedCurrencyDecimals(address _token, uint256 _decimals) external onlyOwner { require(offeredCurrencies[_token].decimals != _decimals, "POOL::RATE_INVALID"); offeredCurrencies[_token].decimals = _decimals; emit PoolStatsChanged(); } /** * @notice Owner can set the close time (time in seconds). User can buy before close time. * @param _closeTime Value in uint256 determine when we stop user to by tokens */ function setCloseTime(uint256 _closeTime) external onlyOwner() { require(_closeTime >= block.timestamp, "POOL::INVALID_TIME"); closeTime = _closeTime; emit PoolStatsChanged(); } /** * @notice Owner can set the open time (time in seconds). User can buy after open time. * @param _openTime Value in uint256 determine when we allow user to by tokens */ function setOpenTime(uint256 _openTime) external onlyOwner() { openTime = _openTime; emit PoolStatsChanged(); } /** * @notice Owner can set extentions. * @param _whitelist Value in bool. True if using whitelist */ function setPoolExtentions(bool _whitelist) external onlyOwner() { useWhitelist = _whitelist; emit PoolStatsChanged(); } function buyTokenByEtherWithPermission( address _beneficiary, address _candidate, uint256 _maxAmount, uint256 _minAmount, bytes memory _signature ) public payable whenNotPaused nonReentrant { uint256 weiAmount = msg.value; require(offeredCurrencies[address(0)].rate != 0, "POOL::PURCHASE_METHOD_NOT_ALLOWED"); _preValidatePurchase(_beneficiary, weiAmount); require(_validPurchase(), "POOL::ENDED"); require(_verifyWhitelist(_candidate, _maxAmount, _minAmount, _signature)); // calculate token amount to be created uint256 tokens = _getOfferedCurrencyToTokenAmount(address(0), weiAmount); require(getAvailableTokensForSale() >= tokens, "POOL::NOT_ENOUGHT_TOKENS_FOR_SALE"); require(tokens >= _minAmount || userPurchased[_candidate].add(tokens) >= _minAmount, "POOL::MIN_AMOUNT_UNREACHED"); require(userPurchased[_candidate].add(tokens) <= _maxAmount, "POOL::PURCHASE_AMOUNT_EXCEED_ALLOWANCE"); _forwardFunds(weiAmount); _updatePurchasingState(weiAmount, tokens); investedAmountOf[address(0)][_candidate] = investedAmountOf[address(0)][_candidate].add(weiAmount); emit TokenPurchaseByEther(msg.sender, _beneficiary, weiAmount, tokens); } function buyTokenByTokenWithPermission( address _beneficiary, address _token, uint256 _amount, address _candidate, uint256 _maxAmount, uint256 _minAmount, bytes memory _signature ) public whenNotPaused nonReentrant { require(offeredCurrencies[_token].rate != 0, "POOL::PURCHASE_METHOD_NOT_ALLOWED"); require(_validPurchase(), "POOL::ENDED"); require(_verifyWhitelist(_candidate, _maxAmount, _minAmount, _signature)); _verifyAllowance(msg.sender, _token, _amount); _preValidatePurchase(_beneficiary, _amount); uint256 tokens = _getOfferedCurrencyToTokenAmount(_token, _amount); require(getAvailableTokensForSale() >= tokens, "POOL::NOT_ENOUGHT_TOKENS_FOR_SALE"); require(tokens >= _minAmount || userPurchased[_candidate].add(tokens) >= _minAmount, "POOL::MIN_AMOUNT_UNREACHED"); require(userPurchased[_candidate].add(tokens) <= _maxAmount, "POOL:PURCHASE_AMOUNT_EXCEED_ALLOWANCE"); _forwardTokenFunds(_token, _amount); _updatePurchasingState(_amount, tokens); investedAmountOf[_token][_candidate] = investedAmountOf[address(0)][_candidate].add(_amount); emit TokenPurchaseByToken( msg.sender, _beneficiary, _token, _amount, tokens ); } /** * @notice Return true if pool has ended * @dev User cannot purchase / trade tokens when isFinalized == true * @return true if the ICO Ended. */ function isFinalized() public view returns (bool) { return block.timestamp >= closeTime; } /** * @notice Owner can receive their remaining tokens when ICO Ended * @dev Can refund remainning token if the ico ended * @param _wallet Address wallet who receive the remainning tokens when Ico end */ function refundRemainingTokens(address _wallet) external onlyOwner { require(isFinalized(), "POOL::ICO_NOT_ENDED"); require(token.balanceOf(address(this)) > 0, "POOL::EMPTY_BALANCE"); uint256 remainingTokens = getAvailableTokensForSale(); _deliverTokens(_wallet, remainingTokens); emit RefundedIcoToken(_wallet, remainingTokens); } /** * @notice User can receive their tokens when pool finished */ function claimTokens(address _candidate, uint256 _amount, bytes memory _signature) public { require(_verifyClaimToken(_candidate, _amount, _signature), "POOL::NOT_ALLOW_TO_CLAIM"); require(isFinalized(), "POOL::NOT_FINALLIZED"); uint256 claimAmount = userPurchased[_candidate].sub(userClaimed[_candidate]); if (claimAmount > _amount) { claimAmount = _amount; } userClaimed[_candidate] = userClaimed[_candidate].add(claimAmount); _deliverTokens(msg.sender, claimAmount); totalUnclaimed = totalUnclaimed.sub(claimAmount); emit TokenClaimed(msg.sender, claimAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal pure { require(_beneficiary != address(0), "POOL::INVALID_BENEFICIARY"); require(_weiAmount != 0, "POOL::INVALID_WEI_AMOUNT"); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _amount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getOfferedCurrencyToTokenAmount(address _token, uint256 _amount) internal view returns (uint256) { uint256 rate = getOfferedCurrencyRate(_token); uint256 decimals = getOfferedCurrencyDecimals(_token); return _amount.mul(rate).div(10**decimals); } /** * @dev Source of tokens. Transfer / mint * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds(uint256 _value) internal { address payable wallet = address(uint160(fundingWallet)); (bool success, ) = wallet.call{value: _value}(""); require(success, "POOL::WALLET_TRANSFER_FAILED"); } /** * @dev Determines how Token is stored/forwarded on purchases. */ function _forwardTokenFunds(address _token, uint256 _amount) internal { IERC20(_token).transferFrom(msg.sender, fundingWallet, _amount); } /** * @param _tokens Value of sold tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(uint256 _weiAmount, uint256 _tokens) internal { weiRaised = weiRaised.add(_weiAmount); tokenSold = tokenSold.add(_tokens); userPurchased[msg.sender] = userPurchased[msg.sender].add(_tokens); totalUnclaimed = totalUnclaimed.add(_tokens); } // @return true if the transaction can buy tokens function _validPurchase() internal view returns (bool) { bool withinPeriod = block.timestamp >= openTime && block.timestamp <= closeTime; return withinPeriod; } /** * @dev Transfer eth to an address * @param _to Address receiving the eth * @param _amount Amount of wei to transfer */ function _transfer(address _to, uint256 _amount) private { address payable payableAddress = address(uint160(_to)); (bool success, ) = payableAddress.call{value: _amount}(""); require(success, "POOL::TRANSFER_FEE_FAILED"); } /** * @dev Verify allowance of purchase * @param _user Address of buyer * @param _token token address of purchasing token * @param _amount Amount of token to buy pool token */ function _verifyAllowance( address _user, address _token, uint256 _amount ) private view { IERC20 tradeToken = IERC20(_token); uint256 allowance = tradeToken.allowance(_user, address(this)); require(allowance >= _amount, "POOL::TOKEN_NOT_APPROVED"); } /** * @dev Verify permission of purchase * @param _candidate Address of buyer * @param _maxAmount max token can buy * @param _minAmount min token can buy * @param _signature Signature of signers */ function _verifyWhitelist( address _candidate, uint256 _maxAmount, uint256 _minAmount, bytes memory _signature ) private view returns (bool) { require(msg.sender == _candidate, "POOL::WRONG_CANDIDATE"); if (useWhitelist) { return (verify(signer, _candidate, _maxAmount, _minAmount, _signature)); } return true; } /** * @dev Verify permission of purchase * @param _candidate Address of buyer * @param _amount claimable amount * @param _signature Signature of signers */ function _verifyClaimToken( address _candidate, uint256 _amount, bytes memory _signature ) private view returns (bool) { require(msg.sender == _candidate, "POOL::WRONG_CANDIDATE"); return (verifyClaimToken(signer, _candidate, _amount, _signature)); } }
Owner can set the open time (time in seconds). User can buy after open time. _openTime Value in uint256 determine when we allow user to by tokens/
function setOpenTime(uint256 _openTime) external onlyOwner() { openTime = _openTime; emit PoolStatsChanged(); }
125,900
./partial_match/1/0x6F9e33E225485Af4874FAC060F65ff60693ab4b8/sources/contracts/mixins/nftCollectionFactory/NFTCollectionFactoryACL.sol
The contract address which manages common roles. Defines a centralized admin role definition for permissioned functions below. return managerContract The contract address with role definitions./
function rolesManager() external view returns (address managerContract) { managerContract = address(_rolesManager); }
15,980,417
/** *Submitted for verification at Etherscan.io on 2021-06-25 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/@openzeppelin/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 on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/@openzeppelin/contracts/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/@openzeppelin/contracts/utils/Initializable.sol // solhint-disable-next-line compiler-version /** * @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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File contracts/@openzeppelin/contracts/utils/ContextUpgradeable.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File contracts/@openzeppelin/contracts/utils/Pausable.sol /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is 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. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File contracts/@openzeppelin/contracts/security/ReentrancyGuard.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 ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/@openzeppelin/contracts/IERC20Metadata.sol /** * @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/@openzeppelin/contracts/utils/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/@openzeppelin/contracts/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, 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 defaut 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 * overloaded; * * 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"); _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"); _approve(_msgSender(), spender, currentAllowance - 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 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"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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 += amount; _balances[account] += 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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/CosmosToken.sol contract CosmosERC20 is ERC20 { uint256 MAX_UINT = 2**256 - 1; uint8 immutable private _decimals; constructor( address peggyAddress_, string memory name_, string memory symbol_, uint8 decimals_ ) ERC20(name_, symbol_) { _decimals = decimals_; _mint(peggyAddress_, MAX_UINT); } function decimals() public view virtual override returns (uint8) { return _decimals; } } // File contracts/@openzeppelin/contracts/OwnableUpgradeableWithExpiry.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 OwnableUpgradeableWithExpiry is Initializable, ContextUpgradeable { address private _owner; uint256 private _deployTimestamp; 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; _deployTimestamp = block.timestamp; 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() external virtual onlyOwner { _renounceOwnership(); } /** * @dev Get the timestamp of ownership expiry. * @return The timestamp of ownership expiry. */ function getOwnershipExpiryTimestamp() public view returns (uint256) { return _deployTimestamp + 52 weeks; } /** * @dev Check if the contract ownership is expired. * @return True if the contract ownership is expired. */ function isOwnershipExpired() public view returns (bool) { return block.timestamp > getOwnershipExpiryTimestamp(); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called after ownership is expired. */ function renounceOwnershipAfterExpiry() external { require(isOwnershipExpired(), "Ownership not yet expired"); _renounceOwnership(); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function _renounceOwnership() private { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } uint256[49] private __gap; } // File contracts/Peggy.sol // This is used purely to avoid stack too deep errors // represents everything about a given validator set struct ValsetArgs { // the validators in this set, represented by an Ethereum address address[] validators; // the powers of the given validators in the same order as above uint256[] powers; // the nonce of this validator set uint256 valsetNonce; // the reward amount denominated in the below reward token, can be // set to zero uint256 rewardAmount; // the reward token, should be set to the zero address if not being used address rewardToken; } // Don't change the order of state for working upgrades. // AND BE AWARE OF INHERITANCE VARIABLES! // Inherited contracts contain storage slots and must be accounted for in any upgrades // always test an exact upgrade on testnet and localhost before mainnet upgrades. contract Peggy is Initializable, OwnableUpgradeableWithExpiry, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; // These are updated often bytes32 public state_lastValsetCheckpoint; mapping(address => uint256) public state_lastBatchNonces; mapping(bytes32 => uint256) public state_invalidationMapping; uint256 public state_lastValsetNonce = 0; uint256 public state_lastEventNonce = 0; // These are set once at initialization bytes32 public state_peggyId; uint256 public state_powerThreshold; // TransactionBatchExecutedEvent and SendToCosmosEvent both include the field _eventNonce. // This is incremented every time one of these events is emitted. It is checked by the // Cosmos module to ensure that all events are received in order, and that none are lost. // // ValsetUpdatedEvent does not include the field _eventNonce because it is never submitted to the Cosmos // module. It is purely for the use of relayers to allow them to successfully submit batches. event TransactionBatchExecutedEvent( uint256 indexed _batchNonce, address indexed _token, uint256 _eventNonce ); event SendToCosmosEvent( address indexed _tokenContract, address indexed _sender, bytes32 indexed _destination, uint256 _amount, uint256 _eventNonce ); event ERC20DeployedEvent( // TODO(xlab): _cosmosDenom can be represented as bytes32 to allow indexing string _cosmosDenom, address indexed _tokenContract, string _name, string _symbol, uint8 _decimals, uint256 _eventNonce ); event ValsetUpdatedEvent( uint256 indexed _newValsetNonce, uint256 _eventNonce, uint256 _rewardAmount, address _rewardToken, address[] _validators, uint256[] _powers ); function initialize( // A unique identifier for this peggy instance to use in signatures bytes32 _peggyId, // How much voting power is needed to approve operations uint256 _powerThreshold, // The validator set, not in valset args format since many of it's // arguments would never be used in this case address[] calldata _validators, uint256[] memory _powers ) external initializer { __Context_init_unchained(); __Ownable_init_unchained(); // CHECKS // Check that validators, powers, and signatures (v,r,s) set is well-formed require( _validators.length == _powers.length, "Malformed current validator set" ); // Check cumulative power to ensure the contract has sufficient power to actually // pass a vote uint256 cumulativePower = 0; for (uint256 i = 0; i < _powers.length; i++) { cumulativePower = cumulativePower + _powers[i]; if (cumulativePower > _powerThreshold) { break; } } require( cumulativePower > _powerThreshold, "Submitted validator set signatures do not have enough power." ); ValsetArgs memory _valset; _valset = ValsetArgs(_validators, _powers, 0, 0, address(0)); bytes32 newCheckpoint = makeCheckpoint(_valset, _peggyId); // ACTIONS state_peggyId = _peggyId; state_powerThreshold = _powerThreshold; state_lastValsetCheckpoint = newCheckpoint; state_lastEventNonce = state_lastEventNonce + 1; // LOGS emit ValsetUpdatedEvent( state_lastValsetNonce, state_lastEventNonce, 0, address(0), _validators, _powers ); } function lastBatchNonce(address _erc20Address) public view returns (uint256) { return state_lastBatchNonces[_erc20Address]; } // Utility function to verify geth style signatures function verifySig( address _signer, bytes32 _theHash, uint8 _v, bytes32 _r, bytes32 _s ) private pure returns (bool) { bytes32 messageDigest = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _theHash)); return _signer == ecrecover(messageDigest, _v, _r, _s); } // Make a new checkpoint from the supplied validator set // A checkpoint is a hash of all relevant information about the valset. This is stored by the contract, // instead of storing the information directly. This saves on storage and gas. // The format of the checkpoint is: // h(peggyId, "checkpoint", valsetNonce, validators[], powers[]) // Where h is the keccak256 hash function. // The validator powers must be decreasing or equal. This is important for checking the signatures on the // next valset, since it allows the caller to stop verifying signatures once a quorum of signatures have been verified. function makeCheckpoint(ValsetArgs memory _valsetArgs, bytes32 _peggyId) private pure returns (bytes32) { // bytes32 encoding of the string "checkpoint" bytes32 methodName = 0x636865636b706f696e7400000000000000000000000000000000000000000000; bytes32 checkpoint = keccak256( abi.encode( _peggyId, methodName, _valsetArgs.valsetNonce, _valsetArgs.validators, _valsetArgs.powers, _valsetArgs.rewardAmount, _valsetArgs.rewardToken ) ); return checkpoint; } function checkValidatorSignatures( // The current validator set and their powers address[] memory _currentValidators, uint256[] memory _currentPowers, // The current validator's signatures uint8[] memory _v, bytes32[] memory _r, bytes32[] memory _s, // This is what we are checking they have signed bytes32 _theHash, uint256 _powerThreshold ) private pure { uint256 cumulativePower = 0; for (uint256 i = 0; i < _currentValidators.length; i++) { // If v is set to 0, this signifies that it was not possible to get a signature from this validator and we skip evaluation // (In a valid signature, it is either 27 or 28) if (_v[i] != 0) { // Check that the current validator has signed off on the hash require( verifySig(_currentValidators[i], _theHash, _v[i], _r[i], _s[i]), "Validator signature does not match." ); // Sum up cumulative power cumulativePower = cumulativePower + _currentPowers[i]; // Break early to avoid wasting gas if (cumulativePower > _powerThreshold) { break; } } } // Check that there was enough power require( cumulativePower > _powerThreshold, "Submitted validator set signatures do not have enough power." ); // Success } // This updates the valset by checking that the validators in the current valset have signed off on the // new valset. The signatures supplied are the signatures of the current valset over the checkpoint hash // generated from the new valset. // Anyone can call this function, but they must supply valid signatures of state_powerThreshold of the current valset over // the new valset. function updateValset( // The new version of the validator set ValsetArgs memory _newValset, // The current validators that approve the change ValsetArgs memory _currentValset, // These are arrays of the parts of the current validator's signatures uint8[] memory _v, bytes32[] memory _r, bytes32[] memory _s ) external whenNotPaused { // CHECKS // Check that the valset nonce is greater than the old one require( _newValset.valsetNonce > _currentValset.valsetNonce, "New valset nonce must be greater than the current nonce" ); // Check that new validators and powers set is well-formed require( _newValset.validators.length == _newValset.powers.length, "Malformed new validator set" ); // Check that current validators, powers, and signatures (v,r,s) set is well-formed require( _currentValset.validators.length == _currentValset.powers.length && _currentValset.validators.length == _v.length && _currentValset.validators.length == _r.length && _currentValset.validators.length == _s.length, "Malformed current validator set" ); // Check that the supplied current validator set matches the saved checkpoint require( makeCheckpoint(_currentValset, state_peggyId) == state_lastValsetCheckpoint, "Supplied current validators and powers do not match checkpoint." ); // Check that enough current validators have signed off on the new validator set bytes32 newCheckpoint = makeCheckpoint(_newValset, state_peggyId); checkValidatorSignatures( _currentValset.validators, _currentValset.powers, _v, _r, _s, newCheckpoint, state_powerThreshold ); // ACTIONS // Stored to be used next time to validate that the valset // supplied by the caller is correct. state_lastValsetCheckpoint = newCheckpoint; // Store new nonce state_lastValsetNonce = _newValset.valsetNonce; // Send submission reward to msg.sender if reward token is a valid value if (_newValset.rewardToken != address(0) && _newValset.rewardAmount != 0) { IERC20(_newValset.rewardToken).safeTransfer( msg.sender, _newValset.rewardAmount ); } // LOGS state_lastEventNonce = state_lastEventNonce + 1; emit ValsetUpdatedEvent( _newValset.valsetNonce, state_lastEventNonce, _newValset.rewardAmount, _newValset.rewardToken, _newValset.validators, _newValset.powers ); } // submitBatch processes a batch of Cosmos -> Ethereum transactions by sending the tokens in the transactions // to the destination addresses. It is approved by the current Cosmos validator set. // Anyone can call this function, but they must supply valid signatures of state_powerThreshold of the current valset over // the batch. function submitBatch( // The validators that approve the batch ValsetArgs memory _currentValset, // These are arrays of the parts of the validators signatures uint8[] memory _v, bytes32[] memory _r, bytes32[] memory _s, // The batch of transactions uint256[] memory _amounts, address[] memory _destinations, uint256[] memory _fees, uint256 _batchNonce, address _tokenContract, // a block height beyond which this batch is not valid // used to provide a fee-free timeout uint256 _batchTimeout ) external nonReentrant whenNotPaused { // CHECKS scoped to reduce stack depth { // Check that the batch nonce is higher than the last nonce for this token require( state_lastBatchNonces[_tokenContract] < _batchNonce, "New batch nonce must be greater than the current nonce" ); // Check that the block height is less than the timeout height require( block.number < _batchTimeout, "Batch timeout must be greater than the current block height" ); // Check that current validators, powers, and signatures (v,r,s) set is well-formed require( _currentValset.validators.length == _currentValset.powers.length && _currentValset.validators.length == _v.length && _currentValset.validators.length == _r.length && _currentValset.validators.length == _s.length, "Malformed current validator set" ); // Check that the supplied current validator set matches the saved checkpoint require( makeCheckpoint(_currentValset, state_peggyId) == state_lastValsetCheckpoint, "Supplied current validators and powers do not match checkpoint." ); // Check that the transaction batch is well-formed require( _amounts.length == _destinations.length && _amounts.length == _fees.length, "Malformed batch of transactions" ); // Check that enough current validators have signed off on the transaction batch and valset checkValidatorSignatures( _currentValset.validators, _currentValset.powers, _v, _r, _s, // Get hash of the transaction batch and checkpoint keccak256( abi.encode( state_peggyId, // bytes32 encoding of "transactionBatch" 0x7472616e73616374696f6e426174636800000000000000000000000000000000, _amounts, _destinations, _fees, _batchNonce, _tokenContract, _batchTimeout ) ), state_powerThreshold ); // ACTIONS // Store batch nonce state_lastBatchNonces[_tokenContract] = _batchNonce; { // Send transaction amounts to destinations uint256 totalFee; for (uint256 i = 0; i < _amounts.length; i++) { IERC20(_tokenContract).safeTransfer(_destinations[i], _amounts[i]); totalFee = totalFee + _fees[i]; } if (totalFee > 0) { // Send transaction fees to msg.sender IERC20(_tokenContract).safeTransfer(msg.sender, totalFee); } } } // LOGS scoped to reduce stack depth { state_lastEventNonce = state_lastEventNonce + 1; emit TransactionBatchExecutedEvent( _batchNonce, _tokenContract, state_lastEventNonce ); } } function sendToCosmos( address _tokenContract, bytes32 _destination, uint256 _amount ) external whenNotPaused nonReentrant { IERC20(_tokenContract).safeTransferFrom(msg.sender, address(this), _amount); state_lastEventNonce = state_lastEventNonce + 1; emit SendToCosmosEvent( _tokenContract, msg.sender, _destination, _amount, state_lastEventNonce ); } function deployERC20( string calldata _cosmosDenom, string calldata _name, string calldata _symbol, uint8 _decimals ) external { // Deploy an ERC20 with entire supply granted to Peggy.sol CosmosERC20 erc20 = new CosmosERC20(address(this), _name, _symbol, _decimals); // Fire an event to let the Cosmos module know state_lastEventNonce = state_lastEventNonce + 1; emit ERC20DeployedEvent( _cosmosDenom, address(erc20), _name, _symbol, _decimals, state_lastEventNonce ); } function emergencyPause() external onlyOwner { _pause(); } function emergencyUnpause() external onlyOwner { _unpause(); } }
submitBatch processes a batch of Cosmos -> Ethereum transactions by sending the tokens in the transactions to the destination addresses. It is approved by the current Cosmos validator set. Anyone can call this function, but they must supply valid signatures of state_powerThreshold of the current valset over the batch. The validators that approve the batch These are arrays of the parts of the validators signatures The batch of transactions a block height beyond which this batch is not valid used to provide a fee-free timeout CHECKS scoped to reduce stack depth Check that the batch nonce is higher than the last nonce for this token Check that the block height is less than the timeout height Check that current validators, powers, and signatures (v,r,s) set is well-formed Check that the supplied current validator set matches the saved checkpoint Check that the transaction batch is well-formed Check that enough current validators have signed off on the transaction batch and valset Get hash of the transaction batch and checkpoint bytes32 encoding of "transactionBatch" ACTIONS Store batch nonce Send transaction amounts to destinations Send transaction fees to msg.sender LOGS scoped to reduce stack depth
function submitBatch( ValsetArgs memory _currentValset, uint8[] memory _v, bytes32[] memory _r, bytes32[] memory _s, uint256[] memory _amounts, address[] memory _destinations, uint256[] memory _fees, uint256 _batchNonce, address _tokenContract, uint256 _batchTimeout ) external nonReentrant whenNotPaused { { require( state_lastBatchNonces[_tokenContract] < _batchNonce, "New batch nonce must be greater than the current nonce" ); require( block.number < _batchTimeout, "Batch timeout must be greater than the current block height" ); require( _currentValset.validators.length == _currentValset.powers.length && _currentValset.validators.length == _v.length && _currentValset.validators.length == _r.length && _currentValset.validators.length == _s.length, "Malformed current validator set" ); require( makeCheckpoint(_currentValset, state_peggyId) == state_lastValsetCheckpoint, "Supplied current validators and powers do not match checkpoint." ); require( _amounts.length == _destinations.length && _amounts.length == _fees.length, "Malformed batch of transactions" ); checkValidatorSignatures( _currentValset.validators, _currentValset.powers, _v, _r, _s, keccak256( abi.encode( state_peggyId, 0x7472616e73616374696f6e426174636800000000000000000000000000000000, _amounts, _destinations, _fees, _batchNonce, _tokenContract, _batchTimeout ) ), state_powerThreshold ); state_lastBatchNonces[_tokenContract] = _batchNonce; { uint256 totalFee; for (uint256 i = 0; i < _amounts.length; i++) { IERC20(_tokenContract).safeTransfer(_destinations[i], _amounts[i]); totalFee = totalFee + _fees[i]; } if (totalFee > 0) { IERC20(_tokenContract).safeTransfer(msg.sender, totalFee); } } } { state_lastEventNonce = state_lastEventNonce + 1; emit TransactionBatchExecutedEvent( _batchNonce, _tokenContract, state_lastEventNonce ); } }
2,134,355
//SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "../inheritances/OwnableEnhanced.sol"; import "../interfaces/IEternalFactory.sol"; import "../interfaces/IEternalTreasury.sol"; import "../interfaces/IEternalStorage.sol"; import "../interfaces/ILoyaltyGage.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@traderjoe-xyz/core/contracts/traderjoe/interfaces/IJoeRouter02.sol"; import "@traderjoe-xyz/core/contracts/traderjoe/interfaces/IJoeFactory.sol"; import "@traderjoe-xyz/core/contracts/traderjoe/interfaces/IJoePair.sol"; import "@traderjoe-xyz/core/contracts/traderjoe/interfaces/IWAVAX.sol"; /** * @title Contract for the Eternal Treasury * @author Nobody (me) * @notice The Eternal Treasury contract holds all treasury logic */ contract EternalTreasury is IEternalTreasury, OwnableEnhanced { /////–––««« Variables: Interfaces, Addresses and Hashes »»»––––\\\\\ // The Trader Joe router interface IJoeRouter02 public immutable joeRouter; // The Trader Joe factory interface IJoeFactory public immutable joeFactory; // The Eternal shared storage interface IEternalStorage public immutable eternalStorage; // The Eternal factory interface IEternalFactory private eternalFactory; // The Eternal token interface IERC20 private eternal; // The address of the ETRNL/AVAX pair address private joePair; // The keccak256 hash of this contract's address bytes32 public immutable entity; /////–––««« Variables: Hidden Mappings »»»––––\\\\\ /** // The amount of ETRNL staked by any given individual user, converted to the "reserve" number space for fee distribution mapping (address => uint256) reserveBalances // The amount of ETRNL staked by any given individual user, converted to the regular number space (raw number, no fees) mapping (address => uint256) stakedBalances // The amount of a given asset provided by a user in a liquid gage of said asset mapping (address => mapping (address => uint256)) amountProvided // The amount of liquidity tokens provided for a given ETRNL/Asset pair mapping (address => mapping (address => uint256)) liquidityProvided */ /////–––««« Variables: Automatic Liquidity Provision »»»––––\\\\\ // Determines whether the contract is tasked with providing liquidity using part of the transaction fees bytes32 public immutable autoLiquidityProvision; // Determines whether an auto-liquidity provision process is undergoing bool private undergoingSwap; /////–––««« Variables: Gaging & Staking »»»––––\\\\\ // The total number of ETRNL staked by users bytes32 public immutable totalStakedBalances; // Used to increase or decrease everyone's accumulated fees bytes32 public immutable reserveStakedBalances; // The (percentage) fee rate applied to any gage-reward computations not using ETRNL (x 10 ** 5) bytes32 public immutable feeRate; // Allows contract to receive AVAX tokens // solhint-disable-next-line no-empty-blocks receive() external payable {} /////–––««« Constructors & Initializers »»»––––\\\\\ constructor (address _eternalStorage, address _eternalFactory, address _eternal) { // Set initial Storage, Factory and Token addresses eternalStorage = IEternalStorage(_eternalStorage); eternalFactory = IEternalFactory(_eternalFactory); eternal = IERC20(_eternal); // Initialize the Trader Joe router IJoeRouter02 _joeRouter = IJoeRouter02(0x60aE616a2155Ee3d9A68541Ba4544862310933d4); joeRouter = _joeRouter; IJoeFactory _joeFactory = IJoeFactory(_joeRouter.factory()); joeFactory = _joeFactory; // Create pair address joePair = _joeFactory.createPair(address(eternal), _joeRouter.WAVAX()); // Initialize keccak256 hashes entity = keccak256(abi.encodePacked(address(this))); autoLiquidityProvision = keccak256(abi.encodePacked("autoLiquidityProvision")); totalStakedBalances = keccak256(abi.encodePacked("totalStakedBalances")); reserveStakedBalances = keccak256(abi.encodePacked("reserveStakedBalances")); feeRate = keccak256(abi.encodePacked("feeRate")); } function initialize(address _fund) external onlyAdmin { // The largest possible number in a 256-bit integer uint256 max = ~uint256(0); // Set initial staking balances uint256 totalStake = eternal.balanceOf(address(this)); eternalStorage.setUint(entity, totalStakedBalances, totalStake); eternalStorage.setUint(entity, reserveStakedBalances, (max - 100 * (max % totalStake))); eternalStorage.setUint(entity, keccak256(abi.encodePacked("stakedBalances", address(this))), totalStake); eternalStorage.setUint(entity, keccak256(abi.encodePacked("reserveBalances", address(this))), max - 10 * (max % totalStake)); eternalStorage.setBool(entity, autoLiquidityProvision, true); // Set initial feeRate eternalStorage.setUint(entity, feeRate, 500); attributeFundRights(_fund); } /////–––««« Modifiers »»»––––\\\\\ /** * Ensures the contract doesn't affect its AVAX balance when swapping (prevents it from getting caught in a circular liquidity event). */ modifier haltsActivity() { undergoingSwap = true; _; undergoingSwap = false; } /** * Reverts if activity is halted (a liquidity swap is in progress) */ modifier activityHalted() { require(!undergoingSwap, "A liquidity swap is in progress"); _; } /////–––««« Variable state-inspection functions »»»––––\\\\\ /** * @notice View the address of the ETRNL/AVAX pair on Trader Joe. */ function viewPair() external view override returns(address) { return joePair; } /** * @notice View whether a liquidity swap is currently in progress */ function viewUndergoingSwap() external view override returns(bool) { return undergoingSwap; } /////–––««« Reserve Utility functions »»»––––\\\\\ /** * @notice Converts a given staked amount to the "reserve" number space * @param amount The specified staked amount * @return The reserve number space of the staked amount */ function convertToReserve(uint256 amount) public view override returns(uint256) { uint256 currentRate = eternalStorage.getUint(entity, reserveStakedBalances) / eternalStorage.getUint(entity, totalStakedBalances); return amount * currentRate; } /** * @notice Converts a given reserve amount to the regular number space (staked) * @param reserveAmount The specified reserve amount * @return The regular number space value of the reserve amount */ function convertToStaked(uint256 reserveAmount) public view override returns(uint256) { uint256 currentRate = eternalStorage.getUint(entity, reserveStakedBalances) / eternalStorage.getUint(entity, totalStakedBalances); return reserveAmount / currentRate; } /** * @notice Computes the equivalent of an asset to an other asset and the minimum amount of the two needed to provide liquidity * @param asset The first specified asset, which we want to convert * @param otherAsset The other specified asset * @param amountAsset The amount of the first specified asset * @param uncertainty The minimum loss to deduct from each minimum in case of price changes * @return minOtherAsset The minimum amount of otherAsset needed to provide liquidity (not given if uncertainty = 0) * @return minAsset The minimum amount of Asset needed to provide liquidity (not given if uncertainty = 0) * @return amountOtherAsset The equivalent in otherAsset of the given amount of asset */ function computeMinAmounts(address asset, address otherAsset, uint256 amountAsset, uint256 uncertainty) public view override returns(uint256 minOtherAsset, uint256 minAsset, uint256 amountOtherAsset) { // Get the reserve ratios for the Asset-otherAsset pair (uint256 reserveAsset, uint256 reserveOtherAsset) = _fetchPairReserves(asset, otherAsset); // Determine a reasonable minimum amount of asset and otherAsset based on current reserves (with a tolerance = 1 / uncertainty) amountOtherAsset = joeRouter.quote(amountAsset, reserveAsset, reserveOtherAsset); if (uncertainty != 0) { minAsset = joeRouter.quote(amountOtherAsset, reserveOtherAsset, reserveAsset); minAsset -= minAsset / uncertainty; minOtherAsset = amountOtherAsset - (amountOtherAsset / uncertainty); } } /** * @notice View the liquidity reserves of a given asset pair on Trader Joe * @param asset The first asset of the specified pair * @param otherAsset The second asset of the specified pair * @return reserveAsset The reserve amount of the first asset * @return reserveOtherAsset The reserve amount of the second asset */ function _fetchPairReserves(address asset, address otherAsset) private view returns(uint256 reserveAsset, uint256 reserveOtherAsset) { (uint256 reserveA, uint256 reserveB,) = IJoePair(joeFactory.getPair(asset, otherAsset)).getReserves(); (reserveAsset, reserveOtherAsset) = asset < otherAsset ? (reserveA, reserveB) : (reserveB, reserveA); } /** * @notice Removes liquidity provided by a liquid gage, for a given ETRNL-Asset pair * @param rAsset The address of the specified asset * @param providedAsset The amount of the asset which was provided as liquidity * @param receiver The address of the liquid gage's receiver * @return The amount of ETRNL and Asset obtained from removing liquidity */ function _removeLiquidity(address rAsset, uint256 providedAsset, address receiver) private returns(uint256, uint256) { (uint256 minETRNL, uint256 minAsset,) = computeMinAmounts(rAsset, address(eternal), providedAsset, 100); uint256 liquidity = eternalStorage.getUint(entity, keccak256(abi.encodePacked("liquidity", receiver, rAsset))); return joeRouter.removeLiquidity(address(eternal), rAsset, liquidity, minETRNL/2, minAsset/2, address(this), block.timestamp); } /** * @notice Swap a given amount of tokens for ETRNL * @param amount The specified amount of tokens * @param asset The address of the asset being swapped * @return minAsset The minimum amount of tokens received from the swap with a 1% uncertainty */ function _swapTokensForETRNL(uint256 amount, address asset) private returns(uint256 minAsset) { address[] memory path = new address[](2); path[0] = asset; path[1] = address(eternal); // Calculate the minimum amount of ETRNL to swap the asset for (with a tolerance of 1%) (uint256 reserveETRNL, uint256 reserveAsset) = _fetchPairReserves(address(eternal), asset); minAsset = _computeMinSwapAmount(amount, reserveAsset, reserveETRNL, 100); // Swap the asset for ETRNL require(IERC20(asset).approve(address(joeRouter), amount), "Approve failed"); if (asset == joeRouter.WAVAX()) { joeRouter.swapExactAVAXForTokensSupportingFeeOnTransferTokens{value : amount}(minAsset, path, address(this), block.timestamp); } else { joeRouter.swapExactTokensForTokens(amount, minAsset, path, address(this), block.timestamp); } } /////–––««« Gage-logic functions »»»––––\\\\\ /** * @notice Funds a given liquidity gage with ETRNL, provides liquidity using ETRNL and the receiver's asset and transfers a bonus to the receiver * @param gage The address of the specified liquidity gage * @param receiver The address of the receiver * @param asset The address of the asset provided by the receiver * @param userAmount The amount of the asset provided by the receiver * @param rRisk The treasury's (distributor) risk percentage * @param dRisk The receiver's bonus percentage * * Requirements: * * - Only callable by the Eternal Platform */ function fundEternalLiquidGage(address gage, address receiver, address asset, uint256 userAmount, uint256 rRisk, uint256 dRisk) external payable override { // Checks require(_msgSender() == address(eternalFactory), "msg.sender must be the platform"); // Compute minimum amounts and the amount of ETRNL needed to provide liquidity uint256 providedETRNL; uint256 providedAsset; uint256 liquidity; (uint256 minETRNL, uint256 minAsset, uint256 amountETRNL) = computeMinAmounts(asset, address(eternal), userAmount, 100); // Add liquidity to the ETRNL/Asset pair require(eternal.approve(address(joeRouter), amountETRNL), "Approve failed"); if (asset == joeRouter.WAVAX()) { (providedETRNL, providedAsset, liquidity) = joeRouter.addLiquidityAVAX{value: msg.value}(address(eternal), amountETRNL, minETRNL, minAsset, address(this), block.timestamp); } else { (providedETRNL, providedAsset, liquidity) = joeRouter.addLiquidity(address(eternal), asset, amountETRNL, userAmount, minETRNL, minAsset, address(this), block.timestamp); } // Save the true amount provided as liquidity by the receiver and the actual liquidity amount eternalStorage.setUint(entity, keccak256(abi.encodePacked("amountProvided", receiver, asset)), providedAsset); eternalStorage.setUint(entity, keccak256(abi.encodePacked("liquidity", receiver, asset)), liquidity); // Initialize the liquid gage and transfer the user's instant reward ILoyaltyGage(gage).initialize(asset, address(eternal), userAmount, providedETRNL, rRisk, dRisk); require(eternal.transfer(receiver, providedETRNL * dRisk / (10 ** 4)), "Failed to transfer bonus"); } /** * @notice Settles a given ETRNL liquid gage * @param receiver The address of the receiver * @param id The id of the specified liquid gage * @param winner Whether the gage closed in favor of the receiver or not * * Requirements: * * - Only callable by an Eternal-deployed gage */ function settleGage(address payable receiver, uint256 id, bool winner) external override activityHalted { // Checks bytes32 factory = keccak256(abi.encodePacked(address(eternalFactory))); address gageAddress = eternalStorage.getAddress(factory, keccak256(abi.encodePacked("gages", id))); require(_msgSender() == gageAddress, "msg.sender must be the gage"); // Fetch the liquid gage data (address rAsset,, uint256 rRisk) = ILoyaltyGage(gageAddress).viewUserData(receiver); (,uint256 dAmount, uint256 dRisk) = ILoyaltyGage(gageAddress).viewUserData(address(this)); uint256 providedAsset = eternalStorage.getUint(entity, keccak256(abi.encodePacked("amountProvided", receiver, rAsset))); // Remove the liquidity for this gage (uint256 amountETRNL, uint256 amountAsset) = _removeLiquidity(rAsset, providedAsset, receiver); // Compute and transfer the net gage deposit + any rewards due to the receiver uint256 eternalRewards = amountETRNL > dAmount ? amountETRNL - dAmount : 0; uint256 eternalFee = eternalStorage.getUint(entity, feeRate) * providedAsset / (10 ** 5); if (winner) { require(eternal.transfer(receiver, amountETRNL * dRisk / (10 ** 4)), "Failed to transfer ETRNL reward"); // Compute the net liquidity rewards left to distribute to stakers //solhint-disable-next-line reentrancy eternalRewards = eternalRewards == 0 ? 0 : eternalRewards - (eternalRewards * dRisk / (10 ** 4)); } else { eternalFee += amountAsset * rRisk / (10 ** 4); amountAsset -= amountAsset * rRisk / (10 ** 4); // Compute the net liquidity rewards + gage deposit left to distribute to staker //solhint-disable-next-line reentrancy eternalRewards = amountETRNL * rRisk / (10 ** 4); } if (rAsset != joeRouter.WAVAX()) { require(IERC20(rAsset).transfer(receiver, amountAsset - eternalFee), "Failed to transfer ERC20 reward"); } else { IWAVAX(rAsset).deposit{value: amountAsset}(); IWAVAX(rAsset).withdraw(amountAsset); (bool success, ) = receiver.call{value: amountAsset}(""); require(success, "Failed to transfer AVAX reward"); } // Update staker's fees w.r.t the gage fee, gage rewards and liquidity rewards and buy ETRNL with the fee // Fees and rewards are both calculated in terms of ETRNL { uint256 totalFee = eternalRewards + _swapTokensForETRNL(eternalFee, rAsset); eternalStorage.setUint(entity, reserveStakedBalances, eternalStorage.getUint(entity, reserveStakedBalances) - convertToReserve(totalFee)); } } /////–––««« Staking-logic functions »»»––––\\\\\ /** * @notice Stakes a given amount of ETRNL into the treasury * @param amount The specified amount of ETRNL being staked * * Requirements: * * - Staked amount must be greater than 0 */ function stake(uint256 amount) external override { require(amount > 0, "Amount must be greater than 0"); require(eternal.transferFrom(_msgSender(), address(this), amount), "Transfer failed"); emit Stake(_msgSender(), amount); // Update user/total staked and reserve balances bytes32 reserveBalances = keccak256(abi.encodePacked("reserveBalances", _msgSender())); bytes32 stakedBalances = keccak256(abi.encodePacked("stakedBalances", _msgSender())); uint256 reserveAmount = convertToReserve(amount); uint256 reserveBalance = eternalStorage.getUint(entity, reserveBalances); uint256 stakedBalance = eternalStorage.getUint(entity, stakedBalances); eternalStorage.setUint(entity, reserveBalances, reserveBalance + reserveAmount); eternalStorage.setUint(entity, stakedBalances, stakedBalance + amount); eternalStorage.setUint(entity, reserveStakedBalances, eternalStorage.getUint(entity, reserveStakedBalances) + reserveAmount); eternalStorage.setUint(entity, totalStakedBalances, eternalStorage.getUint(entity, totalStakedBalances) + amount); } /** * @notice Unstakes a user's given amount of ETRNL and transfers the user's accumulated rewards proportional to that amount (in ETRNL) * @param amount The specified amount of ETRNL being unstaked * * Requirements: * * - A liquidity swap should not be in progress */ function unstake(uint256 amount) external override { bytes32 stakedBalances = keccak256(abi.encodePacked("stakedBalances", _msgSender())); uint256 stakedBalance = eternalStorage.getUint(entity, stakedBalances); require(amount <= stakedBalance , "Amount exceeds staked balance"); emit Unstake(_msgSender(), amount); bytes32 reserveBalances = keccak256(abi.encodePacked("reserveBalances", _msgSender())); uint256 reserveBalance = eternalStorage.getUint(entity, reserveBalances); // Reward user with percentage of fees proportional to the amount he is withdrawing uint256 reserveAmount = amount * reserveBalance / stakedBalance; // Update user/total staked and reserve balances eternalStorage.setUint(entity, reserveBalances, reserveBalance - reserveAmount); eternalStorage.setUint(entity, stakedBalances, stakedBalance - amount); eternalStorage.setUint(entity, reserveStakedBalances, eternalStorage.getUint(entity, reserveStakedBalances) - reserveAmount); eternalStorage.setUint(entity, totalStakedBalances, eternalStorage.getUint(entity, totalStakedBalances) - amount); require(eternal.transfer(_msgSender(), convertToStaked(reserveAmount)), "Transfer failed"); } /////–––««« Automatic liquidity provision functions »»»––––\\\\\ /** * @notice Computes the minimum amount to swap a given asset for another asset, with a given percentage uncertainty * @param amountAsset The specified asset being swapped * @param reserveAsset The reserve of the asset being swapped * @param reserveOtherAsset The reserve of the asset being swapped for * @param uncertainty The denominator of the percentage uncertainty if it were viewed as (1 / uncertainty) */ function _computeMinSwapAmount(uint256 amountAsset, uint256 reserveAsset, uint256 reserveOtherAsset, uint256 uncertainty) private view returns(uint256 minOtherAsset) { uint256 amountOtherAsset = joeRouter.getAmountOut(amountAsset, reserveAsset, reserveOtherAsset); minOtherAsset = amountOtherAsset - (amountOtherAsset / uncertainty); } /** * @notice Swaps a given amount of ETRNL for AVAX using Trader Joe. (Used for auto-liquidity swaps) * @param amount The amount of ETRNL to be swapped for AVAX */ function _swapETRNLForAVAX(uint256 amount, uint256 reserveETRNL, uint256 reserveAVAX) private { address[] memory path = new address[](2); path[0] = address(eternal); path[1] = joeRouter.WAVAX(); // Calculate the minimum amount of AVAX to swap the ETRNL for (with a tolerance of 1%) uint256 minAVAX = _computeMinSwapAmount(amount, reserveETRNL, reserveAVAX, 100); // Swap the ETRNL for AVAX require(eternal.approve(address(joeRouter), amount), "Approve failed"); joeRouter.swapExactTokensForAVAXSupportingFeeOnTransferTokens(amount, minAVAX, path, address(this), block.timestamp); } /** * @notice Provides liquidity to the ETRNL/AVAX pair on Trader Joe for the EternalToken contract. * @param contractBalance The contract's ETRNL balance * * Requirements: * * - There cannot already be a liquidity swap in progress * - Automatic liquidity provision must be enabled * - Caller can only be the Eternal Token contract */ function provideLiquidity(uint256 contractBalance) external override activityHalted { require(_msgSender() == address(eternal), "Only callable by ETRNL contract"); require(eternalStorage.getBool(entity, autoLiquidityProvision), "Auto-liquidity is disabled"); _provideLiquidity(contractBalance); } /** * @notice Converts half the contract's balance to AVAX and adds liquidity to the ETRNL/AVAX pair. * @param contractBalance The contract's ETRNL balance */ function _provideLiquidity(uint256 contractBalance) private haltsActivity { // Split the contract's balance into two halves uint256 half = contractBalance / 2; uint256 amountETRNL = contractBalance - half; // Get the reserve ratios for the ETRNL-AVAX pair (uint256 reserveETRNL, uint256 reserveAVAX) = _fetchPairReserves(address(eternal), joeRouter.WAVAX()); // Capture the initial balance to later compute the difference uint256 initialBalance = address(this).balance; // Swap half the contract's ETRNL balance to AVAX _swapETRNLForAVAX(half, reserveETRNL, reserveAVAX); // Compute the amount of AVAX received from the swap uint256 amountAVAX = address(this).balance - initialBalance; // Determine a reasonable minimum amount of ETRNL and AVAX based on current reserves (with a tolerance of 1%) uint256 minAVAX = joeRouter.quote(amountETRNL, reserveETRNL, reserveAVAX); minAVAX -= minAVAX / 100; uint256 minETRNL = joeRouter.quote(amountAVAX, reserveAVAX, reserveETRNL); minETRNL -= minETRNL / 100; // Add liquidity to the ETRNL/AVAX pair emit AutomaticLiquidityProvision(amountETRNL, contractBalance, amountAVAX); eternal.approve(address(joeRouter), amountETRNL); // Update the total liquidity (,,uint256 liquidity) = joeRouter.addLiquidityAVAX{value: amountAVAX}(address(eternal), amountETRNL, minETRNL, minAVAX, address(this), block.timestamp); bytes32 totalLiquidity = keccak256(abi.encodePacked("liquidityProvided", address(this), joeRouter.WAVAX())); uint256 currentLiquidity = eternalStorage.getUint(entity, totalLiquidity); eternalStorage.setUint(entity, totalLiquidity, currentLiquidity + liquidity); } /////–––««« Fund-only functions »»»––––\\\\\ /** * @notice Transfers a given amount of AVAX from the contract to an address. (Fund only) * @param recipient The address to which the AVAX is to be sent * @param amount The specified amount of AVAX to transfer * * Requirements: * * - Only callable by the Eternal Fund * - A liquidity swap should not be in progress * - The contract's balance must have enough funds to accomodate the withdrawal */ function withdrawAVAX(address payable recipient, uint256 amount) external override onlyFund activityHalted { require(amount < address(this).balance, "Insufficient balance"); emit AVAXTransferred(amount, recipient); (bool success, ) = recipient.call{value: amount}(""); require(success, "Failed to transfer AVAX"); } /** * @notice Transfers a given amount of a token from the contract to an address. (Fund only) * @param asset The address of the asset being withdrawn * @param recipient The address to which the ETRNL is to be sent * @param amount The specified amount of ETRNL to transfer * * Requirements: * * - Only callable by the Eternal Fund */ function withdrawAsset(address asset, address recipient, uint256 amount) external override onlyFund { emit AssetTransferred(asset, amount, recipient); require(IERC20(asset).transfer(recipient, amount), "Asset withdrawal failed"); } /** * @notice Updates the address of the Eternal Factory contract * @param newContract The new address for the Eternal Factory contract * * Requirements: * * - Only callable by the Eternal Fund */ function setEternalFactory(address newContract) external onlyFund { eternalFactory = IEternalFactory(newContract); } /** * @notice Updates the address of the Eternal Token contract * @param newContract The new address for the Eternal Token contract * * Requirements: * * - Only callable by the Eternal Fund */ function setEternalToken(address newContract) external onlyFund { eternal = IERC20(newContract); } }
Funds a given liquidity gage with ETRNL, provides liquidity using ETRNL and the receiver's asset and transfers a bonus to the receiver gage The address of the specified liquidity gage receiver The address of the receiver asset The address of the asset provided by the receiver userAmount The amount of the asset provided by the receiver rRisk The treasury's (distributor) risk percentage dRisk The receiver's bonus percentage Requirements: - Only callable by the Eternal Platform/ Checks Compute minimum amounts and the amount of ETRNL needed to provide liquidity Add liquidity to the ETRNL/Asset pair
function fundEternalLiquidGage(address gage, address receiver, address asset, uint256 userAmount, uint256 rRisk, uint256 dRisk) external payable override { require(_msgSender() == address(eternalFactory), "msg.sender must be the platform"); uint256 providedETRNL; uint256 providedAsset; uint256 liquidity; (uint256 minETRNL, uint256 minAsset, uint256 amountETRNL) = computeMinAmounts(asset, address(eternal), userAmount, 100); require(eternal.approve(address(joeRouter), amountETRNL), "Approve failed"); if (asset == joeRouter.WAVAX()) { (providedETRNL, providedAsset, liquidity) = joeRouter.addLiquidity(address(eternal), asset, amountETRNL, userAmount, minETRNL, minAsset, address(this), block.timestamp); } eternalStorage.setUint(entity, keccak256(abi.encodePacked("liquidity", receiver, asset)), liquidity); require(eternal.transfer(receiver, providedETRNL * dRisk / (10 ** 4)), "Failed to transfer bonus"); }
14,073,590
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(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 MUL487(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 DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(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 MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(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 SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(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.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(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).ISCONTRACT107(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library 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; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(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; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract 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_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view {
14,087,940
./full_match/1/0xB6764c2Cc8F1fDCd89Af1C3e246f886579746233/sources/contracts/strategies/ConvexGeneralizedMetaStrategy.sol
Take 3pool LP and deposit it to metapool. Take the LP from metapool and deposit them to Convex./
function _lpDepositAll() internal override { IERC20 threePoolLp = IERC20(pTokenAddress); ICurvePool curvePool = ICurvePool(platformAddress); uint256 threePoolLpBalance = threePoolLp.balanceOf(address(this)); uint256 curve3PoolVirtualPrice = curvePool.get_virtual_price(); uint256 threePoolLpDollarValue = threePoolLpBalance.mulTruncate( curve3PoolVirtualPrice ); uint256[2] memory _amounts = [0, threePoolLpBalance]; uint256 metapoolVirtualPrice = metapool.get_virtual_price(); uint256 minReceived = threePoolLpDollarValue .divPrecisely(metapoolVirtualPrice) .mulTruncate(uint256(1e18) - MAX_SLIPPAGE); uint256 metapoolLp = metapool.add_liquidity(_amounts, minReceived); bool success = IConvexDeposits(cvxDepositorAddress).deposit( cvxDepositorPTokenId, metapoolLp, ); require(success, "Failed to deposit to Convex");
8,370,630
pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20 { using SafeMath for uint256; mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; uint256 private totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); 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 Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances[_account] = balances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) internal { require(_account != 0); require(_amount <= balances[_account]); totalSupply_ = totalSupply_.sub(_amount); balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal _burn function. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burnFrom(address _account, uint256 _amount) internal { require(_amount <= allowed[_account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_account][msg.sender] = allowed[_account][msg.sender].sub(_amount); _burn(_account, _amount); } } /** * @title FasTrader Token */ contract FasTrader is StandardToken { string public constant name = "FasTrader"; string public constant symbol = "FTD"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 100000000000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() public { _mint(msg.sender, INITIAL_SUPPLY); } }
Multiplies two numbers, reverts on overflow./ Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-solidity/pull/522
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; }
176,265
// SPDX-License-Identifier: MIT pragma solidity 0.5.17; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; /** * @title RariGovernanceToken * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @notice RariGovernanceToken is the contract behind the Rari Governance Token (RGT), an ERC20 token accounting for the ownership of Rari Stable Pool, Yield Pool, and Ethereum Pool. */ contract RariGovernanceToken is Initializable, ERC20, ERC20Detailed, ERC20Burnable, ERC20Pausable { using SafeERC20 for IERC20; /** * @dev Initializer that reserves 8.75 million RGT for liquidity mining and 1.25 million RGT to the team/advisors/etc. */ function initialize(address distributor, address vesting) public initializer { ERC20Detailed.initialize("Rari Governance Token", "RGT", 18); ERC20Pausable.initialize(msg.sender); _mint(distributor, 8750000 * (10 ** uint256(decimals()))); _mint(vesting, 1250000 * (10 ** uint256(decimals()))); } /** * @dev Boolean indicating if this RariFundToken contract has been deployed at least `v1.4.0` or upgraded to at least `v1.4.0`. */ bool private upgraded1; /** * @dev Boolean indicating if this RariFundToken contract has been deployed at least `v1.4.0` or upgraded to at least `v1.4.0`. */ bool private upgraded2; /** * @dev Upgrades RariGovernanceToken from `v1.3.0` to `v1.4.0`. */ function upgrade2() external onlyPauser { require(!upgraded2, "Already upgraded."); _mint(msg.sender, 2500000 * (10 ** uint256(decimals()))); upgraded2 = true; } /** * @dev Forwards tokens accidentally sent to this contract to the specified address. * At no point in time should this contract hold any tokens. * @param erc20Contract The ERC20 contract address of the token to forward. * @param to The destination address to which the funds will be forwarded. * @param amount Amount of tokens to forward. */ function sweepLostFunds(address erc20Contract, address to, uint256 amount) external onlyPauser { IERC20(erc20Contract).safeTransfer(to, amount); } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); _moveDelegates(delegates[_msgSender()], delegates[recipient], safe96(amount, "RGT::transfer: amount exceeds 96 bits")); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _moveDelegates(delegates[sender], delegates[recipient], safe96(amount, "RGT::transferFrom: amount exceeds 96 bits")); _approve(sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "RGT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "RGT::delegateBySig: invalid nonce"); require(now <= expiry, "RGT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "RGT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(balanceOf(delegator), "RGT::_delegate: balance exceeds 96 bits"); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "RGT::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "RGT::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "RGT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/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 Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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]; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "../Roles.sol"; contract PauserRole is Initializable, Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require(isPauser(_msgSender()), "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 onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../GSN/Context.sol"; import "../access/roles/PauserRole.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Initializable, Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ function initialize(address sender) public initializer { PauserRole.initialize(sender); _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Initializable, Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./ERC20.sol"; import "../../lifecycle/Pausable.sol"; /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is Initializable, ERC20, Pausable { function initialize(address sender) public initializer { Pausable.initialize(sender); } function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.5; /** * @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"); } } 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; }
See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./
function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); _moveDelegates(delegates[_msgSender()], delegates[recipient], safe96(amount, "RGT::transfer: amount exceeds 96 bits")); return true; }
449,216
pragma solidity ^0.4.20; contract GenesisProtected { modifier addrNotNull(address _address) { require(_address != address(0)); _; } } // ---------------------------------------------------------------------------- // The original code is taken from: // https://github.com/OpenZeppelin/zeppelin-solidity: // master branch from zeppelin-solidity/contracts/ownership/Ownable.sol // Changed function name: transferOwnership -> setOwner. // Added inheritance from GenesisProtected (address != 0x0). // setOwner refactored for emitting after owner replacing. // ---------------------------------------------------------------------------- /** * @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 is GenesisProtected { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a _new. * @param a The address to transfer ownership to. */ function setOwner(address a) external onlyOwner addrNotNull(a) { owner = a; emit OwnershipReplaced(msg.sender, a); } event OwnershipReplaced( address indexed previousOwner, address indexed newOwner ); } contract Enums { // Type for mapping uint (index) => name for baskets types described in WP enum BasketType { unknown, // 0 unknown team, // 1 Team foundation, // 2 Foundation arr, // 3 Advertisement, Referral program, Reward advisors, // 4 Advisors bounty, // 5 Bounty referral, // 6 Referral referrer // 7 Referrer } } contract WPTokensBaskets is Ownable, Enums { // This mapping holds all accounts ever used as baskets forever mapping (address => BasketType) internal types; // Baskets for tokens address public team; address public foundation; address public arr; address public advisors; address public bounty; // Public constructor function WPTokensBaskets( address _team, address _foundation, address _arr, address _advisors, address _bounty ) public { setTeam(_team); setFoundation(_foundation); setARR(_arr); setAdvisors(_advisors); setBounty(_bounty); } // Fallback function - do not apply any ether to this contract. function () external payable { revert(); } // Last resort to return ether. // See the last warning at // http://solidity.readthedocs.io/en/develop/contracts.html#fallback-function // for such cases. function transferEtherTo(address a) external onlyOwner addrNotNull(a) { a.transfer(address(this).balance); } function typeOf(address a) public view returns (BasketType) { return types[a]; } // Return truth if given address is not registered as token basket. function isUnknown(address a) public view returns (bool) { return types[a] == BasketType.unknown; } function isTeam(address a) public view returns (bool) { return types[a] == BasketType.team; } function isFoundation(address a) public view returns (bool) { return types[a] == BasketType.foundation; } function setTeam(address a) public onlyOwner addrNotNull(a) { require(isUnknown(a)); types[team = a] = BasketType.team; } function setFoundation(address a) public onlyOwner addrNotNull(a) { require(isUnknown(a)); types[foundation = a] = BasketType.foundation; } function setARR(address a) public onlyOwner addrNotNull(a) { require(isUnknown(a)); types[arr = a] = BasketType.arr; } function setAdvisors(address a) public onlyOwner addrNotNull(a) { require(isUnknown(a)); types[advisors = a] = BasketType.advisors; } function setBounty(address a) public onlyOwner addrNotNull(a) { require(types[a] == BasketType.unknown); types[bounty = a] = BasketType.bounty; } } // ---------------------------------------------------------------------------- // The original code is taken from: // https://github.com/OpenZeppelin/zeppelin-solidity: // master branch from zeppelin-solidity/contracts/math/SafeMath.sol // ---------------------------------------------------------------------------- /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // The original code is taken from: // https://theethereum.wiki/w/index.php/ERC20_Token_Standard // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval( address indexed tokenOwner, address indexed spender, uint tokens ); } contract Token is Ownable, ERC20Interface, Enums { using SafeMath for uint; // Token full name string private constant NAME = "EnvisionX EXCHAIN Token"; // Token symbol name string private constant SYMBOL = "EXT"; // Token max fraction, in decimal signs after the point uint8 private constant DECIMALS = 18; // Tokens max supply, in EXTwei uint public constant MAX_SUPPLY = 3000000000 * (10**uint(DECIMALS)); // Tokens balances map mapping(address => uint) internal balances; // Maps with allowed amounts fot TransferFrom mapping (address => mapping (address => uint)) internal allowed; // Total amount of issued tokens, in EXTwei uint internal _totalSupply; // Map with Ether founds amount by address (using when refunds) mapping(address => uint) internal etherFunds; uint internal _earnedFunds; // Map with refunded addreses (Black List) mapping(address => bool) internal refunded; // Address of sale agent (a contract) which can mint new tokens address public mintAgent; // Token transfer allowed only when token minting is finished bool public isMintingFinished = false; // When minting was finished uint public mintingStopDate; // Total amount of tokens minted to team basket, in EXTwei. // This will not include tokens, transferred to team basket // after minting is finished. uint public teamTotal; // Amount of tokens spent by team in first 96 weeks since // minting finish date. Used to calculate team spend // restrictions according to ICO White Paper. uint public spentByTeam; // Address of WPTokensBaskets contract WPTokensBaskets public wpTokensBaskets; // Constructor function Token(WPTokensBaskets baskets) public { wpTokensBaskets = baskets; mintAgent = owner; } // Fallback function - do not apply any ether to this contract. function () external payable { revert(); } // Last resort to return ether. // See the last warning at // http://solidity.readthedocs.io/en/develop/contracts.html#fallback-function // for such cases. function transferEtherTo(address a) external onlyOwner addrNotNull(a) { a.transfer(address(this).balance); } /** ---------------------------------------------------------------------- ERC20 Interface implementation */ // Return token full name function name() public pure returns (string) { return NAME; } // Return token symbol name function symbol() public pure returns (string) { return SYMBOL; } // Return amount of decimals after point function decimals() public pure returns (uint8) { return DECIMALS; } // Return total amount of issued tokens, in EXTwei function totalSupply() public constant returns (uint) { return _totalSupply; } // Return account balance in tokens (in EXTwei) function balanceOf(address _address) public constant returns (uint) { return balances[_address]; } // Transfer tokens to another account function transfer(address to, uint value) public addrNotNull(to) returns (bool) { if (balances[msg.sender] < value) return false; if (isFrozen(wpTokensBaskets.typeOf(msg.sender), value)) return false; balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); saveTeamSpent(msg.sender, value); emit Transfer(msg.sender, to, value); return true; } // Transfer tokens from one account to another, // using permissions defined with approve() method. function transferFrom(address from, address to, uint value) public addrNotNull(to) returns (bool) { if (balances[from] < value) return false; if (allowance(from, msg.sender) < value) return false; if (isFrozen(wpTokensBaskets.typeOf(from), value)) return false; balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); saveTeamSpent(from, value); emit Transfer(from, to, value); return true; } // Allow to transfer given amount of tokens (in EXTwei) // to account which is not owner. function approve(address spender, uint value) public returns (bool) { if (msg.sender == spender) return false; allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } // Return amount of tokens (in EXTwei) which allowed to // be transferred by non-owner spender function allowance(address _owner, address spender) public constant returns (uint) { return allowed[_owner][spender]; } /** ---------------------------------------------------------------------- Other methods */ // Return account funds in ether (in wei) function etherFundsOf(address _address) public constant returns (uint) { return etherFunds[_address]; } // Return total amount of funded ether, in wei function earnedFunds() public constant returns (uint) { return _earnedFunds; } // Return true if given address have been refunded function isRefunded(address _address) public view returns (bool) { return refunded[_address]; } // Set new address of sale agent contract. // Will be called for each sale stage: PrivateSale, PreSale, MainSale. function setMintAgent(address a) public onlyOwner addrNotNull(a) { emit MintAgentReplaced(mintAgent, a); mintAgent = a; } // Interface for sale agent contract - mint new tokens function mint(address to, uint256 extAmount, uint256 etherAmount) public { require(!isMintingFinished); require(msg.sender == mintAgent); require(!refunded[to]); _totalSupply = _totalSupply.add(extAmount); require(_totalSupply <= MAX_SUPPLY); balances[to] = balances[to].add(extAmount); if (wpTokensBaskets.isUnknown(to)) { _earnedFunds = _earnedFunds.add(etherAmount); etherFunds[to] = etherFunds[to].add(etherAmount); } else if (wpTokensBaskets.isTeam(to)) { teamTotal = teamTotal.add(extAmount); } emit Mint(to, extAmount); emit Transfer(msg.sender, to, extAmount); } // Destroy minted tokens and refund ether spent by investor. // Used in AML (Anti Money Laundering) workflow. // Will be called only by humans because there is no way // to withdraw crowdfunded ether from Beneficiary account // from context of this account. // Important note: all tokens minted to team, foundation etc. // will NOT be burned, because they in general are spent // during the sale and its too expensive to track all these // transactions. function burnTokensAndRefund(address _address) external payable addrNotNull(_address) onlyOwner() { require(msg.value > 0 && msg.value == etherFunds[_address]); _totalSupply = _totalSupply.sub(balances[_address]); balances[_address] = 0; _earnedFunds = _earnedFunds.sub(msg.value); etherFunds[_address] = 0; refunded[_address] = true; _address.transfer(msg.value); } // Stop tokens minting forever. function finishMinting() external onlyOwner { require(!isMintingFinished); isMintingFinished = true; mintingStopDate = now; emit MintingFinished(); } /** ---------------------------------------------------------------------- Tokens freeze logic, according to ICO White Paper */ // Return truth if given _value amount of tokens (in EXTwei) // cannot be transferred from account due to spend restrictions // defined in ICO White Paper. // !!!Caveat of current implementaion!!! // Say, // 1. There was 100 tokens minted to the team basket; // 2. Minting was finished and 24 weeks elapsed, and now // team can spend up to 25 tokens till next 24 weeks; // 3. Someone transfers another 100 tokens to the team basket; // 4. ... // Problem is, actually, you can't spend any of these extra 100 // tokens until 96 weeks will elapse since minting finish date. // That's because after next 24 weeks will be unlocked only // 25 tokens more (25% of *minted* tokens) and so on. // So, DO NOT send tokens to the team basket until 96 weeks elapse! function isFrozen( BasketType _basketType, uint _value ) public view returns (bool) { if (!isMintingFinished) { // Allow spend only after minting is finished return true; } if (_basketType == BasketType.foundation) { // Allow to spend foundation tokens only after // 48 weeks after minting is finished return now < mintingStopDate + 48 weeks; } if (_basketType == BasketType.team) { // Team allowed to spend tokens: // 25% - after minting finished date + 24 weeks; // 50% - after minting finished date + 48 weeks; // 75% - after minting finished date + 72 weeks; // 100% - after minting finished date + 96 weeks. if (mintingStopDate + 96 weeks <= now) { return false; } if (now < mintingStopDate + 24 weeks) return true; // Calculate fraction as percents multipled to 10^10. // Without this owner will be able to spend fractions // less than 1% per transaction. uint fractionSpent = spentByTeam.add(_value).mul(1000000000000).div(teamTotal); if (now < mintingStopDate + 48 weeks) { return 250000000000 < fractionSpent; } if (now < mintingStopDate + 72 weeks) { return 500000000000 < fractionSpent; } // from 72 to 96 weeks elapsed return 750000000000 < fractionSpent; } // No restrictions for other token holders return false; } // Save amount of spent tokens by team till 96 weeks after minting // finish date. This is vital because without the check we'll eventually // overflow the uint256. function saveTeamSpent(address _owner, uint _value) internal { if (wpTokensBaskets.isTeam(_owner)) { if (now < mintingStopDate + 96 weeks) spentByTeam = spentByTeam.add(_value); } } /** ---------------------------------------------------------------------- Events */ // Emitted when mint agent (address of a sale contract) // replaced with new one event MintAgentReplaced( address indexed previousMintAgent, address indexed newMintAgent ); // Emitted when new tokens were created and funded to account event Mint(address indexed to, uint256 amount); // Emitted when tokens minting is finished. event MintingFinished(); } contract Killable is Ownable { function kill(address a) external onlyOwner addrNotNull(a) { selfdestruct(a); } } contract Beneficiary is Killable { // Address of account which will receive all ether // gathered from ICO address public beneficiary; // Constructor function Beneficiary() public { beneficiary = owner; } // Fallback function - do not apply any ether to this contract. function () external payable { revert(); } // Set new beneficiary for ICO function setBeneficiary(address a) external onlyOwner addrNotNull(a) { beneficiary = a; } } contract TokenSale is Killable, Enums { using SafeMath for uint256; // Type describing: // - the address of the beneficiary of the tokens; // - the final amount of tokens calculated according to the // terms of the WP; // - the amount of Ether (in Wei) if the beneficiary is an investor // This type is used in arrays[8] that should be declare in the heir // contracts. struct tokens { address beneficiary; uint256 extAmount; uint256 ethAmount; } // Sale stage start date/time, Unix timestamp uint32 public start; // Sale stage stop date/time, Unix timestamp uint32 public stop; // Min ether amount for purchase uint256 public minBuyingAmount; // Price of one token, in wei uint256 public currentPrice; // Amount of tokens available, in EXTwei uint256 public remainingSupply; // Amount of earned funds, in wei uint256 public earnedFunds; // Address of Token contract Token public token; // Address of Beneficiary contract - a container // for the beneficiary address Beneficiary internal _beneficiary; // Equals to 10^decimals. // Internally tokens stored as EXTwei (token count * 10^decimals). // Used to convert EXT to EXTwei and vice versa. uint256 internal dec; // Constructor function TokenSale( Token _token, // address of EXT ERC20 token contract Beneficiary beneficiary, // address of container for Ether beneficiary uint256 _supplyAmount // in EXT ) public { token = _token; _beneficiary = beneficiary; // Factor for convertation EXT to EXTwei and vice versa dec = 10 ** uint256(token.decimals()); // convert to EXTwei remainingSupply = _supplyAmount.mul(dec); } // Fallback function. Here we'll receive all investments. function() external payable { purchase(); } // Investments receive logic. Must be overrided in // arbitrary sale agent (per each sale stage). function purchase() public payable; // Return truth if purchase with given _value of ether // (in wei) can be made function canPurchase(uint256 _value) public view returns (bool) { return start <= now && now <= stop && minBuyingAmount <= _value && toEXTwei(_value) <= remainingSupply; } // Return address of crowdfunding beneficiary address. function beneficiary() public view returns (address) { return _beneficiary.beneficiary(); } // Return truth if there are tokens which can be purchased. function isActive() public view returns (bool) { return canPurchase(minBuyingAmount); } // Initialize tokensArray records with actual addresses of WP tokens baskets function setBaskets(tokens[8] memory _tokensArray) internal view { _tokensArray[uint8(BasketType.unknown)].beneficiary = msg.sender; _tokensArray[uint8(BasketType.team)].beneficiary = token.wpTokensBaskets().team(); _tokensArray[uint8(BasketType.foundation)].beneficiary = token.wpTokensBaskets().foundation(); _tokensArray[uint8(BasketType.arr)].beneficiary = token.wpTokensBaskets().arr(); _tokensArray[uint8(BasketType.advisors)].beneficiary = token.wpTokensBaskets().advisors(); _tokensArray[uint8(BasketType.bounty)].beneficiary = token.wpTokensBaskets().bounty(); } // Return amount of tokens (in EXTwei) which can be purchased // at the moment for given amount of ether (in wei). function toEXTwei(uint256 _value) public view returns (uint256) { return _value.mul(dec).div(currentPrice); } // Return amount of bonus tokens (in EXTwei) // Receive amount of tokens (in EXTwei) that will be sale, and bonus percent function bonus(uint256 _tokens, uint8 _bonus) internal pure returns (uint256) { return _tokens.mul(_bonus).div(100); } // Initialize tokensArray records with actual amounts of tokens function calcWPTokens(tokens[8] memory a, uint8 _bonus) internal pure { a[uint8(BasketType.unknown)].extAmount = a[uint8(BasketType.unknown)].extAmount.add( bonus( a[uint8(BasketType.unknown)].extAmount, _bonus ) ); uint256 n = a[uint8(BasketType.unknown)].extAmount; a[uint8(BasketType.team)].extAmount = n.mul(24).div(40); a[uint8(BasketType.foundation)].extAmount = n.mul(20).div(40); a[uint8(BasketType.arr)].extAmount = n.mul(10).div(40); a[uint8(BasketType.advisors)].extAmount = n.mul(4).div(40); a[uint8(BasketType.bounty)].extAmount = n.mul(2).div(40); } // Send received ether (in wei) to beneficiary function transferFunds(uint256 _value) internal { beneficiary().transfer(_value); earnedFunds = earnedFunds.add(_value); } // Method for call mint() in EXT ERC20 contract. // mint() will be called for each record if amount of tokens > 0 function createTokens(tokens[8] memory _tokensArray) internal { for (uint i = 0; i < _tokensArray.length; i++) { if (_tokensArray[i].extAmount > 0) { token.mint( _tokensArray[i].beneficiary, _tokensArray[i].extAmount, _tokensArray[i].ethAmount ); } } } } contract PrivateSale is TokenSale { using SafeMath for uint256; // List of investors allowed to buy tokens at PrivateSale mapping(address => bool) internal allowedInvestors; function PrivateSale(Token _token, Beneficiary _beneficiary) TokenSale(_token, _beneficiary, uint256(400000000)) public { start = 1522627620; stop = 1525046399; minBuyingAmount = 70 szabo; currentPrice = 70 szabo; } function purchase() public payable { require(isInvestorAllowed(msg.sender)); require(canPurchase(msg.value)); transferFunds(msg.value); tokens[8] memory tokensArray; tokensArray[uint8(BasketType.unknown)].extAmount = toEXTwei(msg.value); setBaskets(tokensArray); remainingSupply = remainingSupply.sub( tokensArray[uint8(BasketType.unknown)].extAmount ); calcWPTokens(tokensArray, 30); tokensArray[uint8(BasketType.unknown)].ethAmount = msg.value; createTokens(tokensArray); } // Register new investor function allowInvestor(address a) public onlyOwner addrNotNull(a) { allowedInvestors[a] = true; } // Discard existing investor function denyInvestor(address a) public onlyOwner addrNotNull(a) { delete allowedInvestors[a]; } // Return truth if given account is allowed to buy tokens function isInvestorAllowed(address a) public view returns (bool) { return allowedInvestors[a]; } }
Save amount of spent tokens by team till 96 weeks after minting finish date. This is vital because without the check we'll eventually overflow the uint256.
function saveTeamSpent(address _owner, uint _value) internal { if (wpTokensBaskets.isTeam(_owner)) { if (now < mintingStopDate + 96 weeks) spentByTeam = spentByTeam.add(_value); } } Events address indexed previousMintAgent, address indexed newMintAgent );
13,433,396
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./DaoStaking.sol"; import "./RicVault.sol"; // The FeeDao is where the fees accumulate from the contracts in the catalog. // Token holders can Vote on IERC20 addresses to use for fees. // Token holders can exchange their tokens for reward from up to 3 IERC20 balances. // The exchanged tokens are added to the DaoStaking developer reward pool. struct TokenProposal { address creator; string name; IERC20 proposal; string discussionURL; uint256 approvals; uint256 rejections; uint256 created; bool closed; } struct Token { string name; // The name of the token IERC20 token; } uint256 constant requiredBalance = 10000e18; uint256 constant precision = 1000000000; //The precision of reward calculation, 9 decimals enum Balance { current, total } enum Periods { singleLock, trippleLock, pollPeriod } contract FeeDao { using SafeERC20 for IERC20; DaoStaking private staking; CatalogDao private catalogDao; RicVault private ricVault; IERC20 private ric; TokenProposal[] private proposals; mapping(bytes32 => bool) private voted; mapping(address => TokenProposal[]) private myProposals; mapping(address => bool) private hasPendingProposal; Token[] private tokens; // addressAdded is used like a .contains array method for the tokens . // will return true if the address has been added mapping(address => bool) private addressAdded; mapping(bytes32 => uint256) private balance; mapping(Periods => uint256) private periods; address private owner; bool private lock; event ProposeNewToken( address indexed _address, IERC20 _token, string _discussionURL ); event VoteOnToken(address indexed _address, bool _accepted, uint256 _index); event CloseProposal(address indexed _address, uint256 index); event WithdrawToken( address indexed _address, IERC20 withdraw, uint256 amount, uint256 reward ); event WithdrawThreeTokens( address indexed _address, IERC20 first, IERC20 second, IERC20 third, uint256 amount, uint256 firstReward, uint256 secondReward, uint256 thirdReward ); event Received(address to, uint256 value); event WithdrawEth(address to, uint256 reward, uint256 ricAmount); constructor( IERC20 ric_, DaoStaking _staking_, CatalogDao _catalogDao_, uint256 pollPeriod_ ) { ric = ric_; staking = _staking_; periods[Periods.pollPeriod] = pollPeriod_; periods[Periods.singleLock] = 1314900; //blocks are around 1 month with 2 second finality periods[Periods.trippleLock] = 3944700; // blocks are around 3 months with a 2 second finality owner = msg.sender; catalogDao = _catalogDao_; balance[hashBalance(Balance.current)] = 0; balance[hashBalance(Balance.total)] = 0; } function setRicVault(RicVault _ricVault_) external { require(msg.sender == owner, "937"); ricVault = _ricVault_; } function setPollPeriods( uint256 singleLock, uint256 trippleLock, uint256 pollPeriod ) external { require(msg.sender == owner, "937"); periods[Periods.singleLock] = singleLock; periods[Periods.trippleLock] = trippleLock; periods[Periods.pollPeriod] = pollPeriod; } function proposeNewToken( IERC20 _token, string memory _discussionURL, string memory _name_ ) external returns (uint256) { require(address(_token) != address(0), "948"); require(staking.isStaking(msg.sender), "919"); require(catalogDao.getRank(msg.sender) > 0, "911"); // The proposer must have the required balance require(ric.balanceOf(msg.sender) > requiredBalance, "932"); require(!hasPendingProposal[msg.sender], "944"); TokenProposal memory proposal = TokenProposal({ name: _name_, creator: msg.sender, proposal: _token, discussionURL: _discussionURL, approvals: 0, rejections: 0, created: block.number, closed: false }); hasPendingProposal[msg.sender] = true; proposals.push(proposal); bytes32 _hash_ = hashTokenProposal(proposal, msg.sender); voted[_hash_] = true; myProposals[msg.sender].push(proposal); emit ProposeNewToken(msg.sender, _token, _discussionURL); return proposals.length; } function hashTokenProposal(TokenProposal memory _proposal, address _voter) internal pure returns (bytes32) { return keccak256( abi.encodePacked( _proposal.creator, _proposal.proposal, _proposal.discussionURL, _proposal.created, _voter ) ); } // Accessing array by index here! function votedAlready(uint256 index, address _voter) public view returns (bool) { bytes32 _hash_ = hashTokenProposal(proposals[index], _voter); return voted[_hash_]; } function voteOnToken(uint256 index, bool accepted) external { require(staking.isStaking(msg.sender), "919"); require(catalogDao.getRank(msg.sender) > 0, "911"); // The voter must have the required balance require(ric.balanceOf(msg.sender) > requiredBalance, "932"); bytes32 _hash_ = hashTokenProposal(proposals[index], msg.sender); require(!voted[_hash_], "933"); // check if the voting period is over require( proposals[index].created + periods[Periods.pollPeriod] > block.number, "913" ); if (accepted) { proposals[index].approvals += 1; // The deployer of the contract can moderate proposals if (msg.sender == owner) { proposals[index].approvals += 4; } } else { proposals[index].rejections += 1; if (msg.sender == owner) { proposals[index].rejections += 4; } } voted[_hash_] = true; emit VoteOnToken(msg.sender, accepted, index); } function closeTokenProposal(uint256 index) external { require(catalogDao.getRank(msg.sender) > 0, "911"); // Everybody closes their own proposals require(proposals[index].creator == msg.sender, "914"); // The poll period must be over require( proposals[index].created + periods[Periods.pollPeriod] < block.number, "915" ); require(!proposals[index].closed, "917"); proposals[index].closed = true; hasPendingProposal[msg.sender] = false; // If there are more approvals than rejections if (proposals[index].approvals > proposals[index].rejections) { tokens.push( Token({ name: proposals[index].name, token: proposals[index].proposal }) ); addressAdded[address(proposals[index].proposal)] = true; } // else its closed, done. emit CloseProposal(msg.sender, index); } function tokenHashWithAddress(Token memory _tokens_) internal view returns (bytes32) { return keccak256( abi.encodePacked(_tokens_.name, _tokens_.token, msg.sender) ); } function getTokens() external view returns (Token[] memory) { return tokens; } function getProposals() external view returns (TokenProposal[] memory) { return proposals; } function getMyProposals() external view returns (TokenProposal[] memory) { return myProposals[msg.sender]; } function calculateWithdraw(IERC20 from, uint256 amount) public view returns (uint256 payment) { // How much is the amount compared to the total supply? uint256 withPadding = amount * precision; uint256 dividedByTotal = (withPadding / ric.totalSupply()); uint256 calculatedValue = dividedByTotal * from.balanceOf(address(this)); payment = calculatedValue / precision; } function calculateETHWithdraw(uint256 amount) public view returns (uint256 payment) { // How much is the amount compared to the total supply? uint256 withPadding = amount * precision; uint256 dividedByTotal = (withPadding / ric.totalSupply()); uint256 calculatedValue = dividedByTotal * balance[hashBalance(Balance.current)]; payment = calculatedValue / precision; } function withdrawETH(uint256 amount) external { require(!lock, "925"); lock = true; require(ric.balanceOf(msg.sender) >= amount, "934"); uint256 _reward = calculateETHWithdraw(amount); require(_reward < balance[hashBalance(Balance.current)], "927"); balance[hashBalance(Balance.current)] -= _reward; // Lock the ric in the vault ricVault.lockFor(msg.sender, periods[Periods.singleLock], amount); // reduce the balance and send it Address.sendValue(payable(msg.sender), _reward); lock = false; emit WithdrawEth(msg.sender, _reward, amount); } receive() external payable { emit Received(msg.sender, msg.value); balance[hashBalance(Balance.current)] += msg.value; balance[hashBalance(Balance.total)] += msg.value; } function getCurrentBalance() external view returns (uint256) { return balance[hashBalance(Balance.current)]; } function getTotalBalance() external view returns (uint256) { return balance[hashBalance(Balance.total)]; } function withdrawOne(IERC20 from, uint256 amount) external { require(!lock, "935"); lock = true; require(addressAdded[address(from)], "939"); require(ric.balanceOf(msg.sender) >= amount, "934"); uint256 _reward = calculateWithdraw(from, amount); require(_reward < from.balanceOf(address(this)), "927"); // Register a spend balance[hashBalance(address(from))] += _reward; // Lock the ric in the vault ricVault.lockFor(msg.sender, periods[Periods.trippleLock], amount); // transfer the requiested tokens from.safeTransfer(msg.sender, _reward); lock = false; emit WithdrawToken(msg.sender, from, amount, _reward); } function viewSpentBalanceOf(IERC20 _token_) external view returns (uint256) { return balance[hashBalance(address(_token_))]; } function hashBalance(Balance _balance_) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_balance_)); } // hashBalance with the address parameter is used for IERC20 address spent balance tracking // It was done like this because of the limit on variable declarations in the contract function hashBalance(address _balance_) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_balance_)); } }
How much is the amount compared to the total supply?
function calculateETHWithdraw(uint256 amount) public view returns (uint256 payment) { uint256 withPadding = amount * precision; uint256 dividedByTotal = (withPadding / ric.totalSupply()); uint256 calculatedValue = dividedByTotal * balance[hashBalance(Balance.current)]; payment = calculatedValue / precision; }
2,473,273
./partial_match/1/0x16B0a1a87ae8aF5C792faBC429C4FE248834842B/sources/AlgoryToken.sol
Interface marker /
function isUpgradeAgent() public constant returns (bool) { return true; }
4,229,648
/** *Submitted for verification at Etherscan.io on 2020-02-17 */ pragma solidity 0.5.16; // File: openzeppelin-solidity/contracts/ownership/Ownable.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. * * 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 /** * @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 /** * @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: contracts/LockedGoldOracle.sol // Simple contract regulating the total supply of gold locked at any // given time so that the Cache contract can't over mint tokens contract LockedGoldOracle is Ownable { using SafeMath for uint256; uint256 private _lockedGold; address private _cacheContract; event LockEvent(uint256 amount); event UnlockEvent(uint256 amount); function setCacheContract(address cacheContract) external onlyOwner { _cacheContract = cacheContract; } function lockAmount(uint256 amountGrams) external onlyOwner { _lockedGold = _lockedGold.add(amountGrams); emit LockEvent(amountGrams); } // Can only unlock amount of gold if it would leave the // total amount of locked gold greater than or equal to the // number of tokens in circulation function unlockAmount(uint256 amountGrams) external onlyOwner { _lockedGold = _lockedGold.sub(amountGrams); require(_lockedGold >= CacheGold(_cacheContract).totalCirculation()); emit UnlockEvent(amountGrams); } function lockedGold() external view returns(uint256) { return _lockedGold; } function cacheContract() external view returns(address) { return _cacheContract; } } // File: contracts/CacheGold.sol /// @title The CacheGold Token Contract /// @author Cache Pte Ltd contract CacheGold is IERC20, Ownable { using SafeMath for uint256; // ERC20 Detailed Info /* solhint-disable */ string public constant name = "CACHE Gold"; string public constant symbol = "CGT"; uint8 public constant decimals = 8; /* solhint-enable */ // 10^8 shortcut uint256 private constant TOKEN = 10 ** uint256(decimals); // Seconds in a day uint256 private constant DAY = 86400; // Days in a year uint256 private constant YEAR = 365; // The maximum transfer fee is 10 basis points uint256 private constant MAX_TRANSFER_FEE_BASIS_POINTS = 10; // Basis points means divide by 10,000 to get decimal uint256 private constant BASIS_POINTS_MULTIPLIER = 10000; // The storage fee of 0.25% uint256 private constant STORAGE_FEE_DENOMINATOR = 40000000000; // The inactive fee of 0.50% uint256 private constant INACTIVE_FEE_DENOMINATOR = 20000000000; // The minimum balance that would accrue a storage fee after 1 day uint256 private constant MIN_BALANCE_FOR_FEES = 146000; // Initial basis points for transfer fee uint256 private _transferFeeBasisPoints = 10; // Cap on total number of tokens that can ever be produced uint256 public constant SUPPLY_CAP = 8133525786 * TOKEN; // How many days need to pass before late fees can be collected (3 years) uint256 public constant INACTIVE_THRESHOLD_DAYS = 1095; // Token balance of each address mapping (address => uint256) private _balances; // Allowed transfer from address mapping (address => mapping (address => uint256)) private _allowances; // Last time storage fee was paid mapping (address => uint256) private _timeStorageFeePaid; // Last time the address produced a transaction on this contract mapping (address => uint256) private _timeLastActivity; // Amount of inactive fees already paid mapping (address => uint256) private _inactiveFeePaid; // If address doesn't have any activity for INACTIVE_THRESHOLD_DAYS // we can start deducting chunks off the address so that // full balance can be recouped after 200 years. This is likely // to happen if the user loses their private key. mapping (address => uint256) private _inactiveFeePerYear; // Addresses not subject to transfer fees mapping (address => bool) private _transferFeeExempt; // Address is not subject to storage fees mapping (address => bool) private _storageFeeExempt; // Save grace period on storage fees for an address mapping (address => uint256) private _storageFeeGracePeriod; // Current total number of tokens created uint256 private _totalSupply; // Address where storage and transfer fees are collected address private _feeAddress; // The address for the "backed treasury". When a bar is locked into the // vault for tokens to be minted, they are created in the backed_treasury // and can then be sold from this address. address private _backedTreasury; // The address for the "unbacked treasury". The unbacked treasury is a // storing address for excess tokens that are not locked in the vault // and therefore do not correspond to any real world value. If new bars are // locked in the vault, tokens will first be moved from the unbacked // treasury to the backed treasury before minting new tokens. // // This address only accepts transfers from the _backedTreasury or _redeemAddress // the general public should not be able to manipulate this balance. address private _unbackedTreasury; // The address for the LockedGoldOracle that determines the maximum number of // tokens that can be in circulation at any given time address private _oracle; // A fee-exempt address that can be used to collect gold tokens in exchange // for redemption of physical gold address private _redeemAddress; // An address that can force addresses with overdue storage or inactive fee to pay. // This is separate from the contract owner, because the owner will change // to a multisig address after deploy, and we want to be able to write // a script that can sign "force-pay" transactions with a single private key address private _feeEnforcer; // Grace period before storage fees kick in uint256 private _storageFeeGracePeriodDays = 0; // When gold bars are locked, we add tokens to circulation either // through moving them from the unbacked treasury or minting new ones, // or some combination of both event AddBackedGold(uint256 amount); // Before gold bars can be unlocked (removed from circulation), they must // be moved to the unbacked treasury, we emit an event when this happens // to signal a change in the circulating supply event RemoveGold(uint256 amount); // When an account has no activity for INACTIVE_THRESHOLD_DAYS // it will be flagged as inactive event AccountInactive(address indexed account, uint256 feePerYear); // If an previoulsy dormant account is reactivated event AccountReActive(address indexed account); /** * @dev Contructor for the CacheGold token sets internal addresses * @param unbackedTreasury The address of the unbacked treasury * @param backedTreasury The address of the backed treasury * @param feeAddress The address where fees are collected * @param redeemAddress The address where tokens are send to redeem physical gold * @param oracle The address of the LockedGoldOracle */ constructor(address unbackedTreasury, address backedTreasury, address feeAddress, address redeemAddress, address oracle) public { _unbackedTreasury = unbackedTreasury; _backedTreasury = backedTreasury; _feeAddress = feeAddress; _redeemAddress = redeemAddress; _feeEnforcer = owner(); _oracle = oracle; setFeeExempt(_feeAddress); setFeeExempt(_redeemAddress); setFeeExempt(_backedTreasury); setFeeExempt(_unbackedTreasury); setFeeExempt(owner()); } /** * @dev Throws if called by any account other than THE ENFORCER */ modifier onlyEnforcer() { require(msg.sender == _feeEnforcer); _; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) external returns (bool) { // Update activity for the sender _updateActivity(msg.sender); // Can opportunistically mark an account inactive if someone // sends money to it if (_shouldMarkInactive(to)) { _setInactive(to); } _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool) { _updateActivity(msg.sender); _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * Also note that even though balance requirements are not explicitly checked, * any transfer attempt over the approved amount will automatically fail due to * SafeMath revert when trying to subtract approval to a negative balance * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) external returns (bool) { _updateActivity(msg.sender); _transfer(from, to, value); _approve(from, msg.sender, _allowances[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _updateActivity(msg.sender); _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { _updateActivity(msg.sender); _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Function to add a certain amount of backed tokens. This will first * take any tokens from the _unbackedTreasury address and move them to the * _backedTreasury. Any remaining tokens will actually be minted. * This operation will fail if there is not a sufficient supply of locked gold * as determined by the LockedGoldOracle * * @param value The amount of tokens to add to the backed treasury * @return A boolean that indicates if the operation was successful. */ function addBackedTokens(uint256 value) external onlyOwner returns (bool) { uint256 unbackedBalance = _balances[_unbackedTreasury]; // Use oracle to check if there is actually enough gold // in custody to validate this operation uint256 lockedGrams = LockedGoldOracle(_oracle).lockedGold(); // Should reject mint if it would make the total supply // exceed the amount actually locked in vault require(lockedGrams >= totalCirculation().add(value), "Insufficent grams locked in LockedGoldOracle to complete operation"); // If we have sufficient balance, just move from the unbacked to backed // treasury address if (block.number <= unbackedBalance) { //injected CONTRACT AFFECTED BY MINERS _transfer(_unbackedTreasury, _backedTreasury, value); } else { if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS // There is no sufficient balance, so we have to both transfer and mint new tokens // Transfer the remaining unbacked treasury balance to backed treasury _transfer(_unbackedTreasury, _backedTreasury, unbackedBalance); } // And mint the remaining to the backed treasury _mint(value.sub(unbackedBalance)); } emit AddBackedGold(value); return true; } /** * @dev Manually pay storage fees on senders address. Exchanges may want to * periodically call this function to pay owed storage fees. This is a * cheaper option than 'send to self', which would also trigger paying * storage fees * * @return A boolean that indicates if the operation was successful. */ function payStorageFee() external returns (bool) { _updateActivity(msg.sender); _payStorageFee(msg.sender); return true; } function setAccountInactive(address account) external onlyEnforcer returns (bool) { require(_shouldMarkInactive(account), "Account not eligible to be marked inactive"); _setInactive(account); } /** * @dev Contract allows the forcible collection of storage fees on an address * if it is has been more than than 365 days since the last time storage fees * were paid on this address. * * Alternatively inactive fees may also be collected periodically on a prorated * basis if the account is currently marked as inactive. * * @param account The address to pay storage fees on * @return A boolean that indicates if the operation was successful. */ function forcePayFees(address account) external onlyEnforcer returns(bool) { require(account != address(0)); require(_balances[account] > 0, "Account has no balance, cannot force paying fees"); // If account is inactive, pay inactive fees if (isInactive(account)) { uint256 paid = _payInactiveFee(account); require(paid > 0); } else if (_shouldMarkInactive(account)) { // If it meets inactive threshold, but hasn't been set yet, set it. // This will also trigger automatic payment of owed storage fees // before starting inactive fees _setInactive(account); } else { // Otherwise just force paying owed storage fees, which can only // be called if they are more than 365 days overdue require(daysSincePaidStorageFee(account) >= YEAR, "Account has paid storage fees more recently than 365 days"); uint256 paid = _payStorageFee(account); require(paid > 0, "No appreciable storage fees due, will refund gas"); } } /** * @dev Set the address that can force collecting fees from users * @param enforcer The address to force collecting fees * @return An bool representing successfully changing enforcer address */ function setFeeEnforcer(address enforcer) external onlyOwner returns(bool) { require(enforcer != address(0)); _feeEnforcer = enforcer; setFeeExempt(_feeEnforcer); return true; } /** * @dev Set the address to collect fees * @param newFeeAddress The address to collect storage and transfer fees * @return An bool representing successfully changing fee address */ function setFeeAddress(address newFeeAddress) external onlyOwner returns(bool) { require(newFeeAddress != address(0)); require(newFeeAddress != _unbackedTreasury, "Cannot set fee address to unbacked treasury"); _feeAddress = newFeeAddress; setFeeExempt(_feeAddress); return true; } /** * @dev Set the address to deposit tokens when redeeming for physical locked bars. * @param newRedeemAddress The address to redeem tokens for bars * @return An bool representing successfully changing redeem address */ function setRedeemAddress(address newRedeemAddress) external onlyOwner returns(bool) { require(newRedeemAddress != address(0)); require(newRedeemAddress != _unbackedTreasury, "Cannot set redeem address to unbacked treasury"); _redeemAddress = newRedeemAddress; setFeeExempt(_redeemAddress); return true; } /** * @dev Set the address of backed treasury * @param newBackedAddress The address of backed treasury * @return An bool representing successfully changing backed address */ function setBackedAddress(address newBackedAddress) external onlyOwner returns(bool) { require(newBackedAddress != address(0)); require(newBackedAddress != _unbackedTreasury, "Cannot set backed address to unbacked treasury"); _backedTreasury = newBackedAddress; setFeeExempt(_backedTreasury); return true; } /** * @dev Set the address to unbacked treasury * @param newUnbackedAddress The address of unbacked treasury * @return An bool representing successfully changing unbacked address */ function setUnbackedAddress(address newUnbackedAddress) external onlyOwner returns(bool) { require(newUnbackedAddress != address(0)); require(newUnbackedAddress != _backedTreasury, "Cannot set unbacked treasury to backed treasury"); require(newUnbackedAddress != _feeAddress, "Cannot set unbacked treasury to fee address "); require(newUnbackedAddress != _redeemAddress, "Cannot set unbacked treasury to fee address "); _unbackedTreasury = newUnbackedAddress; setFeeExempt(_unbackedTreasury); return true; } /** * @dev Set the LockedGoldOracle address * @param oracleAddress The address for oracle * @return An bool representing successfully changing oracle address */ function setOracleAddress(address oracleAddress) external onlyOwner returns(bool) { require(oracleAddress != address(0)); _oracle = oracleAddress; return true; } /** * @dev Set the number of days before storage fees begin accruing. * @param daysGracePeriod The global setting for the grace period before storage * fees begin accruing. Note that calling this will not change the grace period * for addresses already actively inside a grace period */ function setStorageFeeGracePeriodDays(uint256 daysGracePeriod) external onlyOwner { _storageFeeGracePeriodDays = daysGracePeriod; } /** * @dev Set this account as being exempt from transfer fees. This may be used * in special circumstance for cold storage addresses owed by Cache, exchanges, etc. * @param account The account to exempt from transfer fees */ function setTransferFeeExempt(address account) external onlyOwner { _transferFeeExempt[account] = true; } /** * @dev Set this account as being exempt from storage fees. This may be used * in special circumstance for cold storage addresses owed by Cache, exchanges, etc. * @param account The account to exempt from storage fees */ function setStorageFeeExempt(address account) external onlyOwner { _storageFeeExempt[account] = true; } /** * @dev Set account is no longer exempt from all fees * @param account The account to reactivate fees */ function unsetFeeExempt(address account) external onlyOwner { _transferFeeExempt[account] = false; _storageFeeExempt[account] = false; } /** * @dev Set a new transfer fee in basis points, must be less than or equal to 10 basis points * @param fee The new transfer fee in basis points */ function setTransferFeeBasisPoints(uint256 fee) external onlyOwner { require(fee <= MAX_TRANSFER_FEE_BASIS_POINTS, "Transfer fee basis points must be an integer between 0 and 10"); _transferFeeBasisPoints = fee; } /** * @dev Gets the balance of the specified address deducting owed fees and * accounting for the maximum amount that could be sent including transfer fee * @param owner The address to query the balance of. * @return An uint256 representing the amount sendable by the passed address * including transaction and storage fees */ function balanceOf(address owner) external view returns (uint256) { return calcSendAllBalance(owner); } /** * @dev Gets the balance of the specified address not deducting owed fees. * this returns the 'traditional' ERC-20 balance that represents the balance * currently stored in contract storage. * @param owner The address to query the balance of. * @return An uint256 representing the amount stored in passed address */ function balanceOfNoFees(address owner) external view returns (uint256) { return _balances[owner]; } /** * @dev Total number of tokens in existence. This includes tokens * in the unbacked treasury that are essentially unusable and not * in circulation * @return A uint256 representing the total number of minted tokens */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @return address that can force paying overdue inactive fees */ function feeEnforcer() external view returns(address) { return _feeEnforcer; } /** * @return address where fees are collected */ function feeAddress() external view returns(address) { return _feeAddress; } /** * @return address for redeeming tokens for gold bars */ function redeemAddress() external view returns(address) { return _redeemAddress; } /** * @return address for backed treasury */ function backedTreasury() external view returns(address) { return _backedTreasury; } /** * @return address for unbacked treasury */ function unbackedTreasury() external view returns(address) { return _unbackedTreasury; } /** * @return address for oracle contract */ function oracleAddress() external view returns(address) { return _oracle; } /** * @return the current number of days and address is exempt * from storage fees upon receiving tokens */ function storageFeeGracePeriodDays() external view returns(uint256) { return _storageFeeGracePeriodDays; } /** * @return the current transfer fee in basis points [0-10] */ function transferFeeBasisPoints() external view returns(uint256) { return _transferFeeBasisPoints; } /** * @dev Simulate the transfer from one address to another see final balances and associated fees * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. * @return See _simulateTransfer function */ function simulateTransfer(address from, address to, uint256 value) external view returns (uint256[5] memory) { return _simulateTransfer(from, to, value); } /** * @dev Set this account as being exempt from all fees. This may be used * in special circumstance for cold storage addresses owed by Cache, exchanges, etc. * @param account The account to exempt from storage and transfer fees */ function setFeeExempt(address account) public onlyOwner { _transferFeeExempt[account] = true; _storageFeeExempt[account] = true; } /** * @dev Check if the address given is extempt from storage fees * @param account The address to check * @return A boolean if the address passed is exempt from storage fees */ function isStorageFeeExempt(address account) public view returns(bool) { return _storageFeeExempt[account]; } /** * @dev Check if the address given is extempt from transfer fees * @param account The address to check * @return A boolean if the address passed is exempt from transfer fees */ function isTransferFeeExempt(address account) public view returns(bool) { return _transferFeeExempt[account]; } /** * @dev Check if the address given is extempt from transfer fees * @param account The address to check * @return A boolean if the address passed is exempt from transfer fees */ function isAllFeeExempt(address account) public view returns(bool) { return _transferFeeExempt[account] && _storageFeeExempt[account]; } /** * @dev Check if the address is considered inactive for not having transacted with * the contract for INACTIVE_THRESHOLD_DAYS * @param account The address to check * @return A boolean if the address passed is considered inactive */ function isInactive(address account) public view returns(bool) { return _inactiveFeePerYear[account] > 0; } /** * @dev Total number of tokens that are actually in circulation, which is * total tokens excluding the unbacked treasury * @return A uint256 representing the total number of tokens in circulation */ function totalCirculation() public view returns (uint256) { return _totalSupply.sub(_balances[_unbackedTreasury]); } /** * @dev Get the number of days since the account last paid storage fees * @param account The address to check * @return A uint256 representing the number of days since storage fees where last paid */ function daysSincePaidStorageFee(address account) public view returns(uint256) { if (isInactive(account) || _timeStorageFeePaid[account] == 0) { return 0; } return block.timestamp.sub(_timeStorageFeePaid[account]).div(DAY); } /** * @dev Get the days since the account last sent a transaction to the contract (activity) * @param account The address to check * @return A uint256 representing the number of days since the address last had activity * with the contract */ function daysSinceActivity(address account) public view returns(uint256) { if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS return 0; } return block.timestamp.sub(_timeLastActivity[account]).div(DAY); } /** * @dev Returns the total number of fees owed on a particular address * @param account The address to check * @return The total storage and inactive fees owed on the address */ function calcOwedFees(address account) public view returns(uint256) { return calcStorageFee(account).add(calcInactiveFee(account)); } /** * @dev Calculate the current storage fee owed for a given address * @param account The address to check * @return A uint256 representing current storage fees for the address */ function calcStorageFee(address account) public view returns(uint256) { // If an account is in an inactive state those fees take over and // storage fees are effectively paused uint256 balance = _balances[account]; if (isInactive(account) || isStorageFeeExempt(account) || balance == 0) { return 0; } uint256 daysSinceStoragePaid = daysSincePaidStorageFee(account); uint256 daysInactive = daysSinceActivity(account); uint256 gracePeriod = _storageFeeGracePeriod[account]; // If there is a grace period, we can deduct it from the daysSinceStoragePaid if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS if (block.timestamp > gracePeriod) { //injected CONTRACT AFFECTED BY MINERS daysSinceStoragePaid = daysSinceStoragePaid.sub(gracePeriod); } else { daysSinceStoragePaid = 0; } } if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS return 0; } // This is an edge case where the account has not yet been marked inactive, but // will be marked inactive whenever there is a transaction allowing it to be marked. // Therefore we know storage fees will only be valid up to a point, and inactive // fees will take over. if (block.number >= INACTIVE_THRESHOLD_DAYS) { //injected CONTRACT AFFECTED BY MINERS // This should not be at risk of being negative, because its impossible to force paying // storage fees without also setting the account to inactive, so if we are here it means // the last time storage fees were paid was BEFORE the account became eligible to be inactive // and it's always the case that daysSinceStoragePaid > daysInactive.sub(INACTIVE_THRESHOLD_DAYS) daysSinceStoragePaid = daysSinceStoragePaid.sub(daysInactive.sub(INACTIVE_THRESHOLD_DAYS)); } // The normal case with normal storage fees return storageFee(balance, daysSinceStoragePaid); } /** * @dev Calculate the current inactive fee for a given address * @param account The address to check * @return A uint256 representing current inactive fees for the address */ function calcInactiveFee(address account) public view returns(uint256) { uint256 balance = _balances[account]; uint256 daysInactive = daysSinceActivity(account); // if the account is marked inactive already, can use the snapshot balance if (isInactive(account)) { return _calcInactiveFee(balance, daysInactive, _inactiveFeePerYear[account], _inactiveFeePaid[account]); } else if (_shouldMarkInactive(account)) { // Account has not yet been marked inactive in contract, but the inactive fees will still be due. // Just assume snapshotBalance will be current balance after fees uint256 snapshotBalance = balance.sub(calcStorageFee(account)); return _calcInactiveFee(snapshotBalance, // current balance daysInactive, // number of days inactive _calcInactiveFeePerYear(snapshotBalance), // the inactive fee per year based on balance 0); // fees paid already } return 0; } /** * @dev Calculate the amount that would clear the balance from the address * accounting for owed storage and transfer fees * accounting for storage and transfer fees * @param account The address to check * @return A uint256 representing total amount an address has available to send */ function calcSendAllBalance(address account) public view returns (uint256) { require(account != address(0)); // Internal addresses pay no fees, so they can send their entire balance uint256 balanceAfterStorage = _balances[account].sub(calcOwedFees(account)); if (_transferFeeBasisPoints == 0 || isTransferFeeExempt(account)) { return balanceAfterStorage; } // Edge cases where remaining balance is 0.00000001, but is effectively 0 if (block.number <= 1) { //injected CONTRACT AFFECTED BY MINERS return 0; } // Calculate the send all amount including storage fee // Send All = Balance / 1.001 // and round up 0.00000001 uint256 divisor = TOKEN.add(_transferFeeBasisPoints.mul(BASIS_POINTS_MULTIPLIER)); uint256 sendAllAmount = balanceAfterStorage.mul(TOKEN).div(divisor).add(1); // Calc transfer fee on send all amount uint256 transFee = sendAllAmount.mul(_transferFeeBasisPoints).div(BASIS_POINTS_MULTIPLIER); // Fix to include rounding errors if (block.gaslimit > balanceAfterStorage) { //injected CONTRACT AFFECTED BY MINERS return sendAllAmount.sub(1); } return sendAllAmount; } /* * @dev Calculate the transfer fee on an amount * @param value The value being sent * @return A uint256 representing the transfer fee on sending the value given */ function calcTransferFee(address account, uint256 value) public view returns(uint256) { if (isTransferFeeExempt(account)) { return 0; } // Basis points -> decimal multiplier: // f(x) = x / 10,0000 (10 basis points is 0.001) // So transfer fee working with integers = // f(balance, basis) = (balance * TOKEN) / (10,000 * TOKEN / basis) return value.mul(_transferFeeBasisPoints).div(BASIS_POINTS_MULTIPLIER); } /* * @dev Calculate the storage fee for a given balance after a certain number of * days have passed since the last time fees were paid. * @param balance The current balance of the address * @param daysSinceStoragePaid The number days that have passed since fees where last paid * @return A uint256 representing the storage fee owed */ function storageFee(uint256 balance, uint256 daysSinceStoragePaid) public pure returns(uint256) { uint256 fee = balance.mul(TOKEN).mul(daysSinceStoragePaid).div(YEAR).div(STORAGE_FEE_DENOMINATOR); if (fee > balance) { return balance; } return fee; } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Transfer token for a specified addresses. Transfer is modified from a * standard ERC20 contract in that it must also process transfer and storage fees * for the token itself. Additionally there are certain internal addresses that * are not subject to fees. * @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 { _transferRestrictions(to, from); // If the account was previously inactive and initiated the transfer, the // inactive fees and storage fees have already been paid by the time we get here // via the _updateActivity() call uint256 storageFeeFrom = calcStorageFee(from); uint256 storageFeeTo = 0; uint256 allFeeFrom = storageFeeFrom; uint256 balanceFromBefore = _balances[from]; uint256 balanceToBefore = _balances[to]; // If not sending to self can pay storage and transfer fee if (block.coinbase != to) { //injected CONTRACT AFFECTED BY MINERS // Need transfer fee and storage fee for receiver if not sending to self allFeeFrom = allFeeFrom.add(calcTransferFee(from, value)); storageFeeTo = calcStorageFee(to); _balances[from] = balanceFromBefore.sub(value).sub(allFeeFrom); _balances[to] = balanceToBefore.add(value).sub(storageFeeTo); _balances[_feeAddress] = _balances[_feeAddress].add(allFeeFrom).add(storageFeeTo); } else { // Only storage fee if sending to self _balances[from] = balanceFromBefore.sub(storageFeeFrom); _balances[_feeAddress] = _balances[_feeAddress].add(storageFeeFrom); } // Regular Transfer emit Transfer(from, to, value); // Fee transfer on `from` address if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS emit Transfer(from, _feeAddress, allFeeFrom); if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS _timeStorageFeePaid[from] = block.timestamp; _endGracePeriod(from); } } // If first time receiving coins, set the grace period // and start the the activity clock and storage fee clock if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS // We may change the grace period in the future so we want to // preserve it per address so there is no retroactive deduction _storageFeeGracePeriod[to] = _storageFeeGracePeriodDays; _timeLastActivity[to] = block.timestamp; _timeStorageFeePaid[to] = block.timestamp; } // Fee transfer on `to` address if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS emit Transfer(to, _feeAddress, storageFeeTo); _timeStorageFeePaid[to] = block.timestamp; _endGracePeriod(to); } else if (block.gaslimit < MIN_BALANCE_FOR_FEES) { //injected CONTRACT AFFECTED BY MINERS // MIN_BALANCE_FOR_FEES is the minimum amount in which a storage fee // would be due after a sigle day, so if the balance is above that, // the storage fee would always be greater than 0. // // This avoids the following condition: // 1. User receives tokens // 2. Users sends all but a tiny amount to another address // 3. A year later, the user receives more tokens. Because // their previous balance was super small, there were no appreciable // storage fee, therefore the storage fee clock was not reset // 4. User now owes storage fees on entire balance, as if they // held tokens for 1 year, instead of resetting the clock to now. _timeStorageFeePaid[to] = block.timestamp; } // If transferring to unbacked treasury, tokens are being taken from // circulation, because gold is being 'unlocked' from the vault if (block.coinbase == _unbackedTreasury) { //injected CONTRACT AFFECTED BY MINERS emit RemoveGold(value); } } /** * @dev Function to mint tokens to backed treasury. In general this method * will not be called on it's own, but instead will be called from * addBackedTokens. * @param value The amount of tokens to mint to backed treasury * @return A boolean that indicates if the operation was successful. */ function _mint(uint256 value) internal returns(bool) { // Can't break supply cap require(_totalSupply.add(value) <= SUPPLY_CAP, "Call would exceed supply cap"); // Can only mint if the unbacked treasury balance is 0 require(_balances[_unbackedTreasury] == 0, "The unbacked treasury balance is not 0"); // Can only mint to the backed treasury _totalSupply = _totalSupply.add(value); _balances[_backedTreasury] = _balances[_backedTreasury].add(value); emit Transfer(address(0), _backedTreasury, value); return true; } /** * @dev Apply storage fee deduction * @param account The account to pay storage fees * @return A uint256 representing the storage fee paid */ function _payStorageFee(address account) internal returns(uint256) { uint256 storeFee = calcStorageFee(account); if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS return 0; } // Reduce account balance and add to fee address _balances[account] = _balances[account].sub(storeFee); _balances[_feeAddress] = _balances[_feeAddress].add(storeFee); emit Transfer(account, _feeAddress, storeFee); _timeStorageFeePaid[account] = block.timestamp; _endGracePeriod(account); return storeFee; } /** * @dev Apply inactive fee deduction * @param account The account to pay inactive fees * @return A uint256 representing the inactive fee paid */ function _payInactiveFee(address account) internal returns(uint256) { uint256 fee = _calcInactiveFee( _balances[account], daysSinceActivity(account), _inactiveFeePerYear[account], _inactiveFeePaid[account]); if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS return 0; } _balances[account] = _balances[account].sub(fee); _balances[_feeAddress] = _balances[_feeAddress].add(fee); _inactiveFeePaid[account] = _inactiveFeePaid[account].add(fee); emit Transfer(account, _feeAddress, fee); return fee; } function _shouldMarkInactive(address account) internal view returns(bool) { // Can only mark an account as inactive if // // 1. it's not fee exempt // 2. it has a balance // 3. it's been over INACTIVE_THRESHOLD_DAYS since last activity // 4. it's not already marked inactive // 5. the storage fees owed already consume entire balance if (account != address(0) && _balances[account] > 0 && daysSinceActivity(account) >= INACTIVE_THRESHOLD_DAYS && !isInactive(account) && !isAllFeeExempt(account) && _balances[account].sub(calcStorageFee(account)) > 0) { return true; } return false; } /** * @dev Mark an account as inactive. The function will automatically deduct * owed storage fees and inactive fees in one go. * * @param account The account to mark inactive */ function _setInactive(address account) internal { // First get owed storage fees uint256 storeFee = calcStorageFee(account); uint256 snapshotBalance = _balances[account].sub(storeFee); // all _setInactive calls are wrapped in _shouldMarkInactive, which // already checks this, so we shouldn't hit this condition assert(snapshotBalance > 0); // Set the account inactive on deducted balance _inactiveFeePerYear[account] = _calcInactiveFeePerYear(snapshotBalance); emit AccountInactive(account, _inactiveFeePerYear[account]); uint256 inactiveFees = _calcInactiveFee(snapshotBalance, daysSinceActivity(account), _inactiveFeePerYear[account], 0); // Deduct owed storage and inactive fees uint256 fees = storeFee.add(inactiveFees); _balances[account] = _balances[account].sub(fees); _balances[_feeAddress] = _balances[_feeAddress].add(fees); _inactiveFeePaid[account] = _inactiveFeePaid[account].add(inactiveFees); emit Transfer(account, _feeAddress, fees); // Reset storage fee clock if storage fees paid if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS _timeStorageFeePaid[account] = block.timestamp; _endGracePeriod(account); } } /** * @dev Update the activity clock on an account thats originated a transaction. * If the account has previously been marked inactive or should have been * marked inactive, it will opportunistically collect those owed fees. * * @param account The account to update activity */ function _updateActivity(address account) internal { // Cache has the ability to force collecting storage and inactivity fees, // but in the event an address was missed, can we still detect if the // account was inactive when they next transact // // Here we simply set the account as being inactive, collect the previous // storage and inactive fees that were owed, and then reactivate the account if (_shouldMarkInactive(account)) { // Call will pay existing storage fees before marking inactive _setInactive(account); } // Pay remaining fees and reset fee clocks if (isInactive(account)) { _payInactiveFee(account); _inactiveFeePerYear[account] = 0; _timeStorageFeePaid[account] = block.timestamp; emit AccountReActive(account); } // The normal case will just hit this and update // the activity clock for the account _timeLastActivity[account] = block.timestamp; } /** * @dev Turn off storage fee grace period for an address the first * time storage fees are paid (after grace period has ended) * @param account The account to turn off storage fee grace period */ function _endGracePeriod(address account) internal { if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS _storageFeeGracePeriod[account] = 0; } } /** * @dev Enforce the rules of which addresses can transfer to others * @param to The sending address * @param from The receiving address */ function _transferRestrictions(address to, address from) internal view { require(from != address(0)); require(to != address(0)); require(to != address(this), "Cannot transfer tokens to the contract"); // unbacked treasury can only transfer to backed treasury if (block.coinbase == _unbackedTreasury) { //injected CONTRACT AFFECTED BY MINERS require(to == _backedTreasury, "Unbacked treasury can only transfer to backed treasury"); } // redeem address can only transfer to unbacked or backed treasury if (block.coinbase == _redeemAddress) { //injected CONTRACT AFFECTED BY MINERS require((to == _unbackedTreasury) || (to == _backedTreasury), "Redeem address can only transfer to treasury"); } // Only the backed treasury and redeem address // can transfer to unbacked treasury if (block.coinbase == _unbackedTreasury) { //injected CONTRACT AFFECTED BY MINERS require((from == _backedTreasury) || (from == _redeemAddress), "Unbacked treasury can only receive from redeem address and backed treasury"); } // Only the unbacked treasury can transfer to the backed treasury if (block.coinbase == _backedTreasury) { //injected CONTRACT AFFECTED BY MINERS require((from == _unbackedTreasury) || (from == _redeemAddress), "Only unbacked treasury and redeem address can transfer to backed treasury"); } } /** * @dev Simulate the transfer from one address to another see final balances and associated fees * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @return a uint256 array of 5 values representing the * [0] storage fees `from` * [1] storage fees `to` * [2] transfer fee `from` * [3] final `from` balance * [4] final `to` balance */ function _simulateTransfer(address from, address to, uint256 value) internal view returns (uint256[5] memory) { uint256[5] memory ret; // Return value slots // 0 - fees `from` // 1 - fees `to` // 2 - transfer fee `from` // 3 - final `from` balance // 4 - final `to` balance ret[0] = calcOwedFees(from); ret[1] = 0; ret[2] = 0; // Don't double charge storage fee sending to self if (block.coinbase != to) { //injected CONTRACT AFFECTED BY MINERS ret[1] = calcOwedFees(to); ret[2] = calcTransferFee(from, value); ret[3] = _balances[from].sub(value).sub(ret[0]).sub(ret[2]); ret[4] = _balances[to].add(value).sub(ret[1]); } else { ret[3] = _balances[from].sub(ret[0]); ret[4] = ret[3]; } return ret; } /** * @dev Calculate the amount of inactive fees due per year on the snapshot balance. * Should return 50 basis points or 1 token minimum. * * @param snapshotBalance The balance of the account when marked inactive * @return uint256 the inactive fees due each year */ function _calcInactiveFeePerYear(uint256 snapshotBalance) internal pure returns(uint256) { uint256 inactiveFeePerYear = snapshotBalance.mul(TOKEN).div(INACTIVE_FEE_DENOMINATOR); if (inactiveFeePerYear < TOKEN) { return TOKEN; } return inactiveFeePerYear; } /** * @dev Calcuate inactive fees due on an account * @param balance The current account balance * @param daysInactive The number of days the account has been inactive * @param feePerYear The inactive fee per year based on snapshot balance * @param paidAlready The amount of inactive fees that have been paid already * @return uint256 for inactive fees due */ function _calcInactiveFee(uint256 balance, uint256 daysInactive, uint256 feePerYear, uint256 paidAlready) internal pure returns(uint256) { uint256 daysDue = daysInactive.sub(INACTIVE_THRESHOLD_DAYS); uint256 totalDue = feePerYear.mul(TOKEN).mul(daysDue).div(YEAR).div(TOKEN).sub(paidAlready); // The fee per year can be off by 0.00000001 so we can collect // the final dust after 200 years if (totalDue > balance || balance.sub(totalDue) <= 200) { return balance; } return totalDue; } }
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: spender The address which will spend the funds. value The amount of tokens to be spent./
function approve(address spender, uint256 value) external returns (bool) { _updateActivity(msg.sender); _approve(msg.sender, spender, value); return true; }
12,987,786
./partial_match/1/0x7733EB6D6F57B53055d748072B94526C3Bd1f6bb/sources/ResidentGenesis.sol
transferの前処理./ 新規保有者が増えた時はカウントアップ 既存の保有者の保有数が `0` になる時はカウントダウン
function _beforeTokenTransfers( address from, address to, uint256 /* startTokenId */, uint256 /* quantity */ ) internal virtual override { if (to != address(0) && balanceOf(to) == 0) { unchecked { _totalOwner++; } } if (from != address(0) && balanceOf(from) == 1 && _totalOwner > 0) { unchecked { _totalOwner--; } } }
2,777,595
./full_match/97/0xB840ABBfc54Dc3018Cf4A3db56D977f5521C949d/sources/project_/contracts/CandaoFriend.sol
Unfriending oneself is explicitly allowed. Unfriending more than once is explicitly allowed./
function unfriend(address _address) external { emit Events.Unfollow(_address); }
3,277,964
pragma solidity ^0.4.24; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } /** * @title UpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param _implementation Address of the initial implementation. */ constructor(address _implementation) public { assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation")); _setImplementation(_implementation); } /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". This adds two-phase * ownership control to OpenZeppelin's Ownable class. In this model, the original owner * designates a new owner but does not actually transfer ownership. The new owner then accepts * ownership and completes the transfer. */ contract Ownable { address public owner; address public pendingOwner; 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; pendingOwner = address(0); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @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)); pendingOwner = _newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * * @dev Stores permissions and validators and provides setter and getter methods. * Permissions determine which methods users have access to call. Validators * are able to mutate permissions at the Regulator level. * */ contract RegulatorStorage is Ownable { /** Structs */ /* Contains metadata about a permission to execute a particular method signature. */ struct Permission { string name; // A one-word description for the permission. e.g. "canMint" string description; // A longer description for the permission. e.g. "Allows user to mint tokens." string contract_name; // e.g. "PermissionedToken" bool active; // Permissions can be turned on or off by regulator } /** Constants: stores method signatures. These are potential permissions that a user can have, and each permission gives the user the ability to call the associated PermissionedToken method signature */ bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)")); bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)")); bytes4 public constant CONVERT_WT_SIG = bytes4(keccak256("convertWT(uint256)")); bytes4 public constant BURN_SIG = bytes4(keccak256("burn(uint256)")); bytes4 public constant CONVERT_CARBON_DOLLAR_SIG = bytes4(keccak256("convertCarbonDollar(address,uint256)")); bytes4 public constant BURN_CARBON_DOLLAR_SIG = bytes4(keccak256("burnCarbonDollar(address,uint256)")); bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)")); bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)")); bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()")); /** Mappings */ /* each method signature maps to a Permission */ mapping (bytes4 => Permission) public permissions; /* list of validators, either active or inactive */ mapping (address => bool) public validators; /* each user can be given access to a given method signature */ mapping (address => mapping (bytes4 => bool)) public userPermissions; /** Events */ event PermissionAdded(bytes4 methodsignature); event PermissionRemoved(bytes4 methodsignature); event ValidatorAdded(address indexed validator); event ValidatorRemoved(address indexed validator); /** Modifiers */ /** * @notice Throws if called by any account that does not have access to set attributes */ modifier onlyValidator() { require (isValidator(msg.sender), "Sender must be validator"); _; } /** * @notice Sets a permission within the list of permissions. * @param _methodsignature Signature of the method that this permission controls. * @param _permissionName A "slug" name for this permission (e.g. "canMint"). * @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens"). * @param _contractName Name of the contract that the method belongs to. */ function addPermission( bytes4 _methodsignature, string _permissionName, string _permissionDescription, string _contractName) public onlyValidator { Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true); permissions[_methodsignature] = p; emit PermissionAdded(_methodsignature); } /** * @notice Removes a permission the list of permissions. * @param _methodsignature Signature of the method that this permission controls. */ function removePermission(bytes4 _methodsignature) public onlyValidator { permissions[_methodsignature].active = false; emit PermissionRemoved(_methodsignature); } /** * @notice Sets a permission in the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature"); userPermissions[_who][_methodsignature] = true; } /** * @notice Removes a permission from the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature"); userPermissions[_who][_methodsignature] = false; } /** * @notice add a Validator * @param _validator Address of validator to add */ function addValidator(address _validator) public onlyOwner { validators[_validator] = true; emit ValidatorAdded(_validator); } /** * @notice remove a Validator * @param _validator Address of validator to remove */ function removeValidator(address _validator) public onlyOwner { validators[_validator] = false; emit ValidatorRemoved(_validator); } /** * @notice does validator exist? * @return true if yes, false if no **/ function isValidator(address _validator) public view returns (bool) { return validators[_validator]; } /** * @notice does permission exist? * @return true if yes, false if no **/ function isPermission(bytes4 _methodsignature) public view returns (bool) { return permissions[_methodsignature].active; } /** * @notice get Permission structure * @param _methodsignature request to retrieve the Permission struct for this methodsignature * @return Permission **/ function getPermission(bytes4 _methodsignature) public view returns (string name, string description, string contract_name, bool active) { return (permissions[_methodsignature].name, permissions[_methodsignature].description, permissions[_methodsignature].contract_name, permissions[_methodsignature].active); } /** * @notice does permission exist? * @return true if yes, false if no **/ function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) { return userPermissions[_who][_methodsignature]; } } /** * @title RegulatorProxy * @dev A RegulatorProxy is a proxy contract that acts identically to a Regulator from the * user's point of view. A proxy can change its data storage locations and can also * change its implementation contract location. A call to RegulatorProxy delegates the function call * to the latest implementation contract's version of the function and the proxy then * calls that function in the context of the proxy's data storage * */ contract RegulatorProxy is UpgradeabilityProxy, RegulatorStorage { /** * @dev CONSTRUCTOR * @param _implementation the contract who's logic the proxy will initially delegate functionality to **/ constructor(address _implementation) public UpgradeabilityProxy(_implementation) {} /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) public onlyOwner { _upgradeTo(newImplementation); } /** * @return The address of the implementation. */ function implementation() public view returns (address) { return _implementation(); } } /** * @title Regulator * @dev Regulator can be configured to meet relevant securities regulations, KYC policies * AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken * makes compliant transfers possible. Contains the userPermissions necessary * for regulatory compliance. * */ contract Regulator is RegulatorStorage { /** Modifiers */ /** * @notice Throws if called by any account that does not have access to set attributes */ modifier onlyValidator() { require (isValidator(msg.sender), "Sender must be validator"); _; } /** Events */ event LogWhitelistedUser(address indexed who); event LogBlacklistedUser(address indexed who); event LogNonlistedUser(address indexed who); event LogSetMinter(address indexed who); event LogRemovedMinter(address indexed who); event LogSetBlacklistDestroyer(address indexed who); event LogRemovedBlacklistDestroyer(address indexed who); event LogSetBlacklistSpender(address indexed who); event LogRemovedBlacklistSpender(address indexed who); /** * @notice Sets the necessary permissions for a user to mint tokens. * @param _who The address of the account that we are setting permissions for. */ function setMinter(address _who) public onlyValidator { _setMinter(_who); } /** * @notice Removes the necessary permissions for a user to mint tokens. * @param _who The address of the account that we are removing permissions for. */ function removeMinter(address _who) public onlyValidator { _removeMinter(_who); } /** * @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account. * @param _who The address of the account that we are setting permissions for. */ function setBlacklistSpender(address _who) public onlyValidator { require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token"); setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG); emit LogSetBlacklistSpender(_who); } /** * @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account. * @param _who The address of the account that we are removing permissions for. */ function removeBlacklistSpender(address _who) public onlyValidator { require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token"); removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG); emit LogRemovedBlacklistSpender(_who); } /** * @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account. * @param _who The address of the account that we are setting permissions for. */ function setBlacklistDestroyer(address _who) public onlyValidator { require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token"); setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG); emit LogSetBlacklistDestroyer(_who); } /** * @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account. * @param _who The address of the account that we are removing permissions for. */ function removeBlacklistDestroyer(address _who) public onlyValidator { require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token"); removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG); emit LogRemovedBlacklistDestroyer(_who); } /** * @notice Sets the necessary permissions for a "whitelisted" user. * @param _who The address of the account that we are setting permissions for. */ function setWhitelistedUser(address _who) public onlyValidator { _setWhitelistedUser(_who); } /** * @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts * frozen; they cannot transfer, burn, or withdraw any tokens. * @param _who The address of the account that we are setting permissions for. */ function setBlacklistedUser(address _who) public onlyValidator { _setBlacklistedUser(_who); } /** * @notice Sets the necessary permissions for a "nonlisted" user. Nonlisted users can trade tokens, * but cannot burn them (and therefore cannot convert them into fiat.) * @param _who The address of the account that we are setting permissions for. */ function setNonlistedUser(address _who) public onlyValidator { _setNonlistedUser(_who); } /** Returns whether or not a user is whitelisted. * @param _who The address of the account in question. * @return `true` if the user is whitelisted, `false` otherwise. */ function isWhitelistedUser(address _who) public view returns (bool) { return (hasUserPermission(_who, BURN_SIG) && !hasUserPermission(_who, BLACKLISTED_SIG)); } /** Returns whether or not a user is blacklisted. * @param _who The address of the account in question. * @return `true` if the user is blacklisted, `false` otherwise. */ function isBlacklistedUser(address _who) public view returns (bool) { return (!hasUserPermission(_who, BURN_SIG) && hasUserPermission(_who, BLACKLISTED_SIG)); } /** Returns whether or not a user is nonlisted. * @param _who The address of the account in question. * @return `true` if the user is nonlisted, `false` otherwise. */ function isNonlistedUser(address _who) public view returns (bool) { return (!hasUserPermission(_who, BURN_SIG) && !hasUserPermission(_who, BLACKLISTED_SIG)); } /** Returns whether or not a user is a blacklist spender. * @param _who The address of the account in question. * @return `true` if the user is a blacklist spender, `false` otherwise. */ function isBlacklistSpender(address _who) public view returns (bool) { return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG); } /** Returns whether or not a user is a blacklist destroyer. * @param _who The address of the account in question. * @return `true` if the user is a blacklist destroyer, `false` otherwise. */ function isBlacklistDestroyer(address _who) public view returns (bool) { return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG); } /** Returns whether or not a user is a minter. * @param _who The address of the account in question. * @return `true` if the user is a minter, `false` otherwise. */ function isMinter(address _who) public view returns (bool) { return hasUserPermission(_who, MINT_SIG); } /** Internal Functions **/ function _setMinter(address _who) internal { require(isPermission(MINT_SIG), "Minting not supported by token"); setUserPermission(_who, MINT_SIG); emit LogSetMinter(_who); } function _removeMinter(address _who) internal { require(isPermission(MINT_SIG), "Minting not supported by token"); removeUserPermission(_who, MINT_SIG); emit LogRemovedMinter(_who); } function _setNonlistedUser(address _who) internal { require(isPermission(BURN_SIG), "Burn method not supported by token"); require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token"); removeUserPermission(_who, BURN_SIG); removeUserPermission(_who, BLACKLISTED_SIG); emit LogNonlistedUser(_who); } function _setBlacklistedUser(address _who) internal { require(isPermission(BURN_SIG), "Burn method not supported by token"); require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token"); removeUserPermission(_who, BURN_SIG); setUserPermission(_who, BLACKLISTED_SIG); emit LogBlacklistedUser(_who); } function _setWhitelistedUser(address _who) internal { require(isPermission(BURN_SIG), "Burn method not supported by token"); require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token"); setUserPermission(_who, BURN_SIG); removeUserPermission(_who, BLACKLISTED_SIG); emit LogWhitelistedUser(_who); } } /** * * @dev RegulatorProxyFactory creates new RegulatorProxy contracts with new data storage sheets, properly configured * with ownership, and the proxy logic implementations are based on a user-specified Regulator. * **/ contract RegulatorProxyFactory { // TODO: Instead of a single array of addresses, this should be a mapping or an array // of objects of type { address: ...new_regulator, type: whitelisted_or_cusd } address[] public regulators; // Events event CreatedRegulatorProxy(address newRegulator, uint256 index); /** * * @dev generate a new proxyaddress that users can cast to a Regulator or RegulatorProxy. The * proxy has empty data storage contracts connected to it and it is set with an initial logic contract * to which it will delegate functionality * @notice the method caller will have to claim ownership of regulators since regulators are claimable * @param regulatorImplementation the address of the logic contract that the proxy will initialize its implementation to * **/ function createRegulatorProxy(address regulatorImplementation) public { // Store new data storage contracts for regulator proxy address proxy = address(new RegulatorProxy(regulatorImplementation)); Regulator newRegulator = Regulator(proxy); // Testing: Add msg.sender as a validator, add all permissions newRegulator.addValidator(msg.sender); addAllPermissions(newRegulator); // The function caller should own the proxy contract, so they will need to claim ownership RegulatorProxy(proxy).transferOwnership(msg.sender); regulators.push(proxy); emit CreatedRegulatorProxy(proxy, getCount()-1); } /** * * @dev Add all permission signatures to regulator * **/ function addAllPermissions(Regulator regulator) public { // Make this contract a temporary validator to add all permissions regulator.addValidator(this); regulator.addPermission(regulator.MINT_SIG(), "", "", "" ); regulator.addPermission(regulator.BURN_SIG(), "", "", "" ); regulator.addPermission(regulator.DESTROY_BLACKLISTED_TOKENS_SIG(), "", "", "" ); regulator.addPermission(regulator.APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG(), "", "", "" ); regulator.addPermission(regulator.BLACKLISTED_SIG(), "", "", "" ); regulator.addPermission(regulator.CONVERT_CARBON_DOLLAR_SIG(), "", "", "" ); regulator.addPermission(regulator.BURN_CARBON_DOLLAR_SIG(), "", "", "" ); regulator.addPermission(regulator.MINT_CUSD_SIG(), "", "", "" ); regulator.addPermission(regulator.CONVERT_WT_SIG(), "", "", "" ); regulator.removeValidator(this); } // Return number of proxies created function getCount() public view returns (uint256) { return regulators.length; } // Return the i'th created proxy. The most recently created proxy will be at position getCount()-1. function getRegulatorProxy(uint256 i) public view returns(address) { require((i < regulators.length) && (i >= 0), "Invalid index"); return regulators[i]; } }
Sets the necessary permissions for a "whitelisted" user. _who The address of the account that we are setting permissions for./
function setWhitelistedUser(address _who) public onlyValidator { _setWhitelistedUser(_who); }
1,273,886
pragma solidity ^0.4.24; /** * @title ReailtioSafeMath256 * @dev Math operations with safety checks that throw on error */ library RealitioSafeMath256 { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } pragma solidity ^0.4.24; /** * @title RealitioSafeMath32 * @dev Math operations with safety checks that throw on error * @dev Copy of SafeMath but for uint32 instead of uint256 * @dev Deleted functions we don't use */ library RealitioSafeMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; assert(c >= a); return c; } } pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.4.18; contract BalanceHolder { IERC20 public token; mapping(address => uint256) public balanceOf; event LogWithdraw( address indexed user, uint256 amount ); function withdraw() public { uint256 bal = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; require(token.transfer(msg.sender, bal)); emit LogWithdraw(msg.sender, bal); } } pragma solidity ^0.4.24; contract RealitioERC20 is BalanceHolder { using RealitioSafeMath256 for uint256; using RealitioSafeMath32 for uint32; address constant NULL_ADDRESS = address(0); // History hash when no history is created, or history has been cleared bytes32 constant NULL_HASH = bytes32(0); // An unitinalized finalize_ts for a question will indicate an unanswered question. uint32 constant UNANSWERED = 0; // An unanswered reveal_ts for a commitment will indicate that it does not exist. uint256 constant COMMITMENT_NON_EXISTENT = 0; // Commit->reveal timeout is 1/8 of the question timeout (rounded down). uint32 constant COMMITMENT_TIMEOUT_RATIO = 8; event LogSetQuestionFee( address arbitrator, uint256 amount ); event LogNewTemplate( uint256 indexed template_id, address indexed user, string question_text ); event LogNewQuestion( bytes32 indexed question_id, address indexed user, uint256 template_id, string question, bytes32 indexed content_hash, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce, uint256 created ); event LogFundAnswerBounty( bytes32 indexed question_id, uint256 bounty_added, uint256 bounty, address indexed user ); event LogNewAnswer( bytes32 answer, bytes32 indexed question_id, bytes32 history_hash, address indexed user, uint256 bond, uint256 ts, bool is_commitment ); event LogAnswerReveal( bytes32 indexed question_id, address indexed user, bytes32 indexed answer_hash, bytes32 answer, uint256 nonce, uint256 bond ); event LogNotifyOfArbitrationRequest( bytes32 indexed question_id, address indexed user ); event LogFinalize( bytes32 indexed question_id, bytes32 indexed answer ); event LogClaim( bytes32 indexed question_id, address indexed user, uint256 amount ); struct Question { bytes32 content_hash; address arbitrator; uint32 opening_ts; uint32 timeout; uint32 finalize_ts; bool is_pending_arbitration; uint256 bounty; bytes32 best_answer; bytes32 history_hash; uint256 bond; } // Stored in a mapping indexed by commitment_id, a hash of commitment hash, question, bond. struct Commitment { uint32 reveal_ts; bool is_revealed; bytes32 revealed_answer; } // Only used when claiming more bonds than fits into a transaction // Stored in a mapping indexed by question_id. struct Claim { address payee; uint256 last_bond; uint256 queued_funds; } uint256 nextTemplateID = 0; mapping(uint256 => uint256) public templates; mapping(uint256 => bytes32) public template_hashes; mapping(bytes32 => Question) public questions; mapping(bytes32 => Claim) public question_claims; mapping(bytes32 => Commitment) public commitments; mapping(address => uint256) public arbitrator_question_fees; modifier onlyArbitrator(bytes32 question_id) { require(msg.sender == questions[question_id].arbitrator, "msg.sender must be arbitrator"); _; } modifier stateAny() { _; } modifier stateNotCreated(bytes32 question_id) { require(questions[question_id].timeout == 0, "question must not exist"); _; } modifier stateOpen(bytes32 question_id) { require(questions[question_id].timeout > 0, "question must exist"); require(!questions[question_id].is_pending_arbitration, "question must not be pending arbitration"); uint32 finalize_ts = questions[question_id].finalize_ts; require(finalize_ts == UNANSWERED || finalize_ts > uint32(now), "finalization deadline must not have passed"); uint32 opening_ts = questions[question_id].opening_ts; require(opening_ts == 0 || opening_ts <= uint32(now), "opening date must have passed"); _; } modifier statePendingArbitration(bytes32 question_id) { require(questions[question_id].is_pending_arbitration, "question must be pending arbitration"); _; } modifier stateOpenOrPendingArbitration(bytes32 question_id) { require(questions[question_id].timeout > 0, "question must exist"); uint32 finalize_ts = questions[question_id].finalize_ts; require(finalize_ts == UNANSWERED || finalize_ts > uint32(now), "finalization dealine must not have passed"); uint32 opening_ts = questions[question_id].opening_ts; require(opening_ts == 0 || opening_ts <= uint32(now), "opening date must have passed"); _; } modifier stateFinalized(bytes32 question_id) { require(isFinalized(question_id), "question must be finalized"); _; } modifier bondMustDouble(bytes32 question_id, uint256 tokens) { require(tokens > 0, "bond must be positive"); require(tokens >= (questions[question_id].bond.mul(2)), "bond must be double at least previous bond"); _; } modifier previousBondMustNotBeatMaxPrevious(bytes32 question_id, uint256 max_previous) { if (max_previous > 0) { require(questions[question_id].bond <= max_previous, "bond must exceed max_previous"); } _; } function setToken(IERC20 _token) public { require(token == IERC20(0x0), "Token can only be initialized once"); token = _token; } /// @notice Constructor, sets up some initial templates /// @dev Creates some generalized templates for different question types used in the DApp. /// param _token The token used for everything except arbitration constructor() public { createTemplate('{"title": "%s", "type": "bool", "category": "%s", "lang": "%s"}'); createTemplate('{"title": "%s", "type": "uint", "decimals": 18, "category": "%s", "lang": "%s"}'); createTemplate('{"title": "%s", "type": "single-select", "outcomes": [%s], "category": "%s", "lang": "%s"}'); createTemplate('{"title": "%s", "type": "multiple-select", "outcomes": [%s], "category": "%s", "lang": "%s"}'); createTemplate('{"title": "%s", "type": "datetime", "category": "%s", "lang": "%s"}'); } /// @notice Function for arbitrator to set an optional per-question fee. /// @dev The per-question fee, charged when a question is asked, is intended as an anti-spam measure. /// @param fee The fee to be charged by the arbitrator when a question is asked function setQuestionFee(uint256 fee) stateAny() external { arbitrator_question_fees[msg.sender] = fee; emit LogSetQuestionFee(msg.sender, fee); } /// @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 content) stateAny() public returns (uint256) { uint256 id = nextTemplateID; templates[id] = block.number; template_hashes[id] = keccak256(abi.encodePacked(content)); emit LogNewTemplate(id, msg.sender, content); nextTemplateID = id.add(1); return id; } /// @notice Create a new reusable template and use it to ask a question /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @param content The template content /// @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 template, which is created sequentially. function createTemplateAndAskQuestion( string content, string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce ) // stateNotCreated is enforced by the internal _askQuestion public returns (bytes32) { uint256 template_id = createTemplate(content); return askQuestion(template_id, question, arbitrator, timeout, opening_ts, nonce); } /// @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 question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce) // stateNotCreated is enforced by the internal _askQuestion public returns (bytes32) { require(templates[template_id] > 0, "template must exist"); bytes32 content_hash = keccak256(abi.encodePacked(template_id, opening_ts, question)); bytes32 question_id = keccak256(abi.encodePacked(content_hash, arbitrator, timeout, msg.sender, nonce)); _askQuestion(question_id, content_hash, arbitrator, timeout, opening_ts, 0); emit LogNewQuestion(question_id, msg.sender, template_id, question, content_hash, arbitrator, timeout, opening_ts, nonce, now); return question_id; } /// @notice Ask a new question with 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. /// @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. /// @param tokens The combined initial question bounty and question fee /// @return The ID of the newly-created question, created deterministically. function askQuestionERC20(uint256 template_id, string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce, uint256 tokens) // stateNotCreated is enforced by the internal _askQuestion public returns (bytes32) { _deductTokensOrRevert(tokens); require(templates[template_id] > 0, "template must exist"); bytes32 content_hash = keccak256(abi.encodePacked(template_id, opening_ts, question)); bytes32 question_id = keccak256(abi.encodePacked(content_hash, arbitrator, timeout, msg.sender, nonce)); _askQuestion(question_id, content_hash, arbitrator, timeout, opening_ts, tokens); emit LogNewQuestion(question_id, msg.sender, template_id, question, content_hash, arbitrator, timeout, opening_ts, nonce, now); return question_id; } function _deductTokensOrRevert(uint256 tokens) internal { if (tokens == 0) { return; } uint256 bal = balanceOf[msg.sender]; // Deduct any tokens you have in your internal balance first if (bal > 0) { if (bal >= tokens) { balanceOf[msg.sender] = bal.sub(tokens); return; } else { tokens = tokens.sub(bal); balanceOf[msg.sender] = 0; } } // Now we need to charge the rest from require(token.transferFrom(msg.sender, address(this), tokens), "Transfer of tokens failed, insufficient approved balance?"); return; } function _askQuestion(bytes32 question_id, bytes32 content_hash, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 tokens) stateNotCreated(question_id) internal { uint256 bounty = tokens; // A timeout of 0 makes no sense, and we will use this to check existence require(timeout > 0, "timeout must be positive"); require(timeout < 365 days, "timeout must be less than 365 days"); require(arbitrator != NULL_ADDRESS, "arbitrator must be set"); // The arbitrator can set a fee for asking a question. // This is intended as an anti-spam defence. // The fee is waived if the arbitrator is asking the question. // This allows them to set an impossibly high fee and make users proxy the question through them. // This would allow more sophisticated pricing, question whitelisting etc. if (msg.sender != arbitrator) { uint256 question_fee = arbitrator_question_fees[arbitrator]; require(bounty >= question_fee, "ETH provided must cover question fee"); bounty = bounty.sub(question_fee); balanceOf[arbitrator] = balanceOf[arbitrator].add(question_fee); } questions[question_id].content_hash = content_hash; questions[question_id].arbitrator = arbitrator; questions[question_id].opening_ts = opening_ts; questions[question_id].timeout = timeout; questions[question_id].bounty = bounty; } /// @notice Add funds to the bounty for a question /// @dev Add bounty funds after the initial question creation. Can be done any time until the question is finalized. /// @param question_id The ID of the question you wish to fund /// @param tokens The number of tokens to fund function fundAnswerBountyERC20(bytes32 question_id, uint256 tokens) stateOpen(question_id) external { _deductTokensOrRevert(tokens); questions[question_id].bounty = questions[question_id].bounty.add(tokens); emit LogFundAnswerBounty(question_id, tokens, questions[question_id].bounty, msg.sender); } /// @notice Submit an answer for a question. /// @dev Adds the answer to the history and updates the current "best" answer. /// May be subject to front-running attacks; Substitute submitAnswerCommitment()->submitAnswerReveal() to prevent them. /// @param question_id The ID of the question /// @param answer The answer, encoded into bytes32 /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. /// @param tokens The amount of tokens to submit function submitAnswerERC20(bytes32 question_id, bytes32 answer, uint256 max_previous, uint256 tokens) stateOpen(question_id) bondMustDouble(question_id, tokens) previousBondMustNotBeatMaxPrevious(question_id, max_previous) external { _deductTokensOrRevert(tokens); _addAnswerToHistory(question_id, answer, msg.sender, tokens, false); _updateCurrentAnswer(question_id, answer, questions[question_id].timeout); } // @notice Verify and store a commitment, including an appropriate timeout // @param question_id The ID of the question to store // @param commitment The ID of the commitment function _storeCommitment(bytes32 question_id, bytes32 commitment_id) internal { require(commitments[commitment_id].reveal_ts == COMMITMENT_NON_EXISTENT, "commitment must not already exist"); uint32 commitment_timeout = questions[question_id].timeout / COMMITMENT_TIMEOUT_RATIO; commitments[commitment_id].reveal_ts = uint32(now).add(commitment_timeout); } /// @notice Submit the hash of an answer, laying your claim to that answer if you reveal it in a subsequent transaction. /// @dev Creates a hash, commitment_id, uniquely identifying this answer, to this question, with this bond. /// The commitment_id is stored in the answer history where the answer would normally go. /// Does not update the current best answer - this is left to the later submitAnswerReveal() transaction. /// @param question_id The ID of the question /// @param answer_hash The hash of your answer, plus a nonce that you will later reveal /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. /// @param _answerer If specified, the address to be given as the question answerer. Defaults to the sender. /// @param tokens Number of tokens sent /// @dev Specifying the answerer is useful if you want to delegate the commit-and-reveal to a third-party. function submitAnswerCommitmentERC20(bytes32 question_id, bytes32 answer_hash, uint256 max_previous, address _answerer, uint256 tokens) stateOpen(question_id) bondMustDouble(question_id, tokens) previousBondMustNotBeatMaxPrevious(question_id, max_previous) external { _deductTokensOrRevert(tokens); bytes32 commitment_id = keccak256(abi.encodePacked(question_id, answer_hash, tokens)); address answerer = (_answerer == NULL_ADDRESS) ? msg.sender : _answerer; _storeCommitment(question_id, commitment_id); _addAnswerToHistory(question_id, commitment_id, answerer, tokens, true); } /// @notice Submit the answer whose hash you sent in a previous submitAnswerCommitment() transaction /// @dev Checks the parameters supplied recreate an existing commitment, and stores the revealed answer /// Updates the current answer unless someone has since supplied a new answer with a higher bond /// msg.sender is intentionally not restricted to the user who originally sent the commitment; /// For example, the user may want to provide the answer+nonce to a third-party service and let them send the tx /// NB If we are pending arbitration, it will be up to the arbitrator to wait and see any outstanding reveal is sent /// @param question_id The ID of the question /// @param answer The answer, encoded as bytes32 /// @param nonce The nonce that, combined with the answer, recreates the answer_hash you gave in submitAnswerCommitment() /// @param bond The bond that you paid in your submitAnswerCommitment() transaction function submitAnswerReveal(bytes32 question_id, bytes32 answer, uint256 nonce, uint256 bond) stateOpenOrPendingArbitration(question_id) external { bytes32 answer_hash = keccak256(abi.encodePacked(answer, nonce)); bytes32 commitment_id = keccak256(abi.encodePacked(question_id, answer_hash, bond)); require(!commitments[commitment_id].is_revealed, "commitment must not have been revealed yet"); require(commitments[commitment_id].reveal_ts > uint32(now), "reveal deadline must not have passed"); commitments[commitment_id].revealed_answer = answer; commitments[commitment_id].is_revealed = true; if (bond == questions[question_id].bond) { _updateCurrentAnswer(question_id, answer, questions[question_id].timeout); } emit LogAnswerReveal(question_id, msg.sender, answer_hash, answer, nonce, bond); } function _addAnswerToHistory(bytes32 question_id, bytes32 answer_or_commitment_id, address answerer, uint256 bond, bool is_commitment) internal { bytes32 new_history_hash = keccak256(abi.encodePacked(questions[question_id].history_hash, answer_or_commitment_id, bond, answerer, is_commitment)); // Update the current bond level, if there's a bond (ie anything except arbitration) if (bond > 0) { questions[question_id].bond = bond; } questions[question_id].history_hash = new_history_hash; emit LogNewAnswer(answer_or_commitment_id, question_id, new_history_hash, answerer, bond, now, is_commitment); } function _updateCurrentAnswer(bytes32 question_id, bytes32 answer, uint32 timeout_secs) internal { questions[question_id].best_answer = answer; questions[question_id].finalize_ts = uint32(now).add(timeout_secs); } /// @notice Notify the contract that the arbitrator has been paid for a question, freezing it pending their decision. /// @dev The arbitrator contract is trusted to only call this if they've been paid, and tell us who paid them. /// @param question_id The ID of the question /// @param requester The account that requested arbitration /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. function notifyOfArbitrationRequest(bytes32 question_id, address requester, uint256 max_previous) onlyArbitrator(question_id) stateOpen(question_id) previousBondMustNotBeatMaxPrevious(question_id, max_previous) external { require(questions[question_id].bond > 0, "Question must already have an answer when arbitration is requested"); questions[question_id].is_pending_arbitration = true; emit LogNotifyOfArbitrationRequest(question_id, requester); } /// @notice Submit the answer for a question, for use by the arbitrator. /// @dev Doesn't require (or allow) a bond. /// If the current final answer is correct, the account should be whoever submitted it. /// If the current final answer is wrong, the account should be whoever paid for arbitration. /// However, the answerer stipulations are not enforced by the contract. /// @param question_id The ID of the question /// @param answer The answer, encoded into bytes32 /// @param answerer The account credited with this answer for the purpose of bond claims function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer) onlyArbitrator(question_id) statePendingArbitration(question_id) external { require(answerer != NULL_ADDRESS, "answerer must be provided"); emit LogFinalize(question_id, answer); questions[question_id].is_pending_arbitration = false; _addAnswerToHistory(question_id, answer, answerer, 0, false); _updateCurrentAnswer(question_id, answer, 0); } /// @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 public returns (bool) { uint32 finalize_ts = questions[question_id].finalize_ts; return ( !questions[question_id].is_pending_arbitration && (finalize_ts > UNANSWERED) && (finalize_ts <= uint32(now)) ); } /// @notice (Deprecated) 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 getFinalAnswer(bytes32 question_id) stateFinalized(question_id) external view returns (bytes32) { return questions[question_id].best_answer; } /// @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) stateFinalized(question_id) external view returns (bytes32) { return questions[question_id].best_answer; } /// @notice Return the final answer to the specified question, provided it matches the specified criteria. /// @dev Reverts if the question is not finalized, or if it does not match the specified criteria. /// @param question_id The ID of the question /// @param content_hash The hash of the question content (template ID + opening time + question parameter string) /// @param arbitrator The arbitrator chosen for the question (regardless of whether they are asked to arbitrate) /// @param min_timeout The timeout set in the initial question settings must be this high or higher /// @param min_bond The bond sent with the final answer must be this high or higher /// @return The answer formatted as a bytes32 function getFinalAnswerIfMatches( bytes32 question_id, bytes32 content_hash, address arbitrator, uint32 min_timeout, uint256 min_bond ) stateFinalized(question_id) external view returns (bytes32) { require(content_hash == questions[question_id].content_hash, "content hash must match"); require(arbitrator == questions[question_id].arbitrator, "arbitrator must match"); require(min_timeout <= questions[question_id].timeout, "timeout must be long enough"); require(min_bond <= questions[question_id].bond, "bond must be high enough"); return questions[question_id].best_answer; } /// @notice Assigns the winnings (bounty and bonds) to everyone who gave the accepted answer /// Caller must provide the answer history, in reverse order /// @dev Works up the chain and assign bonds to the person who gave the right answer /// If someone gave the winning answer earlier, they must get paid from the higher bond /// That means we can't pay out the bond added at n until we have looked at n-1 /// The first answer is authenticated by checking against the stored history_hash. /// One of the inputs to history_hash is the history_hash before it, so we use that to authenticate the next entry, etc /// Once we get to a null hash we'll know we're done and there are no more answers. /// Usually you would call the whole thing in a single transaction, but if not then the data is persisted to pick up later. /// @param question_id The ID of the question /// @param history_hashes Second-last-to-first, the hash of each history entry. (Final one should be empty). /// @param addrs Last-to-first, the address of each answerer or commitment sender /// @param bonds Last-to-first, the bond supplied with each answer or commitment /// @param answers Last-to-first, each answer supplied, or commitment ID if the answer was supplied with commit->reveal function claimWinnings( bytes32 question_id, bytes32[] history_hashes, address[] addrs, uint256[] bonds, bytes32[] answers ) stateFinalized(question_id) public { require(history_hashes.length > 0, "at least one history hash entry must be provided"); // These are only set if we split our claim over multiple transactions. address payee = question_claims[question_id].payee; uint256 last_bond = question_claims[question_id].last_bond; uint256 queued_funds = question_claims[question_id].queued_funds; // Starts as the hash of the final answer submitted. It'll be cleared when we're done. // If we're splitting the claim over multiple transactions, it'll be the hash where we left off last time bytes32 last_history_hash = questions[question_id].history_hash; bytes32 best_answer = questions[question_id].best_answer; uint256 i; for (i = 0; i < history_hashes.length; i++) { // Check input against the history hash, and see which of 2 possible values of is_commitment fits. bool is_commitment = _verifyHistoryInputOrRevert(last_history_hash, history_hashes[i], answers[i], bonds[i], addrs[i]); queued_funds = queued_funds.add(last_bond); (queued_funds, payee) = _processHistoryItem( question_id, best_answer, queued_funds, payee, addrs[i], bonds[i], answers[i], is_commitment); // Line the bond up for next time, when it will be added to somebody's queued_funds last_bond = bonds[i]; last_history_hash = history_hashes[i]; } if (last_history_hash != NULL_HASH) { // We haven't yet got to the null hash (1st answer), ie the caller didn't supply the full answer chain. // Persist the details so we can pick up later where we left off later. // If we know who to pay we can go ahead and pay them out, only keeping back last_bond // (We always know who to pay unless all we saw were unrevealed commits) if (payee != NULL_ADDRESS) { _payPayee(question_id, payee, queued_funds); queued_funds = 0; } question_claims[question_id].payee = payee; question_claims[question_id].last_bond = last_bond; question_claims[question_id].queued_funds = queued_funds; } else { // There is nothing left below us so the payee can keep what remains _payPayee(question_id, payee, queued_funds.add(last_bond)); delete question_claims[question_id]; } questions[question_id].history_hash = last_history_hash; } function _payPayee(bytes32 question_id, address payee, uint256 value) internal { balanceOf[payee] = balanceOf[payee].add(value); emit LogClaim(question_id, payee, value); } function _verifyHistoryInputOrRevert( bytes32 last_history_hash, bytes32 history_hash, bytes32 answer, uint256 bond, address addr ) internal pure returns (bool) { if (last_history_hash == keccak256(abi.encodePacked(history_hash, answer, bond, addr, true)) ) { return true; } if (last_history_hash == keccak256(abi.encodePacked(history_hash, answer, bond, addr, false)) ) { return false; } revert("History input provided did not match the expected hash"); } function _processHistoryItem( bytes32 question_id, bytes32 best_answer, uint256 queued_funds, address payee, address addr, uint256 bond, bytes32 answer, bool is_commitment ) internal returns (uint256, address) { // For commit-and-reveal, the answer history holds the commitment ID instead of the answer. // We look at the referenced commitment ID and switch in the actual answer. if (is_commitment) { bytes32 commitment_id = answer; // If it's a commit but it hasn't been revealed, it will always be considered wrong. if (!commitments[commitment_id].is_revealed) { delete commitments[commitment_id]; return (queued_funds, payee); } else { answer = commitments[commitment_id].revealed_answer; delete commitments[commitment_id]; } } if (answer == best_answer) { if (payee == NULL_ADDRESS) { // The entry is for the first payee we come to, ie the winner. // They get the question bounty. payee = addr; queued_funds = queued_funds.add(questions[question_id].bounty); questions[question_id].bounty = 0; } else if (addr != payee) { // Answerer has changed, ie we found someone lower down who needs to be paid // The lower answerer will take over receiving bonds from higher answerer. // They should also be paid the takeover fee, which is set at a rate equivalent to their bond. // (This is our arbitrary rule, to give consistent right-answerers a defence against high-rollers.) // There should be enough for the fee, but if not, take what we have. // There's an edge case involving weird arbitrator behaviour where we may be short. uint256 answer_takeover_fee = (queued_funds >= bond) ? bond : queued_funds; // Settle up with the old (higher-bonded) payee _payPayee(question_id, payee, queued_funds.sub(answer_takeover_fee)); // Now start queued_funds again for the new (lower-bonded) payee payee = addr; queued_funds = answer_takeover_fee; } } return (queued_funds, payee); } /// @notice Convenience function to assign bounties/bonds for multiple questions in one go, then withdraw all your funds. /// Caller must provide the answer history for each question, in reverse order /// @dev Can be called by anyone to assign bonds/bounties, but funds are only withdrawn for the user making the call. /// @param question_ids The IDs of the questions you want to claim for /// @param lengths The number of history entries you will supply for each question ID /// @param hist_hashes In a single list for all supplied questions, the hash of each history entry. /// @param addrs In a single list for all supplied questions, the address of each answerer or commitment sender /// @param bonds In a single list for all supplied questions, the bond supplied with each answer or commitment /// @param answers In a single list for all supplied questions, each answer supplied, or commitment ID function claimMultipleAndWithdrawBalance( bytes32[] question_ids, uint256[] lengths, bytes32[] hist_hashes, address[] addrs, uint256[] bonds, bytes32[] answers ) stateAny() // The finalization checks are done in the claimWinnings function public { uint256 qi; uint256 i; for (qi = 0; qi < question_ids.length; qi++) { bytes32 qid = question_ids[qi]; uint256 ln = lengths[qi]; bytes32[] memory hh = new bytes32[](ln); address[] memory ad = new address[](ln); uint256[] memory bo = new uint256[](ln); bytes32[] memory an = new bytes32[](ln); uint256 j; for (j = 0; j < ln; j++) { hh[j] = hist_hashes[i]; ad[j] = addrs[i]; bo[j] = bonds[i]; an[j] = answers[i]; i++; } claimWinnings(qid, hh, ad, bo, an); } withdraw(); } /// @notice Returns the questions's content hash, identifying the question content /// @param question_id The ID of the question function getContentHash(bytes32 question_id) public view returns(bytes32) { return questions[question_id].content_hash; } /// @notice Returns the arbitrator address for the question /// @param question_id The ID of the question function getArbitrator(bytes32 question_id) public view returns(address) { return questions[question_id].arbitrator; } /// @notice Returns the timestamp when the question can first be answered /// @param question_id The ID of the question function getOpeningTS(bytes32 question_id) public view returns(uint32) { return questions[question_id].opening_ts; } /// @notice Returns the timeout in seconds used after each answer /// @param question_id The ID of the question function getTimeout(bytes32 question_id) public view returns(uint32) { return questions[question_id].timeout; } /// @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) public view returns(uint32) { return questions[question_id].finalize_ts; } /// @notice Returns whether the question is pending arbitration /// @param question_id The ID of the question function isPendingArbitration(bytes32 question_id) public view returns(bool) { return questions[question_id].is_pending_arbitration; } /// @notice Returns the current total unclaimed bounty /// @dev Set back to zero once the bounty has been claimed /// @param question_id The ID of the question function getBounty(bytes32 question_id) public view returns(uint256) { return questions[question_id].bounty; } /// @notice Returns the current best answer /// @param question_id The ID of the question function getBestAnswer(bytes32 question_id) public view returns(bytes32) { return questions[question_id].best_answer; } /// @notice Returns the history hash of the question /// @param question_id The ID of the question /// @dev Updated on each answer, then rewound as each is claimed function getHistoryHash(bytes32 question_id) public view returns(bytes32) { return questions[question_id].history_hash; } /// @notice Returns the highest bond posted so far for a question /// @param question_id The ID of the question function getBond(bytes32 question_id) public view returns(uint256) { return questions[question_id].bond; } }
Verify and store a commitment, including an appropriate timeout question_id The ID of the question to store commitment The ID of the commitment
function _storeCommitment(bytes32 question_id, bytes32 commitment_id) internal { require(commitments[commitment_id].reveal_ts == COMMITMENT_NON_EXISTENT, "commitment must not already exist"); uint32 commitment_timeout = questions[question_id].timeout / COMMITMENT_TIMEOUT_RATIO; commitments[commitment_id].reveal_ts = uint32(now).add(commitment_timeout); }
15,815,191
pragma solidity ^0.4.24; contract _8thereum { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyTokenHolders() { require(myTokens() > 0); _; } // only people with profits modifier onlyDividendPositive() { require(myDividends(true) > 0); _; } // only owner modifier onlyOwner() { require (address(msg.sender) == owner); _; } // only non-whales modifier onlyNonOwner() { require (address(msg.sender) != owner); _; } modifier onlyFoundersIfNotPublic() { if(!openToThePublic) { require (founders[address(msg.sender)] == true); } _; } modifier onlyApprovedContracts() { if(!gameList[msg.sender]) { require (msg.sender == tx.origin); } _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event lotteryPayout( address customerAddress, uint256 lotterySupply ); event whaleDump( uint256 amount ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "8thereum"; string public symbol = "BIT"; bool public openToThePublic = false; address public owner; uint8 constant public decimals = 18; uint8 constant internal dividendFee = 15; uint256 constant internal tokenPrice = 500000000000000;//0.0005 ether uint256 constant internal magnitude = 2**64; uint256 constant public referralLinkRequirement = 5e18;// 5 token minimum for referral link /*================================ = DATASETS = ================================*/ mapping(address => bool) internal gameList; mapping(address => uint256) internal publicTokenLedger; mapping(address => uint256) public whaleLedger; mapping(address => uint256) public gameLedger; mapping(address => uint256) internal referralBalances; mapping(address => int256) internal payoutsTo_; mapping(address => mapping(address => uint256)) public gamePlayers; mapping(address => bool) internal founders; address[] lotteryPlayers; uint256 internal lotterySupply = 0; uint256 internal tokenSupply = 0; uint256 internal gameSuppply = 0; uint256 internal profitPerShare_; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { // no admin, but the owner of the contract is the address used for whale owner = address(msg.sender); // add founders here... Founders don&#39;t get any special priveledges except being first in line at launch day founders[owner] = true; //owner&#39;s address founders[0x7e474fe5Cfb720804860215f407111183cbc2f85] = true; //KENNY founders[0x5138240E96360ad64010C27eB0c685A8b2eDE4F2] = true; //crypt0b!t founders[0xAA7A7C2DECB180f68F11E975e6D92B5Dc06083A6] = true; //NumberOfThings founders[0x6DC622a04Fd13B6a1C3C5B229CA642b8e50e1e74] = true; //supermanlxvi founders[0x41a21b264F9ebF6cF571D4543a5b3AB1c6bEd98C] = true; //Ravi } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral address */ function buy(address referredyBy) onlyFoundersIfNotPublic() public payable returns(uint256) { require (msg.sender == tx.origin); excludeWhale(referredyBy); } /** * Fallback function to handle ethereum that was send straight to the contract */ function() onlyFoundersIfNotPublic() payable public { require (msg.sender == tx.origin); excludeWhale(0x0); } /** * Converts all of caller&#39;s dividends to tokens. */ function reinvest() onlyDividendPositive() onlyNonOwner() public { require (msg.sender == tx.origin); // fetch dividends uint256 dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address customerAddress = msg.sender; payoutsTo_[customerAddress] += int256(SafeMath.mul(dividends, magnitude)); // retrieve ref. bonus dividends += referralBalances[customerAddress]; referralBalances[customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(dividends, 0x0); // fire event for logging emit onReinvestment(customerAddress, dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() onlyNonOwner() onlyTokenHolders() public { require (msg.sender == tx.origin); // get token count for caller & sell them all address customerAddress = address(msg.sender); uint256 _tokens = publicTokenLedger[customerAddress]; if(_tokens > 0) { sell(_tokens); } withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyNonOwner() onlyDividendPositive() public { require (msg.sender == tx.origin); // setup data address customerAddress = msg.sender; uint256 dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[customerAddress] += int256(SafeMath.mul(dividends, magnitude)); // add ref. bonus dividends += referralBalances[customerAddress]; referralBalances[customerAddress] = 0; customerAddress.transfer(dividends); // fire event for logging emit onWithdraw(customerAddress, dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyNonOwner() onlyTokenHolders() public { require (msg.sender == tx.origin); require((_amountOfTokens <= publicTokenLedger[msg.sender]) && (_amountOfTokens > 0)); uint256 _tokens = _amountOfTokens; uint256 ethereum = tokensToEthereum_(_tokens); uint256 dividends = (ethereum * dividendFee) / 100; uint256 taxedEthereum = SafeMath.sub(ethereum, dividends); //Take some divs for the lottery and whale uint256 lotteryAndWhaleFee = dividends / 3; dividends -= lotteryAndWhaleFee; //figure out the lotteryFee uint256 lotteryFee = lotteryAndWhaleFee / 2; //add tokens to the whale uint256 whaleFee = lotteryAndWhaleFee - lotteryFee; whaleLedger[owner] += whaleFee; //add tokens to the lotterySupply lotterySupply += ethereumToTokens_(lotteryFee); // burn the sold tokens tokenSupply -= _tokens; publicTokenLedger[msg.sender] -= _tokens; // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (taxedEthereum * magnitude)); payoutsTo_[msg.sender] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (dividends * magnitude) / tokenSupply); } // fire event for logging emit onTokenSell(msg.sender, _tokens, taxedEthereum); } /** * Transfer tokens from the caller to a new holder. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyNonOwner() onlyTokenHolders() onlyApprovedContracts() public returns(bool) { assert(_toAddress != owner); // setup if(gameList[msg.sender] == true) //If game is transferring tokens { require((_amountOfTokens <= gameLedger[msg.sender]) && (_amountOfTokens > 0 )); // exchange tokens gameLedger[msg.sender] -= _amountOfTokens; gameSuppply -= _amountOfTokens; publicTokenLedger[_toAddress] += _amountOfTokens; // update dividend trackers payoutsTo_[_toAddress] += int256(profitPerShare_ * _amountOfTokens); } else if (gameList[_toAddress] == true) //If customer transferring tokens to game { // make sure we have the requested tokens //each game should only cost one token to play require((_amountOfTokens <= publicTokenLedger[msg.sender]) && (_amountOfTokens > 0 && (_amountOfTokens == 1e18))); // exchange tokens publicTokenLedger[msg.sender] -= _amountOfTokens; gameLedger[_toAddress] += _amountOfTokens; gameSuppply += _amountOfTokens; gamePlayers[_toAddress][msg.sender] += _amountOfTokens; // update dividend trackers payoutsTo_[msg.sender] -= int256(profitPerShare_ * _amountOfTokens); } else{ // make sure we have the requested tokens require((_amountOfTokens <= publicTokenLedger[msg.sender]) && (_amountOfTokens > 0 )); // exchange tokens publicTokenLedger[msg.sender] -= _amountOfTokens; publicTokenLedger[_toAddress] += _amountOfTokens; // update dividend trackers payoutsTo_[msg.sender] -= int256(profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += int256(profitPerShare_ * _amountOfTokens); } // fire event for logging emit Transfer(msg.sender, _toAddress, _amountOfTokens); // ERC20 return true; } /*---------- OWNER ONLY FUNCTIONS ----------*/ /** * future games can be added so they can&#39;t earn divs on their token balances */ function setGames(address newGameAddress) onlyOwner() public { gameList[newGameAddress] = true; } /** * Want to prevent snipers from buying prior to launch */ function goPublic() onlyOwner() public returns(bool) { openToThePublic = true; return openToThePublic; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return (tokenSupply + lotterySupply + gameSuppply); //adds the tokens from ambassadors to the supply (but not to the dividends calculation which is based on the supply) } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { return balanceOf(msg.sender); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { return _includeReferralBonus ? dividendsOf(msg.sender) + referralBalances[msg.sender] : dividendsOf(msg.sender) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address customerAddress) view public returns(uint256) { uint256 balance; if (customerAddress == owner) { // to show div balance of owner balance = whaleLedger[customerAddress]; } else if(gameList[customerAddress] == true) { // games can still see their token balance balance = gameLedger[customerAddress]; } else { // to see token balance for anyone else balance = publicTokenLedger[customerAddress]; } return balance; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * publicTokenLedger[customerAddress]) - payoutsTo_[customerAddress]) / magnitude; } /** * Return the buy and sell price of 1 individual token. */ function buyAndSellPrice() public pure returns(uint256) { uint256 ethereum = tokenPrice; uint256 dividends = SafeMath.div(SafeMath.mul(ethereum, dividendFee ), 100); uint256 taxedEthereum = SafeMath.sub(ethereum, dividends); return taxedEthereum; } /** * Function for the frontend to dynamically retrieve the price of buy orders. */ function calculateTokensReceived(uint256 ethereumToSpend) public pure returns(uint256) { require(ethereumToSpend >= tokenPrice); uint256 dividends = SafeMath.div(SafeMath.mul(ethereumToSpend, dividendFee ), 100); uint256 taxedEthereum = SafeMath.sub(ethereumToSpend, dividends); uint256 amountOfTokens = ethereumToTokens_(taxedEthereum); return amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price of sell orders. */ function calculateEthereumReceived(uint256 tokensToSell) public view returns(uint256) { require(tokensToSell <= tokenSupply); uint256 ethereum = tokensToEthereum_(tokensToSell); uint256 dividends = SafeMath.div(SafeMath.mul(ethereum, dividendFee ), 100); uint256 taxedEthereum = SafeMath.sub(ethereum, dividends); return taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function excludeWhale(address referredyBy) onlyNonOwner() internal returns(uint256) { require (msg.sender == tx.origin); uint256 tokenAmount; tokenAmount = purchaseTokens(msg.value, referredyBy); //redirects to purchaseTokens so same functionality if(gameList[msg.sender] == true) { tokenSupply = SafeMath.sub(tokenSupply, tokenAmount); // takes out game&#39;s tokens from the tokenSupply (important for redistribution) publicTokenLedger[msg.sender] = SafeMath.sub(publicTokenLedger[msg.sender], tokenAmount); // takes out game&#39;s tokens from its ledger so it is "officially" holding 0 tokens. (=> doesn&#39;t receive dividends anymore) gameLedger[msg.sender] += tokenAmount; //it gets a special ledger so it can&#39;t sell its tokens gameSuppply += tokenAmount; // we need this for a correct totalSupply() number later } return tokenAmount; } function purchaseTokens(uint256 incomingEthereum, address referredyBy) internal returns(uint256) { require (msg.sender == tx.origin); // data setup uint256 undividedDivs = SafeMath.div(SafeMath.mul(incomingEthereum, dividendFee ), 100); //divide the divs uint256 lotteryAndWhaleFee = undividedDivs / 3; uint256 referralBonus = lotteryAndWhaleFee; uint256 dividends = SafeMath.sub(undividedDivs, (referralBonus + lotteryAndWhaleFee)); uint256 taxedEthereum = incomingEthereum - undividedDivs; uint256 amountOfTokens = ethereumToTokens_(taxedEthereum); uint256 whaleFee = lotteryAndWhaleFee / 2; //add divs to whale whaleLedger[owner] += whaleFee; //add tokens to the lotterySupply lotterySupply += ethereumToTokens_(lotteryAndWhaleFee - whaleFee); //add entry to lottery lotteryPlayers.push(msg.sender); uint256 fee = dividends * magnitude; require(amountOfTokens > 0 && (amountOfTokens + tokenSupply) > tokenSupply); // is the user referred by a masternode? if( // is this a referred purchase? referredyBy != 0x0000000000000000000000000000000000000000 && // no cheating! referredyBy != msg.sender && //can&#39;t use games for referralBonus gameList[referredyBy] == false && // does the referrer have at least 5 tokens? publicTokenLedger[referredyBy] >= referralLinkRequirement ) { // wealth redistribution referralBalances[referredyBy] += referralBonus; } else { // no ref purchase // add the referral bonus back dividends += referralBonus; fee = dividends * magnitude; } uint256 payoutDividends = isWhalePaying(); // we can&#39;t give people infinite ethereum if(tokenSupply > 0) { // add tokens to the pool tokenSupply += amountOfTokens; // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += ((payoutDividends + dividends) * magnitude / (tokenSupply)); // calculate the amount of tokens the customer receives over his purchase fee -= fee-(amountOfTokens * (dividends * magnitude / (tokenSupply))); } else { // add tokens to the pool tokenSupply = amountOfTokens; //if there are zero tokens prior to this buy, and the whale is triggered, send dividends back to whale if(whaleLedger[owner] == 0) { whaleLedger[owner] = payoutDividends; } } // update circulating supply & the ledger address for the customer publicTokenLedger[msg.sender] += amountOfTokens; // Tells the contract that the buyer doesn&#39;t deserve dividends for the tokens before they owned them; // BUT, you still get the whale&#39;s divs from your purchase.... so, you still get SOMETHING. int256 _updatedPayouts = int256((profitPerShare_ * amountOfTokens) - fee); payoutsTo_[msg.sender] += _updatedPayouts; // fire event for logging emit onTokenPurchase(msg.sender, incomingEthereum, amountOfTokens, referredyBy); return amountOfTokens; } /** * Calculate token sell value. * It&#39;s a simple algorithm. Hopefully, you don&#39;t need a whitepaper with it in scientific notation. */ function isWhalePaying() private returns(uint256) { uint256 payoutDividends = 0; // this is where we check for lottery winner if(whaleLedger[owner] >= 1 ether) { if(lotteryPlayers.length > 0) { uint256 winner = uint256(blockhash(block.number-1))%lotteryPlayers.length; publicTokenLedger[lotteryPlayers[winner]] += lotterySupply; emit lotteryPayout(lotteryPlayers[winner], lotterySupply); tokenSupply += lotterySupply; lotterySupply = 0; delete lotteryPlayers; } //whale pays out everyone its divs payoutDividends = whaleLedger[owner]; whaleLedger[owner] = 0; emit whaleDump(payoutDividends); } return payoutDividends; } /** * Calculate Token price based on an amount of incoming ethereum *It&#39;s a simple algorithm. Hopefully, you don&#39;t need a whitepaper with it in scientific notation. */ function ethereumToTokens_(uint256 ethereum) internal pure returns(uint256) { uint256 tokensReceived = ((ethereum / tokenPrice) * 1e18); return tokensReceived; } /** * Calculate token sell value. * It&#39;s a simple algorithm. Hopefully, you don&#39;t need a whitepaper with it in scientific notation. */ function tokensToEthereum_(uint256 coin) internal pure returns(uint256) { uint256 ethReceived = tokenPrice * (SafeMath.div(coin, 1e18)); return ethReceived; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Alias of sell() and withdraw()./ get token count for caller & sell them all
function exit() onlyNonOwner() onlyTokenHolders() public { require (msg.sender == tx.origin); address customerAddress = address(msg.sender); uint256 _tokens = publicTokenLedger[customerAddress]; if(_tokens > 0) { sell(_tokens); } withdraw(); }
2,284,223
pragma solidity ^0.4.21; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; /// @title interface to EmergencyStop contract interface IEmergencyStop { function breakerIsDisabled() external returns(bool); } /// @title interface to Bank contract interface IBank { function addFunds(address addr_) external payable; } /// @title interface to Users contract interface IUsers { function isStoreowner(address addr_) external returns(bool); function isShopper(address addr_) external returns(bool); } /// @title interface to Stores contract interface IStores { function storeExists(uint storeId_) external returns (bool); function getStoreOwner(uint storeId_) external returns(address); } /// @author Alexander 'rmi7' Remie /// @title Products contract contract Products is Ownable { // // // Variables // // IEmergencyStop private breaker; IStores private stores; IUsers private users; IBank private bank; uint constant public MIN_PRODUCT_PRICE = 0.01 * 1 ether; uint constant public MIN_PRODUCT_QUANTITY = 1; uint constant public MAX_PRODUCT_QUANTITY = 1000; uint public productIdCounter = 0; // storeId productIds mapping(uint => uint[]) public storeIdToProductIds; mapping(uint => uint) public productIdToStoreIndex; // productId productIdIdx-inside-storeIdToProductIds-of-correct-store // currently cannot return a struct from solidity, so this will be used only internally // we implement a getProduct(id) function down below to fetch a product from solidity (using an array) // productId product mapping(uint => Product) internal productIdToProduct; struct Product { uint id; uint storeId; bytes32 contentHash; // can be updated uint quantity; // can be updated uint price; // can be updated uint createdAt; uint updatedAt; // will be updated bool exists; // can be updated } // // // Events // // // this event is used to build the "All Products" page in the ui event ProductAdded(uint indexed productId, uint indexed storeId); event ProductRemoved(uint indexed productId, uint indexed storeId); event ProductPurchased(uint indexed productId, address indexed buyer, uint indexed price, uint quantity, uint newQuantity); event ProductUpdatedPrice(uint indexed productId, uint indexed oldPrice, uint indexed newPrice); event ProductUpdatedContent(uint indexed productId, bytes32 indexed oldContentHash, bytes32 indexed newContentHash); // // // Constructor // // /// @notice contract constructor /// @param breakerContract_ The address of the EmergencyStop contract /// @param usersContract_ The address of the Users contract /// @param storesContract_ The address of the Users contract /// @param bankContract_ The address of the Users contract constructor(address breakerContract_, address usersContract_, address storesContract_, address bankContract_) public { require(breakerContract_ != address(0), "breaker contract address should not be 0x0"); require(usersContract_ != address(0), "users contract address should not be 0x0"); require(storesContract_ != address(0), "stores contract address should not be 0x0"); require(bankContract_ != address(0), "bank contract address should not be 0x0"); breaker = IEmergencyStop(breakerContract_); users = IUsers(usersContract_); stores = IStores(storesContract_); bank = IBank(bankContract_); } // // // Modifiers // // modifier canCreateProduct(uint storeId_, address addr_) { require(breaker.breakerIsDisabled(), "contract breaker is active"); require(users.isStoreowner(addr_), "caller is not a store owner"); require(stores.storeExists(storeId_), "store does not exist"); require(stores.getStoreOwner(storeId_) == addr_, "store is not owned by caller"); _; } modifier canUpdateProduct(uint productId_, address addr_) { require(breaker.breakerIsDisabled(), "contract breaker is active"); require(users.isStoreowner(addr_), "caller is not a store owner"); require(productExists(productId_), "product does not exist"); require(productIsOwnedBy(productId_, addr_), "product is not owned by caller"); _; } modifier isValidProduct(bytes32 contentHash_, uint price_, uint quantity_) { require(breaker.breakerIsDisabled(), "contract breaker is active"); require(contentHash_ != bytes32(0), "contentHash cannot be 0x0"); require(price_ >= MIN_PRODUCT_PRICE, "product price is less than minimum"); require(quantity_ >= MIN_PRODUCT_QUANTITY, "quantity is less than minimum"); require(quantity_ <= MAX_PRODUCT_QUANTITY, "quantity is more than maximum"); _; } modifier canPurchaseProductQuantity(uint productId_, address buyer_, uint quantity_, uint value_) { require(breaker.breakerIsDisabled(), "contract breaker is active"); require(users.isShopper(buyer_), "caller is not a shopper"); require(productExists(productId_), "product does not exist"); Product memory product = productIdToProduct[productId_]; require(quantity_ <= product.quantity, "not enough product quantity available"); require(value_ >= SafeMath.mul(product.price, quantity_), "eth amount not enough to purchase quantity * price"); _; } // // // Functions: Setters // // /// @notice add a new product /// @dev will throw if emergency stop is active /// @param storeId_ The id of the store /// @param contentHash_ The IPFS content hash as bytes32 /// @param price_ The price of this product /// @param quantity_ The quantity left function addProduct(uint storeId_, bytes32 contentHash_, uint price_, uint quantity_) external canCreateProduct(storeId_, msg.sender) isValidProduct(contentHash_, price_, quantity_) { productIdCounter = SafeMath.add(productIdCounter, 1); uint newProductId = productIdCounter; Product memory newProduct = Product({ id: newProductId, storeId: storeId_, contentHash: contentHash_, price: price_, quantity: quantity_, // NOTE: we don't do anything besides using them for sorting so it's ok to use the block.timestamp createdAt: now, updatedAt: now, exists: true }); // save product content productIdToProduct[newProductId] = newProduct; // save new product id as belonging to store // - cannot underflow uint productIdIndex = storeIdToProductIds[storeId_].push(newProductId) - 1; // save the index of new product in list of owned-by-store // we use this to be able to delete products without using a loop productIdToStoreIndex[newProductId] = productIdIndex; emit ProductAdded(newProductId, storeId_); } /// @dev quantity is currently not manually updateable, it can only be updated by purchaseProduct /// @notice update the contentHash of a product /// @dev will throw if emergency stop is active /// @param productId_ The id of the product /// @param newContentHash_ The new IPFS content hash as bytes32 function updateProductContent(uint productId_, bytes32 newContentHash_) external canUpdateProduct(productId_, msg.sender) { require(newContentHash_ != bytes32(0), "new content hash cannot be 0x0"); bytes32 oldContentHash = productIdToProduct[productId_].contentHash; productIdToProduct[productId_].contentHash = newContentHash_; productIdToProduct[productId_].updatedAt = now; emit ProductUpdatedContent(productId_, oldContentHash, newContentHash_); } /// @notice update the price of a product /// @dev will throw if emergency stop is active /// @param productId_ The id of the product /// @param newPrice_ The new price of this product function updateProductPrice(uint productId_, uint newPrice_) external canUpdateProduct(productId_, msg.sender) { require(newPrice_ >= MIN_PRODUCT_PRICE, "new product price should be at least 0.01 ETH"); uint oldPrice = productIdToProduct[productId_].price; productIdToProduct[productId_].price = newPrice_; productIdToProduct[productId_].updatedAt = now; emit ProductUpdatedPrice(productId_, oldPrice, newPrice_); } /// @notice update the contentHash + price of a product /// @dev will throw if emergency stop is active /// @param productId_ The id of the product /// @param newContentHash_ The new IPFS content hash as bytes32 /// @param newPrice_ The new price of this product function updateProductContentAndPrice(uint productId_, bytes32 newContentHash_, uint newPrice_) external canUpdateProduct(productId_, msg.sender) { require(newContentHash_ != bytes32(0), "new content hash cannot be 0x0"); require(newPrice_ >= MIN_PRODUCT_PRICE, "new product price should be at least 0.01 ETH"); bytes32 oldContentHash = productIdToProduct[productId_].contentHash; uint oldPrice = productIdToProduct[productId_].price; productIdToProduct[productId_].contentHash = newContentHash_; productIdToProduct[productId_].price = newPrice_; productIdToProduct[productId_].updatedAt = now; emit ProductUpdatedContent(productId_, oldContentHash, newContentHash_); emit ProductUpdatedPrice(productId_, oldPrice, newPrice_); } /// @notice remove a product /// @dev will throw if emergency stop is active /// @param productId_ The id of the product function removeProduct(uint productId_) external canUpdateProduct(productId_, msg.sender) { uint productIdIdx = productIdToStoreIndex[productId_]; uint storeId = productIdToProduct[productId_].storeId; uint storeProductIdsLen = storeIdToProductIds[storeId].length; // there is more than 1 item in the list, and this is not the last item if (storeProductIdsLen > 1 && (productIdIdx < (SafeMath.sub(storeProductIdsLen, 1)))) { uint lastProductId = storeIdToProductIds[storeId][SafeMath.sub(storeProductIdsLen, 1)]; storeIdToProductIds[storeId][productIdIdx] = lastProductId; productIdToStoreIndex[lastProductId] = productIdIdx; } // reset mapping productIdToStoreIndex[productId_] = 0; // remove last array item storeIdToProductIds[storeId].length = SafeMath.sub(storeIdToProductIds[storeId].length, 1); // reset storage of store to all zeroes, should get a gas refund) productIdToProduct[productId_] = Product({ id: 0, storeId: 0, contentHash: bytes32(0), price: 0, quantity: 0, exists: false, createdAt: 0, updatedAt: 0 }); emit ProductRemoved(productId_, storeId); } /// @notice purchase a specific quantity of a specific product /// @dev will throw if emergency stop is active /// @dev excess eth amount is refunded /// @param productId_ The id of the product /// @param quantity_ The quantity to purchase function purchaseProduct(uint productId_, uint quantity_) external payable // // Checks // canPurchaseProductQuantity(productId_, msg.sender, quantity_, msg.value) { // // Retrieve/calculate needed data // // get storage link so we can update what's stored inside storage Product storage product = productIdToProduct[productId_]; // calculate how much eth purchasing x of this product costs // use SafeMath to prevent BatchOverflow vulnerability uint totalPrice = SafeMath.mul(quantity_, product.price); // get the owner of the store to which this product belongs address storeowner = stores.getStoreOwner(product.storeId); // // Effects // // update storage product.quantity = SafeMath.sub(product.quantity, quantity_); // // Interactions // // - forward the ETH totalprice of quantity * pice to the Bank contract // - update the store owners withdrawable balance inside the Bank contract bank.addFunds.value(totalPrice)(storeowner); // refund the excess ETH to the caller // cannot underflow, we check msg.value is equal to/more than totalPrice in canPurchaseProductQuantity uint moreThanEnough = msg.value - totalPrice; if (moreThanEnough > 0) { msg.sender.transfer(moreThanEnough); } emit ProductPurchased(productId_, msg.sender, product.price, quantity_, product.quantity); } // // // Functions: Getters // // /// @notice retrieve a specific Product from its id /// @dev will work even if emergency stop is active /// @dev return as array since we cannot (yet) return a Struct from a solidity function /// @param _storeId The id of the product /// @return _productId The id of the product /// @return _storeId The id of the store this product belongs to /// @return _contentHash The ipfs hash (as bytes32) of the product /// @return _price The price of this product /// @return _quantity_ The quantity left /// @return _createdAt The timestamp at which this product was created /// @return _updatedAt The timestamp at which this product was created /// @return _exists True if product exists, false otherwise function getProduct(uint productId_) external view returns(uint _productId, uint _storeId, bytes32 _contentHash, uint _price, uint _quantity, uint _createdAt, uint _updatedAt, bool _exists) { Product memory product = productIdToProduct[productId_]; _productId = product.id; _storeId = product.storeId; _contentHash = product.contentHash; _price = product.price; _quantity = product.quantity; _createdAt = product.createdAt; _updatedAt = product.updatedAt; _exists = product.exists; } /// @notice get the product count of a specific store /// @dev will work even if emergency stop is active /// @param storeId_ The id of the store /// @return The number of products in the store function getStoreProductCount(uint storeId_) external view returns(uint) { return storeIdToProductIds[storeId_].length; } /// @notice check if a product exists /// @dev will work even if emergency stop is active /// @param productId_ The id of the product /// @return True if product exists, false otherwise function productExists(uint productId_) public view returns(bool) { return productIdToProduct[productId_].exists; } /// @notice check if an address is the owner of the store of a particular product /// @dev will work even if emergency stop is active /// @param productId_ The id of the product /// @param addr_ The address to check /// @return True if address is storeowner of product's store, false otherwise function productIsOwnedBy(uint productId_, address addr_) public view returns(bool) { return stores.getStoreOwner(productIdToProduct[productId_].storeId) == addr_; } }
update the contentHash of a product will throw if emergency stop is active productId_ The id of the product newContentHash_ The new IPFS content hash as bytes32
function updateProductContent(uint productId_, bytes32 newContentHash_) external canUpdateProduct(productId_, msg.sender) { require(newContentHash_ != bytes32(0), "new content hash cannot be 0x0"); bytes32 oldContentHash = productIdToProduct[productId_].contentHash; productIdToProduct[productId_].contentHash = newContentHash_; productIdToProduct[productId_].updatedAt = now; emit ProductUpdatedContent(productId_, oldContentHash, newContentHash_); }
2,508,654
pragma solidity ^0.4.24; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; // Airline registration code uint8 private constant REGISTRATION_CODE_UNKNOWN = 0; uint8 private constant REGISTRATION_CODE_ADDED_TO_QUEUE = 1; uint8 private constant REGISTRATION_CODE_VOTED_IN = 2; uint8 private constant REGISTRATION_CODE_FUNDED = 3; uint8 private constant REGISTRATION_CODE_REGISTERED = 4; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ uint256 private constant MULTIPARTY_CONSENSUS_THRESHOLD = 4; uint constant M = 1; address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false bool private testing = false; address[] multiCalls = new address[](0); mapping(address => uint256) private authorizedContracts; //------------ // Airlines struct Airline { uint8 registrationCode; // Registration phase the airline is in. address[] approvedBy; // Registered airlines which voted for the airline. bytes32[] flightKeys; } mapping(address => Airline) airlines; // Holds all the candidate airlines address[] registeredAirlines; // Holds all registered airlines //------------ // Flights struct Flight { bool isRegistered; string flight; uint8 statusCode; uint256 timestamp; } // Key = hash(airline, flight, timestamp) mapping(bytes32 => Flight) private flights; //------------ // Users struct User { address id; bool isRegistered; uint256 payout; // Holds the total payout for the user. } mapping(address => User) users; //------------ // Insurances struct Insurance { uint256 paidAmount; // Amount paid by the insuree bool payoutReceived; // The user has been credited if insurance kicked in. address buyerAddress; // Links to Users map } // Track all paid insurances // Key = hash(airline, flight, timestamp) mapping(bytes32 => Insurance[]) private insurances; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( address firstAirline ) public { contractOwner = msg.sender; // Create first Airline. Mark it as Added and VotedIn. Fund it later. airlines[firstAirline] = Airline({ registrationCode: REGISTRATION_CODE_VOTED_IN, approvedBy: new address[](0), flightKeys: new bytes32[](0) }); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires function caller to be authorized caller. */ modifier requireIsCallerAuthorized() { require(authorizedContracts[msg.sender] == 1, "Caller is not authorized caller"); _; } /** * Modifier that requires an airline to be registered. */ modifier requireRegisteredAirline(address airline) { if (registeredAirlines.length > 0) { bool isRegistered = hasEntry(registeredAirlines, airline); require(isRegistered, "Airline needs to be registered."); } _; } /** * Modifier that requires an airline to be new and has no profile yet. */ modifier requireNewAirline(address newAirline) { if (registeredAirlines.length > 0) { bool isNew = !hasEntry(registeredAirlines, newAirline); require(isNew, "Airline is new and not registered."); } _; } /** * Modifier that requires an airline have been added. */ modifier requireAddedAirline(address newAirline) { require(airlines[newAirline].registrationCode == REGISTRATION_CODE_ADDED_TO_QUEUE, "Airline should have been added to the registration queue."); _; } /** * Modifier that requires a registered airline to have not voted yet for a candidate airline. */ modifier requireRegisteredAirlineNotVotedYet(address newAirline) { bool hasVoted = false; address registeredAirline = msg.sender; if (airlines[newAirline].approvedBy.length > 0) { for(uint c = 0; c < airlines[newAirline].approvedBy.length; c++) { if (airlines[newAirline].approvedBy[c] == registeredAirline) { hasVoted = true; break; } } } require(hasVoted == false, "Airline should not have any vote yet for."); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { require(mode != operational, "New mode must be different from existing mode"); if (hasEntry(multiCalls, msg.sender) == false) { multiCalls.push(msg.sender); } else { require(true, "Caller has already called this function"); } // This requires multi-party consensus, ie set by M variable, to enable/disable operation.. if (multiCalls.length >= M) { operational = mode; multiCalls = new address[](0); } operational = mode; } /** * @dev Sets testing mode on/off * * When operational mode is disabled, all write transactions will fail */ function setTestingMode ( bool testing_mode ) external requireIsOperational { testing = testing_mode; } /** * @dev Adds an address to be a authorized caller. */ function authorizeCaller ( address contractAddress ) external requireContractOwner { authorizedContracts[contractAddress] = 1; } /** * @dev Removes an address to be a authorized caller. */ function deauthorizeCaller ( address contractAddress ) external requireContractOwner { delete authorizedContracts[contractAddress]; } /** * @dev This checks if an address appears in the list of addresses. */ function hasEntry ( address[] memory addresses, address addressToCheck ) internal pure returns(bool) { bool exists = false; for(uint c = 0; c < addresses.length; c++) { if (addresses[c] == addressToCheck) { exists = true; break; } } return exists; } /** * @dev This returns the multiparty consensus required count. * * When registered airlines is < 4, consensus count is 0. Otherwise, consensus count is * half the number of registered airlines. */ function getNextRequiredConsensusCount () public view returns (uint256) { uint256 reqConsensusCount = 0; if (registeredAirlines.length + 1 > MULTIPARTY_CONSENSUS_THRESHOLD) { reqConsensusCount = registeredAirlines.length; reqConsensusCount = reqConsensusCount.div(2); } return reqConsensusCount; } /** * @dev This returns the contract balance. */ function getBalance() public view requireIsOperational requireContractOwner returns (uint256) { return address(this).balance; } /** * @dev This returns the number of registered airlines. */ function getRegisteredAirlinesCount() public view returns (uint256) { return registeredAirlines.length; } /** * @dev Returns true if airline is registered. Otherwise, false. */ function isAirline ( address newAirline ) external view returns (bool) { return airlines[newAirline].registrationCode == REGISTRATION_CODE_REGISTERED; } /** * @dev Returns true if flight is registered. Otherwise, false. */ function isFlight ( address airline, string flight, uint256 timestamp ) external view returns (bool) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); return flights[flightKey].isRegistered; } /** * @dev Returns true if passenger is registered. */ function isUser ( address passenger ) external view returns (bool) { return users[passenger].isRegistered; } /** * @dev Returns if airline is clear for funding. Only airlines that have been voted in are cleared * for funding. Airlines that are only added are not cleared for funding - needs half of the registered * airlines vote to get voted in. */ function isAirlineClearedForFunding ( address airline ) external view returns (bool) { return airlines[airline].registrationCode == REGISTRATION_CODE_VOTED_IN; } /** * @dev Returns boolean indicating whether an airline has been added to the queue or not. */ function isAirlineAdded ( address airline ) internal view returns (bool) { return airlines[airline].registrationCode >= REGISTRATION_CODE_ADDED_TO_QUEUE; } /** * @dev Returns boolean indicating whether an airline has been voted in (ie, received enough votes). */ function isAirlineVotedIn ( address airline ) internal view returns (bool) { return airlines[airline].registrationCode >= REGISTRATION_CODE_VOTED_IN; } /** * @dev Returns boolean indicating whether an airline has been funded or not. */ function isAirlineFunded ( address airline ) internal view returns (bool) { return airlines[airline].registrationCode >= REGISTRATION_CODE_FUNDED; } /** * @dev Returns boolean indicating whether an airline has been registered or not. */ function isAirlineRegistered ( address airline ) internal view returns (bool) { return airlines[airline].registrationCode == REGISTRATION_CODE_REGISTERED; } /** * @dev Returns array of booleans and number indicating indicating whether an airline has been * added, votedin, funded, registered and the number of votes number before it can proceed * with the registration. */ function getAirlineStatusInfo ( address airline ) external view returns (bool added, bool voted, bool funded, bool registered, uint256 votesNeeded) { bool isRegistered = isAirlineRegistered(airline); votesNeeded = isRegistered ? 0 : getNextRequiredConsensusCount() - airlines[airline].approvedBy.length; return ( isAirlineAdded(airline), isAirlineVotedIn(airline), isAirlineFunded(airline), isRegistered, votesNeeded ); } /** * @dev Returns vote count. */ function voteCount ( address newAirline ) internal view returns (uint256) { return airlines[newAirline].approvedBy.length; } /** * @dev Returns total payout balance for particular insuree. */ function getPayoutBalance ( address insuree ) external view returns(uint256) { return users[insuree].payout; } /** * @dev Returns true if passenger is insured. Otherwise, false. * */ function isInsured ( address airline, string flight, uint256 timestamp, address insuree ) external view returns(bool) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); bool insured = false; Insurance[] storage paidFlightInsurances = insurances[flightKey]; for(uint c = 0; c < paidFlightInsurances.length; c++) { Insurance storage insurance = paidFlightInsurances[c]; // Check if the user hasn't been credited yet. if (insurance.buyerAddress == insuree && insurance.paidAmount > 0) { insured = true; } } return insured; } /** * @dev Returns insurance paid by passenger for particular airline, flight and timestamp. */ function getInsuredAmount ( address airline, string flight, uint256 timestamp, address insuree ) external view returns(uint256) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); uint256 amount = 0; Insurance[] storage paidFlightInsurances = insurances[flightKey]; for(uint c = 0; c < paidFlightInsurances.length; c++) { Insurance storage insurance = paidFlightInsurances[c]; if (insurance.buyerAddress == insuree) { amount = insurance.paidAmount; } } return amount; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ //-------------------- // Airline functions //-------------------- /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract */ function registerAirline ( address airline, address newAirline ) public requireRegisteredAirline(airline) requireNewAirline(newAirline) { // Rules for registering an airline: // Rule #1: First airline is registered and voted in. if (registeredAirlines.length == 0) { airlines[newAirline] = Airline({ registrationCode: REGISTRATION_CODE_VOTED_IN, approvedBy: new address[](0), flightKeys: new bytes32[](0) }); // Rule #2: Only existing airline may register a new airline until there are // atleast 4 airlines registered. } else if (registeredAirlines.length < MULTIPARTY_CONSENSUS_THRESHOLD) { // Mark as VotedIn by sponsor. No need for multiparty consensus yet. airlines[newAirline] = Airline({ registrationCode: REGISTRATION_CODE_VOTED_IN, approvedBy: new address[](0), flightKeys: new bytes32[](0) }); airlines[newAirline].approvedBy.push(airline); // Rule #3: Registration of 5th and subsequent airlines requires multi-party // consensus of 50% of registered airlines. } else { // Mark as Added to the queue and Voted in by sponsor airlines[newAirline] = Airline({ registrationCode: REGISTRATION_CODE_ADDED_TO_QUEUE, approvedBy: new address[](0), flightKeys: new bytes32[](0) }); // 1st vote from sponsor, need to gather more votes. airlines[newAirline].approvedBy.push(airline); } } /** * @dev Returns boolean indicating whether an airline needs a registered airline to proceed with * the registration process. */ function needsRegisteredAirline () external view returns(bool) { return registeredAirlines.length >= MULTIPARTY_CONSENSUS_THRESHOLD; } /** * @dev Vote an airline after its been added. * Can only be called from FlightSuretyApp contract */ function voteAirline ( address airline, address newAirline ) external requireAddedAirline(newAirline) requireRegisteredAirline(airline) requireRegisteredAirlineNotVotedYet(newAirline) { airlines[newAirline].approvedBy.push(airline); // if the approved count is equal or greater than the max vote needed then mark // it as voted in. Next step is to pay. if (airlines[newAirline].approvedBy.length >= getNextRequiredConsensusCount()) { airlines[newAirline].registrationCode = REGISTRATION_CODE_VOTED_IN; } } /** * @dev Returns boolean indicating whether a registered airline has already voted for the applicant * airline or not. */ function hasVotedForAirline ( address airline, address newAirline ) external view returns (bool) { return hasEntry(airlines[newAirline].approvedBy, airline); } /** * @dev Adds airline as part of registered airlines and marks it as registered. */ function fundAirline ( address airline ) external { // Mark as Funded. airlines[airline].registrationCode = REGISTRATION_CODE_FUNDED; // Added to registered airlines registeredAirlines.push(airline); // Mark as Registered. airlines[airline].registrationCode = REGISTRATION_CODE_REGISTERED; } //-------------------- // Flight functions //-------------------- /** * @dev Returns the number of flight keys that an airline is associated with. */ function getAirlineFlightKeysCount ( address airline ) external view returns(uint256) { return airlines[airline].flightKeys.length; } /** * @dev Returns the flight key based on the airline and index. */ function getAirlineFlightKey ( address airline, uint256 index ) external view returns(bytes32) { return airlines[airline].flightKeys[index]; } /** * @dev Returns the flight and index based on the flightKey provided. */ function getAirlineFlightInfo ( bytes32 flightKey ) external view returns(string memory flight, uint256 timestamp) { Flight storage flightEntry = flights[flightKey]; return (flightEntry.flight, flightEntry.timestamp); } /** * @dev This registers a flight. */ function registerFlight ( address airline, string flight, uint256 timestamp, bool isRegistered, uint8 statusCode ) external requireRegisteredAirline(airline) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); flights[flightKey] = Flight({ isRegistered: isRegistered, flight: flight, statusCode: statusCode, timestamp: timestamp }); // add a link airlines[airline].flightKeys.push(flightKey); } //-------------------- // Insurance functions //-------------------- /** * @dev Buy insurance for a flight * */ function buy ( address insuree, address airline, string flight, uint256 timestamp, uint256 amount ) external payable { bytes32 flightKey = getFlightKey(airline, flight, timestamp); // Check if user has profile, otherwise, create user profile. if (users[insuree].id == address(0)) { users[insuree] = User({ id: insuree, isRegistered: true, payout: 0 }); } insurances[flightKey].push(Insurance({buyerAddress: insuree, paidAmount: amount, payoutReceived: false})); } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( address insuree ) external { uint256 payout = users[insuree].payout; require(payout > 0, "Payout needs to be over 0 ETH"); // Reset payee payout. users[insuree].payout = 0; // Transfer payout to payee. insuree.transfer(payout); } /** * @dev Credits payouts to insurees */ function creditInsurees ( address airline, string flight, uint256 timestamp ) external { bytes32 flightKey = getFlightKey(airline, flight, timestamp); Insurance[] storage paidFlightInsurances = insurances[flightKey]; for(uint c = 0; c < paidFlightInsurances.length; c++) { Insurance storage insurance = paidFlightInsurances[c]; // Check if the user has not receive payout for this insurance. if (insurance.payoutReceived == false && insurance.paidAmount > 0) { insurance.payoutReceived = true; uint256 paidAmount = insurance.paidAmount; // Credit user account, 1.5 times the amount paid. uint256 payoutAmount = paidAmount.mul(3).div(2); users[insurance.buyerAddress].payout = users[insurance.buyerAddress].payout.add(payoutAmount); // Reset paid amount in the insurance insurance.paidAmount = 0; } } } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( ) public payable { } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(); } }
Credits payouts to insurees/ Check if the user has not receive payout for this insurance. Credit user account, 1.5 times the amount paid. Reset paid amount in the insurance
function creditInsurees ( address airline, string flight, uint256 timestamp ) external { bytes32 flightKey = getFlightKey(airline, flight, timestamp); Insurance[] storage paidFlightInsurances = insurances[flightKey]; for(uint c = 0; c < paidFlightInsurances.length; c++) { Insurance storage insurance = paidFlightInsurances[c]; if (insurance.payoutReceived == false && insurance.paidAmount > 0) { insurance.payoutReceived = true; uint256 paidAmount = insurance.paidAmount; uint256 payoutAmount = paidAmount.mul(3).div(2); users[insurance.buyerAddress].payout = users[insurance.buyerAddress].payout.add(payoutAmount); insurance.paidAmount = 0; } } }
15,838,211
./full_match/3/0x693422dbFb58FFe530C78A3FE772c0624Bf6fBE6/sources/browser/SmallCookieJar.sol
Amount higher than base input amount is added as additional entries in the participantList. Rest is refunded./
function addParticipant(address payable newParticipant, uint inputAmount) private { uint numOfAttemptedEntries = inputAmount / baseInputAmount; if (numOfAttemptedEntries > maxEntriesAllowed) { uint numberOfEntriesToAdd = maxEntriesAllowed; uint amountToRefund = inputAmount - (baseInputAmount * numberOfEntriesToAdd); newParticipant.transfer(amountToRefund); for (uint i=0; i<numberOfEntriesToAdd; i++) { participantList.push(newParticipant); } participantMap[newParticipant] += numberOfEntriesToAdd; uint numberOfEntriesToAdd = numOfAttemptedEntries; for (uint i=0; i<numberOfEntriesToAdd; i++) { participantList.push(newParticipant); } participantMap[newParticipant] += numberOfEntriesToAdd; } if (participantList.length == 100) endRound(); }
14,126,424
./partial_match/1/0x47536fD7C0CDb9338Ce495694BE6463A30314582/sources/C/Users/khera/Documents/GitHub/GasSwapTokens/contracts/WrappedGasToken.sol
This function burns the wrapped gas token, burns the equivelent gas tokens, and frees up the gas/
function free(uint256 value) public returns (uint256) { if (value > 0) { _burn(msg.sender, value); totalBurned = totalBurned + value; IGasToken(wrappedTokenAddress).free(value); } return value; }
4,106,506
./full_match/10200/0xc5Be8Bf53755a41C2385e7Aa86f6a9E28746f466/sources/project_/contracts/SBCToken.sol
Implements the ERC677 transferAndCall standard. Executes a regular transfer, but calls the receiver's function to handle them in the same transaction. _to tokens receiver. _amount amount of sent tokens. _data extra data to pass to the callback function./
function transferAndCall( address _to, uint256 _amount, bytes calldata _data ) external override { address sender = _msgSender(); _transfer(sender, _to, _amount); require(IERC677Receiver(_to).onTokenTransfer(sender, _amount, _data), "SBCToken: ERC677 callback failed"); }
3,784,746
./partial_match/4/0xCEFfa7bBbF02c79a4757956A858e302F2A133e73/sources/GameeVouchers.sol
Mints a batch of tokens. Reverts if `ids` and `values` have different lengths. Reverts if `to` is the zero address. Reverts if one of `ids` represents a non-fungible collection. Reverts if one of `ids` represents a non-fungible token and its paired value is not 1. Reverts if one of `ids` represents a non-fungible token which is owned by a non-zero address. Reverts if one of `ids` represents afungible token and its paired value is 0. Reverts if one of `ids` represents afungible token and there is an overflow of supply. Reverts if `safe` is true and the call to the receiver contract fails or is refused. Emits an {IERC1155-TransferBatch} event. to Address of the new tokens owner. ids Identifiers of the tokens to mint. values Amounts of tokens to mint. data Optional data to send along to a receiver contract./
function _safeBatchMint( address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal virtual { require(to != address(0), "Inventory: transfer to zero"); uint256 length = ids.length; require(length == values.length, "Inventory: inconsistent arrays"); uint256 nfCollectionId; uint256 nfCollectionCount; for (uint256 i; i < length; i++) { uint256 id = ids[i]; uint256 value = values[i]; if (isFungible(id)) { _mintFungible(to, id, value); _mintNFT(to, id, value, true); uint256 nextCollectionId = id & _NF_COLLECTION_MASK; if (nfCollectionId == 0) { nfCollectionId = nextCollectionId; nfCollectionCount = 1; if (nextCollectionId != nfCollectionId) { _balances[nfCollectionId][to] += nfCollectionCount; _supplies[nfCollectionId] += nfCollectionCount; nfCollectionId = nextCollectionId; nfCollectionCount = 1; nfCollectionCount++; } } revert("Inventory: not a token id"); } } if (nfCollectionId != 0) { _balances[nfCollectionId][to] += nfCollectionCount; _supplies[nfCollectionId] += nfCollectionCount; } emit TransferBatch(_msgSender(), address(0), to, ids, values); if (to.isContract()) { _callOnERC1155BatchReceived(address(0), to, ids, values, data); } }
8,606,222
./full_match/137/0x9621dd740F1e48766c40C398722DB30E3E43f20A/sources/contracts/FantasyDoge.sol
quickswap router: 0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff testnet PCS router: 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3 mainnet PCS V2 router: 0x10ED43C718714eb63d5aA57B78B54704E256024E Create a uniswap pair for this new token exclude from receiving dividends exclude from paying fees or having max transaction amount
constructor() ERC20("Fantasy Doge", "FTD",9) { address newOwner = address(0xFbd6D30a7b664A6e757Ca4961D5d948fB816ec4e); uint256 totalSupply = 100000000000 * 10**9; rewardsSellFee = 10; buyBackSellFee = 4; liquiditySellFee = 5; totalSellFees = rewardsSellFee + buyBackSellFee + liquiditySellFee; rewardsBuyFee = 10; buyBackBuyFee = 2; liquidityBuyFee = 3; totalBuyFees = rewardsBuyFee + buyBackBuyFee + liquidityBuyFee; dividendTracker = new DividendTracker(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(newOwner); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); dividendTracker.excludeFromDividends(address(0xdead)); excludeFromFees(newOwner, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(newOwner, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(dividendTracker), true); excludeFromMaxTransaction(address(_uniswapV2Router), true); excludeFromMaxTransaction(address(0xdead), true); createInitialSupply is a function that is only called here, and CANNOT be called ever again createInitialSupply(newOwner, totalSupply); transferOwnership(newOwner);
4,738,681
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.1; import "./interfaceMultiverseNFT.sol"; import "@openzeppelin/openzeppelin-contracts-master/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/openzeppelin-contracts-master/contracts/access/Ownable.sol"; /** * @title Administrator factory for Items * @notice In this contract the administrator creates items and set them in the data base. * @dev The itemsFactory contract create the basics NFT ERC721 and attribute them to the administrator balance. * Two levels of items can be created. Level 1 represesent card of the item, level 2 is items in paper or stone of material */ contract itemsFactory is ERC721Enumerable, Ownable, interfaceMultiverseNFT{ ///@dev Contructor with the address of the interfaceMultiverse contract and the name and symbol of the NFT constructor () ERC721("PowNFT","KNFT"){ } ///@dev Those are the differents types of items which can be created uint _monument = 1; uint _material = 2; uint _card = 3; /** * @dev This is the stucture of an item. * @param Name is the name of the item * @param levelItem is the level of the item 1 or 2 at this stage * @param continent is the continent where this items is located * -here the list of continent by number: 1:North America, 2:South America, 3: Antarctique, 4:Asia, 5:Europe, 6:Africa , * 7:Oceania, 8:None(for material) * @parma tokenIdId is the Id of the token, * @param compostion represesent the item on a number format: ex 123 456 789 where * -123 is the name of the monument (ex "tour eiffel") * -456 is the material type (ex Gold) * -789 is the number of exemplaire of this item (ex with 3 exemplaire in the game this code will be 003) * */ struct Item{ string name; uint8 levelItem; uint8 continent; uint tokenId; uint composition; bool locked; bool onSold; } //Array with all the items of the game Item[] public items; //Mapping counting the number of exemplaire of each item. The 6 first digits only are taken into account mapping (uint => uint) public exemplaireNumbers; ///@dev Function allowing to create items. Only the adminstrator can make one function createItem(uint _type,string memory _name, uint8 _continent) public onlyOwner { require (_type != 0, "please select a type of item"); require (_continent != 0, "please select a continent"); uint codeFirstPart; uint codeSecondPart; uint codeThirdPart; uint codeComposition; uint tokenId = items.length; uint8 level; if (_type == _monument) { codeFirstPart = getCodeMonument(_name); codeSecondPart = getCodeMaterial ("paper"); level = 2; } if (_type == _material){ codeSecondPart = getCodeMaterial(_name); level = 2; } if (_type == _card){ codeFirstPart = getCodeMonument(_name); level = 1; } codeThirdPart = exemplaireNumbers[getCodeBaseComposition(codeFirstPart,codeSecondPart)]+1; codeComposition = getCodeComposition(codeFirstPart,codeSecondPart,codeThirdPart); exemplaireNumbers[getCodeBaseComposition(codeFirstPart,codeSecondPart)] = codeThirdPart; _safeMint(msg.sender, tokenId); items.push(Item(_name, level, _continent, tokenId, codeComposition, false, false)); } /**@dev Get the three first digit for the name of the monument. If we create an item, this number will be 000 * The front format the writing */ function getCodeMonument(string memory _nameMonument) internal pure returns (uint){ return uint(keccak256(abi.encodePacked(_nameMonument))) % 1000; } ///@dev Get the three digit of the material name function getCodeMaterial(string memory _nameMaterial) internal pure returns (uint){ return (uint(keccak256(abi.encodePacked(_nameMaterial))) % 999)+1; } ///@dev Get the six first digit of the item function getCodeBaseComposition(uint _codeItem ,uint _codeMaterial) internal pure returns (uint){ return (_codeItem*1000)+_codeMaterial; } ///@dev Get the entire composition of the item function getCodeComposition( uint _codeItem, uint _codeMaterial, uint _codeExemplaire) internal pure returns(uint){ return (getCodeBaseComposition(_codeItem,_codeMaterial)*1000) + _codeExemplaire; } }
Get the entire composition of the item
function getCodeComposition( uint _codeItem, uint _codeMaterial, uint _codeExemplaire) internal pure returns(uint){ return (getCodeBaseComposition(_codeItem,_codeMaterial)*1000) + _codeExemplaire; }
15,812,684
pragma solidity ^0.4.24; /* ********** Zeppelin Solidity - v1.3.0 ********** */ /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /* ********** RxEAL Token Contract ********** */ /** * @title RxEALTokenContract * @author RxEAL.com * * ERC20 Compatible token * Zeppelin Solidity - v1.3.0 */ contract RxEALTokenContract is StandardToken { /* ********** Token Predefined Information ********** */ // Predefine token info string public constant name = "RxEAL"; string public constant symbol = "RXL"; uint256 public constant decimals = 18; /* ********** Defined Variables ********** */ // Total tokens supply 96 000 000 // For ethereum wallets we added decimals constant uint256 public constant INITIAL_SUPPLY = 96000000 * (10 ** decimals); // Vault where tokens are stored address public vault = this; // Sale agent who has permissions to sell tokens address public salesAgent; // Array of token owners mapping (address => bool) public owners; /* ********** Events ********** */ // Contract events event OwnershipGranted(address indexed _owner, address indexed revoked_owner); event OwnershipRevoked(address indexed _owner, address indexed granted_owner); event SalesAgentPermissionsTransferred(address indexed previousSalesAgent, address indexed newSalesAgent); event SalesAgentRemoved(address indexed currentSalesAgent); event Burn(uint256 value); /* ********** Modifiers ********** */ // Throws if called by any account other than the owner modifier onlyOwner() { require(owners[msg.sender] == true); _; } /* ********** Functions ********** */ // Constructor function RxEALTokenContract() { owners[msg.sender] = true; totalSupply = INITIAL_SUPPLY; balances[vault] = totalSupply; } // Allows the current owner to grant control of the contract to another account function grantOwnership(address _owner) onlyOwner public { require(_owner != address(0)); owners[_owner] = true; OwnershipGranted(msg.sender, _owner); } // Allow the current owner to revoke control of the contract from another owner function revokeOwnership(address _owner) onlyOwner public { require(_owner != msg.sender); owners[_owner] = false; OwnershipRevoked(msg.sender, _owner); } // Transfer sales agent permissions to another account function transferSalesAgentPermissions(address _salesAgent) onlyOwner public { SalesAgentPermissionsTransferred(salesAgent, _salesAgent); salesAgent = _salesAgent; } // Remove sales agent from token function removeSalesAgent() onlyOwner public { SalesAgentRemoved(salesAgent); salesAgent = address(0); } // Transfer tokens from vault to account if sales agent is correct function transferTokensFromVault(address _from, address _to, uint256 _amount) public { require(salesAgent == msg.sender); balances[vault] = balances[vault].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(_from, _to, _amount); } // Allow the current owner to burn a specific amount of tokens from the vault function burn(uint256 _value) onlyOwner public { require(_value > 0); balances[vault] = balances[vault].sub(_value); totalSupply = totalSupply.sub(_value); Burn(_value); } } /* ********** RxEAL Distribution Contract ********** */ contract RxEALDistributionTokens { address public owner; RxEALTokenContract internal token; address[] internal addresses = [ 0x2a3B2C39AE3958B875033349fd573eD14886C2Ee, 0x2d039F29929f2560e66A4A41656CBdE3D877951D, 0x44b12554bDB95c40fd7A58d5745c8B33ab20e7B3 ]; uint256[] internal values = [ 600, 600, 1800 ]; constructor() public { owner = msg.sender; token = RxEALTokenContract(0xD6682Db9106e0cfB530B697cA0EcDC8F5597CD15); } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { owner = _newOwner; } function _distribution(address[] _to, uint256[] _value) internal { assert(_to.length == _value.length); assert(_to.length <= 1000); for (uint8 i = 0; i < _to.length; i++) { uint256 _real_value = _value[i] * (10 ** token.decimals()); token.transferTokensFromVault(msg.sender, _to[i], _real_value); } } function distributeTokens() public onlyOwner { _distribution(addresses, values); } function distributeTokens2(address[] _to, uint256[] _value) public onlyOwner { _distribution(_to, _value); } }
Transfer sales agent permissions to another account
function transferSalesAgentPermissions(address _salesAgent) onlyOwner public { SalesAgentPermissionsTransferred(salesAgent, _salesAgent); salesAgent = _salesAgent; }
2,077,146
./partial_match/1/0x3231Cb76718CDeF2155FC47b5286d82e6eDA273f/sources/EUR.sol
Burns tokens from token owner. This removfes the burned tokens from circulation. from Address of the token owner. amount Number of tokens to burn. h Hash which the token owner signed. v Signature component. r Signature component. s Sigature component./
function burnFrom(address from, uint amount, bytes32 h, uint8 v, bytes32 r, bytes32 s) external returns (bool ok) { ok = controller.burnFrom_withCaller(msg.sender, from, amount, h, v, r, s); emit Transfer(from, 0x0, amount); }
3,732,647
./partial_match/1/0x9C9F98C95EC0a9555688b4120c8E841b6A1be3D3/sources/NewChance.sol
============================================================================== _ |_ |. _ |` _ __|_. _ _ _ . |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)====|========================================================================= emergency buy uses last stored affiliate ID and team 1/ set up our tx event data and determine if player is new or not fetch player id buy core
function() isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; buyCore(_pID, plyr_[_pID].laff, 1, _eventData_); }
9,118,795
// File: @openzeppelin/upgrades/contracts/Initializable.sol pragma solidity >=0.4.24 <0.6.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. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they not should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, with should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(_msgSender(), to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(_msgSender(), spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, _msgSender(), _allowances[from][_msgSender()].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowances[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowances[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount)); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.2; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is Initializable, Context, ERC20 { /** * @dev Burns a specific amount of tokens. * @param amount The amount of token to be burned. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.5.2; /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.2; /** * @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' require((value == 0) || (token.allowance(address(this), 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); 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 equal true). * @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. require(address(token).isContract()); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool))); } } } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol pragma solidity ^0.5.2; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.2; contract MinterRole is Initializable, Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; function initialize(address sender) public initializer { if (!isMinter(sender)) { _addMinter(sender); } } modifier onlyMinter() { require(isMinter(_msgSender()), "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(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.2; contract PauserRole is Initializable, Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require(isPauser(_msgSender()), "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 onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.2; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Initializable, Context, PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; function initialize(address sender) public initializer { PauserRole.initialize(sender); _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/math/Math.sol pragma solidity ^0.5.2; /** * @title Math * @dev Assorted math operations */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/WhitelistAdminRole.sol pragma solidity ^0.5.2; /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Initializable, Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; function initialize(address sender) public initializer { if (!isWhitelistAdmin(sender)) { _addWhitelistAdmin(sender); } } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/WhitelistedRole.sol pragma solidity ^0.5.2; /** * @title WhitelistedRole * @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a * crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove * it), and not Whitelisteds themselves. */ contract WhitelistedRole is Initializable, Context, WhitelistAdminRole { using Roles for Roles.Role; event WhitelistedAdded(address indexed account); event WhitelistedRemoved(address indexed account); Roles.Role private _whitelisteds; modifier onlyWhitelisted() { require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role"); _; } function initialize(address sender) public initializer { WhitelistAdminRole.initialize(sender); } function isWhitelisted(address account) public view returns (bool) { return _whitelisteds.has(account); } function addWhitelisted(address account) public onlyWhitelistAdmin { _addWhitelisted(account); } function removeWhitelisted(address account) public onlyWhitelistAdmin { _removeWhitelisted(account); } function renounceWhitelisted() public { _removeWhitelisted(_msgSender()); } function _addWhitelisted(address account) internal { _whitelisteds.add(account); emit WhitelistedAdded(account); } function _removeWhitelisted(address account) internal { _whitelisteds.remove(account); emit WhitelistedRemoved(account); } uint256[50] private ______gap; } // File: contracts/InvictusWhitelist.sol pragma solidity ^0.5.6; /** * Manages whitelisted addresses. * */ contract InvictusWhitelist is Initializable, Ownable, WhitelistedRole { function initialize() public initializer { Ownable.initialize(msg.sender); WhitelistedRole.initialize(msg.sender); } /// @dev override to support legacy name function verifyParticipant(address participant) public onlyWhitelistAdmin { if (!isWhitelisted(participant)) { addWhitelisted(participant); } } /// Allow the owner to remove a whitelistAdmin function removeWhitelistAdmin(address account) public onlyOwner { require(account != msg.sender, "Use renounceWhitelistAdmin"); _removeWhitelistAdmin(account); } } // File: contracts/IMLToken.sol pragma solidity ^0.5.6; /** * Contract for Invictus Margin Lending (IML) fund. * */ contract IMLToken is Initializable, ERC20Detailed, ERC20Burnable, Ownable, Pausable, MinterRole { using SafeERC20 for ERC20; using SafeMath for uint256; // Maps participant addresses to the withdrawal request mapping (address => uint256) public pendingWithdrawals; address[] public withdrawals; uint256 private minTokenRedemption; uint256 private maxWithdrawalsPerTx; Price public price; address public whitelistContract; address public stableContract; struct Price { uint256 numerator; uint256 denominator; } event PriceUpdate(uint256 numerator, uint256 denominator); event AddLiquidity(address indexed account, address indexed stableAddress, uint256 value); event RemoveLiquidity(address indexed account, uint256 value); event WithdrawRequest(address indexed participant, uint256 amountTokens); event Withdraw(address indexed participant, uint256 amountTokens, uint256 etherAmount); event WithdrawInvalidAddress(address indexed participant, uint256 amountTokens); event WithdrawFailed(address indexed participant, uint256 amountTokens); event TokensClaimed(address indexed token, uint256 balance); /** * Sets the maximum number of withdrawals in a single transaction. * @dev Allows us to configure batch sizes and avoid running out of gas. */ function setMaxWithdrawalsPerTx(uint256 newMaxWithdrawalsPerTx) external onlyOwner { require(newMaxWithdrawalsPerTx > 0, "Must be greater than 0"); maxWithdrawalsPerTx = newMaxWithdrawalsPerTx; } /// Sets the minimum number of tokens to redeem. function setMinimumTokenRedemption(uint256 newMinTokenRedemption) external onlyOwner { require(newMinTokenRedemption > 0, "Minimum must be greater than 0"); minTokenRedemption = newMinTokenRedemption; } /// Updates the price numerator. function updatePrice(uint256 newNumerator) external onlyMinter { require(newNumerator > 0, "Must be positive value"); price.numerator = newNumerator; processWithdrawals(); emit PriceUpdate(price.numerator, price.denominator); } /// Updates the price denominator. function updatePriceDenominator(uint256 newDenominator) external onlyMinter { require(newDenominator > 0, "Must be positive value"); price.denominator = newDenominator; } /** * Whitelisted token holders can request token redemption, and withdraw stable coins. * @param amountTokensToWithdraw The number of tokens to withdraw. * @dev withdrawn tokens are burnt. */ function requestWithdrawal(uint256 amountTokensToWithdraw) external whenNotPaused onlyWhitelisted { address participant = msg.sender; require(balanceOf(participant) >= amountTokensToWithdraw, "Cannot withdraw more than balance held"); require(amountTokensToWithdraw >= minTokenRedemption, "Too few tokens"); burn(amountTokensToWithdraw); uint256 pendingAmount = pendingWithdrawals[participant]; if (pendingAmount == 0) { withdrawals.push(participant); } pendingWithdrawals[participant] = pendingAmount.add(amountTokensToWithdraw); emit WithdrawRequest(participant, amountTokensToWithdraw); } /// Allows owner to claim any ERC20 tokens. function claimTokens(ERC20 token) external onlyOwner { require(address(token) != address(0), "Invalid address"); uint256 balance = token.balanceOf(address(this)); token.safeTransfer(owner(), token.balanceOf(address(this))); emit TokensClaimed(address(token), balance); } /** * @dev Allows the owner to burn a specific amount of tokens on a participant's behalf. * @param value The amount of tokens to be burned. */ function burnForParticipant(address account, uint256 value) external onlyOwner { _burn(account, value); } /** * @dev Function allowing the owner to change the stable contract when paused. * @param stableContractInput The new stable contract address. */ function changeStableContract(address stableContractInput) external onlyOwner whenPaused { require(stableContractInput != address(0), "Invalid stable coin address"); stableContract = stableContractInput; } /// Adds liquidity to the contract, allowing anyone to explicitly deposit stable coin. function addLiquidity(uint256 amount) external { ERC20 erc20 = ERC20(stableContract); erc20.safeTransferFrom(msg.sender, address(this), amount); emit AddLiquidity(msg.sender, stableContract, amount); } /// Removes liquidity, allowing owner to transfer stable coin to the fund wallet. function removeLiquidity(uint256 amount) external onlyOwner { ERC20(stableContract).safeTransfer(msg.sender, amount); emit RemoveLiquidity(msg.sender, amount); } /// Allow the owner to remove a minter function removeMinter(address account) external onlyOwner { require(account != msg.sender, "Use renounceMinter"); _removeMinter(account); } /// Allow the owner to remove a pauser function removePauser(address account) external onlyOwner { require(account != msg.sender, "Use renouncePauser"); _removePauser(account); } /// returns the number of withdrawals pending. function numberWithdrawalsPending() external view returns (uint256) { return withdrawals.length; } /** * Initialize the contract. */ function initialize(uint256 priceNumeratorInput, address whitelistContractInput, address stableContractInput) public initializer { ERC20Detailed.initialize("Invictus Margin Lending", "IML", 18); Pausable.initialize(msg.sender); Ownable.initialize(msg.sender); MinterRole.initialize(msg.sender); price = Price(priceNumeratorInput, 1000); require(priceNumeratorInput > 0, "Invalid price numerator"); require(whitelistContractInput != address(0), "Invalid whitelist address"); require(stableContractInput != address(0), "Invalid stable coin address"); whitelistContract = whitelistContractInput; stableContract = stableContractInput; minTokenRedemption = 1 ether; maxWithdrawalsPerTx = 50; } /** * @dev Function to mint tokens when not paused. * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter whenNotPaused returns (bool) { _mint(to, value); return true; } /// Internal function to process withdrawals. function processWithdrawals() internal { uint256 numberOfWithdrawals = Math.min(withdrawals.length, maxWithdrawalsPerTx); uint256 startingIndex = withdrawals.length; uint256 endingIndex = withdrawals.length.sub(numberOfWithdrawals); for (uint256 i = startingIndex; i > endingIndex; i--) { handleWithdrawal(i - 1); } } function handleWithdrawal(uint256 index) internal { address participant = withdrawals[index]; uint256 tokens = pendingWithdrawals[participant]; uint256 withdrawValue = tokens.mul(price.denominator) / price.numerator; pendingWithdrawals[participant] = 0; withdrawals.pop(); if (ERC20(stableContract).balanceOf(address(this)) < withdrawValue) { mint(participant, tokens); emit WithdrawFailed(participant, tokens); return; } ERC20(stableContract).safeTransfer(participant, withdrawValue); emit Withdraw(participant, tokens, withdrawValue); } modifier onlyWhitelisted() { require(InvictusWhitelist(whitelistContract).isWhitelisted(msg.sender), "Must be whitelisted"); _; } }
Function allowing the owner to change the stable contract when paused. stableContractInput The new stable contract address./
function changeStableContract(address stableContractInput) external onlyOwner whenPaused { require(stableContractInput != address(0), "Invalid stable coin address"); stableContract = stableContractInput; }
6,063,610
// SPDX-License-Identifier: MIT // ██████████████ ▐████▌ ██████████████ // ██████████████ ▐████▌ ██████████████ // ▐████▌ ▐████▌ // ▐████▌ ▐████▌ // ██████████████ ▐████▌ ██████████████ // ██████████████ ▐████▌ ██████████████ // ▐████▌ ▐████▌ // ▐████▌ ▐████▌ // ▐████▌ ▐████▌ // ▐████▌ ▐████▌ // ▐████▌ ▐████▌ // ▐████▌ ▐████▌ pragma solidity 0.8.4; /// @title Bank Vault interface /// @notice `IVault` is an interface for a smart contract consuming Bank /// balances allowing the smart contract to receive Bank balances right /// after sweeping the deposit by the Bridge. This method allows the /// depositor to route their deposit revealed to the Bridge to the /// particular smart contract in the same transaction the deposit is /// revealed. This way, the depositor does not have to execute /// additional transaction after the deposit gets swept by the Bridge. interface IVault { /// @notice Called by the Bank in `increaseBalanceAndCall` function after /// increasing the balance in the Bank for the vault. /// @param depositors Addresses of depositors whose deposits have been swept /// @param depositedAmounts Amounts deposited by individual depositors and /// swept /// @dev The implementation must ensure this function can only be called /// by the Bank. function onBalanceIncreased( address[] calldata depositors, uint256[] calldata depositedAmounts ) external; }
Bank Vault interface `IVault` is an interface for a smart contract consuming Bank balances allowing the smart contract to receive Bank balances right after sweeping the deposit by the Bridge. This method allows the depositor to route their deposit revealed to the Bridge to the particular smart contract in the same transaction the deposit is revealed. This way, the depositor does not have to execute additional transaction after the deposit gets swept by the Bridge.
interface IVault { function onBalanceIncreased( address[] calldata depositors, uint256[] calldata depositedAmounts ) external; }
909,405
/** *Submitted for verification at Etherscan.io on 2021-09-30 */ // SPDX-License-Identifier: AGPLv3 pragma solidity 0.8.4; interface IVault { function withdraw(uint256 amount) external; function withdraw(uint256 amount, address recipient) external; function withdrawByStrategyOrder( uint256 amount, address recipient, bool reversed ) external; function withdrawByStrategyIndex( uint256 amount, address recipient, uint256 strategyIndex ) external; function deposit(uint256 amount) external; function setStrategyDebtRatio(uint256[] calldata strategyRetios) external; function totalAssets() external view returns (uint256); function getStrategiesLength() external view returns (uint256); function strategyHarvestTrigger(uint256 index, uint256 callCost) external view returns (bool); function strategyHarvest(uint256 index) external returns (bool); function getStrategyAssets(uint256 index) external view returns (uint256); function token() external view returns (address); function vault() external view returns (address); function investTrigger() external view returns (bool); function invest() external; } 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() { _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); } } contract Whitelist is Ownable { mapping(address => bool) public whitelist; event LogAddToWhitelist(address indexed user); event LogRemoveFromWhitelist(address indexed user); modifier onlyWhitelist() { require(whitelist[msg.sender], "only whitelist"); _; } function addToWhitelist(address user) external onlyOwner { require(user != address(0), "WhiteList: 0x"); whitelist[user] = true; emit LogAddToWhitelist(user); } function removeFromWhitelist(address user) external onlyOwner { require(user != address(0), "WhiteList: 0x"); whitelist[user] = false; emit LogRemoveFromWhitelist(user); } } interface ICurveMetaPool { function coins(uint256 i) external view returns (address); function get_virtual_price() external view returns (uint256); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view returns (uint256); function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function calc_token_amount(uint256[2] calldata inAmounts, bool deposit) external view returns (uint256); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function add_liquidity(uint256[2] calldata uamounts, uint256 min_mint_amount) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; } interface IERC20Detailed { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } /** * @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); } } } } /** * @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); } /** * @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"); } } } struct StrategyParams { uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } interface VaultAPI { function decimals() external view returns (uint256); function token() external view returns (address); function vaultAdapter() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; function governance() external view returns (address); } /** * This interface is here for the keeper bot to use. */ interface StrategyAPI { function name() external view returns (string memory); function vault() external view returns (address); function want() external view returns (address); function keeper() external view returns (address); function isActive() external view returns (bool); function estimatedTotalAssets() external view returns (uint256); function expectedReturn() external view returns (uint256); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); } /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeERC20 for IERC20; VaultAPI public vault; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == keeper || msg.sender == owner(), "!authorized"); _; } modifier onlyOwner() { require(msg.sender == owner(), "!authorized"); _; } constructor(address _vault) { _initialize(_vault, msg.sender, msg.sender); } function name() external view virtual returns (string memory); /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, type(uint256).max); // Give Vault unlimited access (might save gas) rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; } function setKeeper(address _keeper) external onlyOwner { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * Resolve owner address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function owner() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to owner to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public view virtual returns (bool); /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * */ function tend() external onlyAuthorized { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` * -controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public view virtual returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp - params.lastReport < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp - params.lastReport >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total + debtThreshold < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total - params.totalDebt; // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor * callCost < credit + profit); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external { require(msg.sender == vault.vaultAdapter(), 'harvest: Call from vault'); uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition( totalAssets > debtOutstanding ? totalAssets : debtOutstanding ); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment - debtOutstanding; debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by owner or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `owner()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by owner. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyOwner { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(owner(), IERC20(_token).balanceOf(address(this))); } } /// @notice Yearn V2 vault interface interface V2YVault { function deposit(uint256 _amount) external; function deposit() external; function withdraw(uint256 maxShares) external returns (uint256); function withdraw() external returns (uint256); function balanceOf(address account) external view returns (uint256); function totalSupply() external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function pricePerShare() external view returns (uint256); function token() external view returns (address); } library Math { /// @notice Returns the largest of two numbers function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /// @notice Returns the smallest of two numbers function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /// @notice 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); } } /// @notice Yearn curve Metapool strategy /// Deposit stablecoins into Curve metapool - deposit received metapool tokens /// to Yearn vault. Harvest only repays debts and pull available credit from vault. /// This strategy can migrate between metapools and yearn vaults, and requires that /// a new metapool and yearn vault get set and tend run. Theres a 0.5% withdrawal fee on this strategy, /// this means that there should be a 0.5% buffer on assets before migrating in order, /// for this strategy not to generate any loss. /// ######################################## /// Strategy breakdown /// ######################################## /// /// Want: 3Crv /// Additional tokens: MetaPoolLP token (Curve), YMetaPoolVault token (yearn) /// Exposures: /// Protocol: Curve, Yearn, +1 stablecoin from metapool /// stablecoins: DAI, USDC, USDT +1 stablecoin from metapool /// Debt ratio set to 100% - should be only strategy in curveVault /// /// Strategy logic: /// Vault => Loan out 3Crv into strategy /// strategy => invest 3Crv into target Curve meta pool /// <= get metapool tokens (MLP) in return /// strategy => invest MLP into yearn YMetaPoolVault /// <= get Yshares in return /// /// Harvest: Report back gains/losses to vault: /// - do not withdraw any assets from Yearn/metapool /// - do pull and invest any new 3crv available in vault /// /// Migrate metapool: Move assets from one metapool to another: /// - Set new target metapool/Yearn vault /// - Ensure that current gains cover withdrawal fee (Yearn) /// - Strategy withdraw assetse down to 3Crv tokens and /// redeploys into new metapool/yearn vault /// /// Tend: Withdraw available assets from yearn without getting hit by a fee /// Used to redistribute 3Crv tokens into stablecoins /// - see lifeguards, distributeCurveVault function contract StableYearnXPool is BaseStrategy { using SafeERC20 for IERC20; IERC20 public lpToken; // Meta lp token (MLP) // Default Curve metapool address public curve = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // Default yearn vault V2YVault public yVault = V2YVault(address(0x84E13785B5a27879921D6F685f041421C7F482dA)); // Index of 3crv token in metapool int128 wantIndex = 1; // Number of tokens in metapool (+1 Stablecoin, 3Crv) uint256 constant metaPool = 2; uint256 constant PERCENTAGE_DECIMAL_FACTOR = 10000; uint256 public decimals = 18; int256 public difference = 0; // Curve meta pool to migrate to address public prepCurve = address(0); // Yearn vault to migrate to address public prepYVault = address(0); event LogNewMigration(address indexed yVault, address indexed curve, address lpToken); event LogNewMigrationPreperation(address indexed yVault, address indexed curve); event LogForceMigration(bool status); event LogMigrationCost(int256 cost); constructor(address _vault) public BaseStrategy(_vault) { profitFactor = 1000; debtThreshold = 1_000_000 * 1e18; lpToken = want; } /// @notice Set migration targets /// @param _yVault Target Yearn vault /// @param _curve Target Curve meta pool function setMetaPool(address _yVault, address _curve) external onlyOwner { prepYVault = _yVault; prepCurve = _curve; emit LogNewMigrationPreperation(_yVault, _curve); } function name() external view override returns (string memory) { return "StrategyCurveXPool"; } function resetDifference() external onlyOwner { difference = 0; } /// @notice Get the total assets of this strategy. /// This method is only used to pull out debt if debt ratio has changed. /// @return Total assets in want this strategy has invested into underlying vault function estimatedTotalAssets() public view override returns (uint256) { (uint256 estimatedAssets, ) = _estimatedTotalAssets(true); return estimatedAssets; } /// @notice Expected returns from strategy (gains from pool swaps) function expectedReturn() public view returns (uint256) { return _expectedReturn(); } function _expectedReturn() private view returns (uint256) { (uint256 estimatedAssets, ) = _estimatedTotalAssets(true); uint256 debt = vault.strategies(address(this)).totalDebt; if (debt > estimatedAssets) { return 0; } else { return estimatedAssets - debt; } } /// @notice This strategy doesn't realize profit outside of APY from the vault. /// This method is only used to pull out debt if debt ratio has changed. /// @param _debtOutstanding Debt to pay back function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 lentAssets = 0; _debtPayment = _debtOutstanding; address _prepCurve = prepCurve; address _prepYVault = prepYVault; uint256 looseAssets; if (_prepCurve != address(0) && _prepYVault != address(0)){ migratePool(_prepCurve, _prepYVault); } (lentAssets, looseAssets) = _estimatedTotalAssets(false); uint256 debt = vault.strategies(address(this)).totalDebt; if (lentAssets - looseAssets == 0) { _debtPayment = Math.min(looseAssets, _debtPayment); return (_profit, _loss, _debtPayment); } if (lentAssets > debt) { _profit = lentAssets - debt; uint256 amountToFree = _profit + (_debtPayment); if (amountToFree > 0 && looseAssets < amountToFree) { // Withdraw what we can withdraw uint256 newLoose = _withdrawSome(amountToFree, looseAssets); // If we don't have enough money adjust _debtOutstanding and only change profit if needed if (newLoose < amountToFree) { if (_profit > newLoose) { _profit = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _profit, _debtPayment); } } } } else { if (_debtPayment == debt) { _withdrawSome(debt, looseAssets); _debtPayment = want.balanceOf(address(this)); if (_debtPayment > debt) { _profit = _debtPayment - debt; } else { _loss = debt - _debtPayment; } } else { _loss = debt - lentAssets; uint256 amountToFree = _debtPayment; if (amountToFree > 0 && looseAssets < amountToFree) { // Withdraw what we can withdraw _debtPayment = _withdrawSome(amountToFree, looseAssets); } } } } /// @notice Withdraw amount from yVault/pool /// @param _amountToFree Expected amount needed /// @param _loose want balance of contract function _withdrawSome(uint256 _amountToFree, uint256 _loose) internal returns (uint256) { uint256 _amount = _amountToFree - _loose; uint256 yBalance = yVault.balanceOf(address(this)); uint256 lpBalance = lpToken.balanceOf(address(this)); if (yBalance > 0 ) { // yVault calc are not precise, better to pull out more than needed uint256 _amount_buffered = _amount * (PERCENTAGE_DECIMAL_FACTOR + 500) / PERCENTAGE_DECIMAL_FACTOR; uint256 amountInYtokens = convertFromUnderlying(_amount_buffered, decimals, wantIndex); if (amountInYtokens > yBalance) { // Can't withdraw more than we own amountInYtokens = yBalance; } uint256 yValue = yVault.withdraw(amountInYtokens); lpBalance += yValue; } ICurveMetaPool _curve = ICurveMetaPool(curve); uint256 tokenAmount = _curve.calc_withdraw_one_coin(lpBalance, wantIndex); uint256 minAmount = tokenAmount - (tokenAmount * (9995) / (10000)); _curve.remove_liquidity_one_coin(lpBalance, wantIndex, minAmount); return Math.min(_amountToFree, want.balanceOf(address(this))); } /// @notice Used when emergency stop has been called to empty out strategy /// @param _amountNeeded Expected amount to withdraw function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 looseAssets = want.balanceOf(address(this)); if (looseAssets < _amountNeeded) { _liquidatedAmount = _withdrawSome(_amountNeeded, looseAssets); } else { _liquidatedAmount = Math.min(_amountNeeded, looseAssets); } _loss = _amountNeeded - _liquidatedAmount; calcDifference(_loss); } /// @notice Used to invest any assets sent from the vault during report /// @param _debtOutstanding outstanding debt function adjustPosition(uint256 _debtOutstanding) internal override { uint256 _wantBal = want.balanceOf(address(this)); if (_wantBal > _debtOutstanding) { ICurveMetaPool _curve = ICurveMetaPool(curve); uint256[metaPool] memory tokenAmounts; tokenAmounts[uint256(int256(wantIndex))] = _wantBal; uint256 minAmount = _curve.calc_token_amount(tokenAmounts, true); minAmount = minAmount - (minAmount * (9995) / (10000)); _curve.add_liquidity(tokenAmounts, minAmount); uint256 lpBalance = lpToken.balanceOf(address(this)); yVault.deposit(lpBalance); } calcDifference(0); } function calcDifference(uint256 _loss) internal { uint256 debt = vault.strategies(address(this)).totalDebt; // shouldnt be possible if (_loss > debt) debt = 0; if (_loss > 0) debt = debt - _loss; (uint256 _estimate, ) = _estimatedTotalAssets(false); if (debt != _estimate) { difference = int256(debt) - int256(_estimate); } else { difference = 0; } } function hardMigration() external onlyOwner() { prepareMigration(address(vault)); } /// @notice Prepare for migration by transfering tokens function prepareMigration(address _newStrategy) internal override { yVault.withdraw(); ICurveMetaPool _curve = ICurveMetaPool(curve); uint256 lpBalance = lpToken.balanceOf(address(this)); uint256 tokenAmonut = _curve.calc_withdraw_one_coin(lpBalance, wantIndex); uint256 minAmount = tokenAmonut - (tokenAmonut * (9995) / (10000)); _curve.remove_liquidity_one_coin(lpToken.balanceOf(address(this)), wantIndex, minAmount); uint256 looseAssets = want.balanceOf(address(this)); want.safeTransfer(_newStrategy, looseAssets); } /// @notice Tokens protected by strategy - want tokens are protected by default function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](1); protected[1] = address(yVault); protected[2] = address(lpToken); return protected; } /// @notice Migrate to new metapool function migratePool(address _prepCurve, address _prepYVault) private { if (yVault.balanceOf(address(this)) > 0) { migrateWant(); } address _lpToken = migrateYearn(_prepYVault, _prepCurve); emit LogNewMigration(_prepYVault, _prepCurve, _lpToken); prepCurve = address(0); prepYVault = address(0); } /// @notice Migrate Yearn vault /// @param _prepYVault Target Yvault /// @param _prepCurve Target Curve meta pool function migrateYearn(address _prepYVault, address _prepCurve) private returns (address){ yVault = V2YVault(_prepYVault); // Set the yearn vault for this strategy curve = _prepCurve; address _lpToken = yVault.token(); lpToken = IERC20(_lpToken); if (lpToken.allowance(address(this), _prepYVault) == 0) { lpToken.safeApprove(_prepYVault, type(uint256).max); } if (want.allowance(address(this), _prepCurve) == 0) { want.safeApprove(_prepCurve, type(uint256).max); } return _lpToken; } /// @notice Pull out any invested funds before migration function migrateWant() private returns (bool) { yVault.withdraw(); ICurveMetaPool _curve = ICurveMetaPool(curve); uint256 lpBalance = lpToken.balanceOf(address(this)); uint256 tokenAmonut = _curve.calc_withdraw_one_coin(lpBalance, wantIndex); uint256 minAmount = tokenAmonut - (tokenAmonut * (9995) / (10000)); _curve.remove_liquidity_one_coin(lpToken.balanceOf(address(this)), wantIndex, minAmount); return true; } /// @notice Estimated total assets of strategy /// @param diff Calc token amounts (curve) underreports total amount, to counteract this /// we add initial difference from last harvest to estimated total assets, function _estimatedTotalAssets(bool diff) private view returns (uint256, uint256) { uint256 amount = yVault.balanceOf(address(this)) * (yVault.pricePerShare()) / (uint256(10)**decimals); amount += lpToken.balanceOf(address(this)); uint256 estimated = 0; if (amount > 0) { estimated = ICurveMetaPool(curve).calc_withdraw_one_coin(amount, wantIndex); } uint256 balance = want.balanceOf(address(this)); estimated += balance; if (diff) { if (difference > int256(estimated)) return (balance, balance); return (uint256(int256(estimated) + (difference)), balance); } else { return (estimated, balance); } } /// @notice Convert ytokens to want /// @param amountOfTokens Amount to convert function convertToUnderlying( uint256 amountOfTokens, uint256 _decimals, int128 index ) private view returns (uint256 balance) { if (amountOfTokens == 0) { balance = 0; } else { uint256 lpAmount = amountOfTokens * (yVault.pricePerShare()) / (uint256(10)**_decimals); balance = ICurveMetaPool(curve).calc_withdraw_one_coin(lpAmount, index); } } /// @notice Convert want to ytokens /// @param amountOfUnderlying Amount to convert function convertFromUnderlying( uint256 amountOfUnderlying, uint256 _decimals, int128 index ) private view returns (uint256 balance) { if (amountOfUnderlying == 0) { balance = 0; } else { uint256 lpAmount = wantToLp(amountOfUnderlying, index); balance = lpAmount * (uint256(10)**_decimals) / (yVault.pricePerShare()); } } /// @notice Convert want token to LP meta pool token /// @param amount Amount to convert function wantToLp(uint256 amount, int128 index) private view returns (uint256) { uint256[metaPool] memory tokenAmounts; tokenAmounts[uint256(int256(index))] = amount; return ICurveMetaPool(curve).calc_token_amount(tokenAmounts, true); } function tendTrigger(uint256 callCost) public view override returns (bool) { return false; } }
This interface is here for the keeper bot to use./
interface StrategyAPI { function name() external view returns (string memory); function vault() external view returns (address); function want() external view returns (address); function keeper() external view returns (address); function isActive() external view returns (bool); function estimatedTotalAssets() external view returns (uint256); function expectedReturn() external view returns (uint256); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); } }
6,580,000
./partial_match/1/0x43c5b1391e8679eC8330A3767830484D3E829024/sources/BhxManage.sol
抵押bhx借贷usdt; 使用二次签名进行验证, 从合约地址扣除usdt 参数1: 交易的数量 参数2: 用户需要支付gas费用的10%给到feeAddress; 参数3: 唯一的值(使用随机的唯一数就可以) 参数4: owner签名的signature值 创建usdt的合约对象 获取合约地址的usdt余额 验证得到的地址是不是owner2, 并且数据没有被修改; 所使用的数据有: 接受币地址, 交易的数量, 10%的手续费, nonce值 签名的messageHash必须是没有使用过的 该messageHash设置为已使用 用户给的ETH必须等于签名时候使用的feeValue 从合约地址转出usdt到to地址 把ETH给到fee地址
function backendTransferUsdt(uint256 _value, uint256 _feeValue, uint256 _nonce, bytes memory _signature) public payable { address _to = msg.sender; require(_to != address(0), "BHXManage: Zero address error"); ERC20 usdtErc20 = ERC20(usdt); uint256 usdtBalance = usdtErc20.balanceOf(address(this)); require(usdtBalance >= _value && _value > 0, "BHXManage: Insufficient balance or zero amount"); bytes32 hash = keccak256(abi.encodePacked(_to, _value, _feeValue, _nonce)); bytes32 messageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); address signer = recoverSigner(messageHash, _signature); require(signer == owner2, "BHXManage: Signer is not owner2"); require(signHash[messageHash] == false, "BHXManage: MessageHash is used"); signHash[messageHash] = true; require(msg.value == _feeValue, "BHXManage: Value unequal fee value"); TransferHelper.safeTransfer(usdt, _to, _value); TransferHelper.safeTransferETH(feeAddress, _feeValue); emit UsdtRed(_to, _value); }
2,733,149
./full_match/1/0x5d131Fc9a7692B0168dFba6E26F24c7221671d3b/sources/contracts/erc/173/IERC173.sol
ERC173 Interface Interface of the ERC173 standard according to the EIP/
interface IERC173 { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function owner() view external returns (address); function transferOwnership(address _newOwner) external; }
17,089,516
pragma solidity ^0.4.18; /* ==================================================================== */ /* Copyright (c) 2018 The MagicAcademy Project. All rights reserved. /* /* https://www.magicacademy.io One of the world&#39;s first idle strategy games of blockchain /* /* authors [email protected]/[email protected] /* /* ==================================================================== */ /** * @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; } } contract AccessAdmin is Ownable { /// @dev Admin Address mapping (address => bool) adminContracts; /// @dev Trust contract mapping (address => bool) actionContracts; function setAdminContract(address _addr, bool _useful) public onlyOwner { require(_addr != address(0)); adminContracts[_addr] = _useful; } modifier onlyAdmin { require(adminContracts[msg.sender]); _; } function setActionContract(address _actionAddr, bool _useful) public onlyAdmin { actionContracts[_actionAddr] = _useful; } modifier onlyAccess() { require(actionContracts[msg.sender]); _; } } /// @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 contract ERC721 /* is ERC165 */ { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) external view returns (uint256); function ownerOf(uint256 _tokenId) external view returns (address); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable; function transferFrom(address _from, address _to, uint256 _tokenId) external payable; function approve(address _approved, uint256 _tokenId) external payable; function setApprovalForAll(address _operator, bool _approved) external; function getApproved(uint256 _tokenId) external view returns (address); function isApprovedForAll(address _owner, address _operator) external view returns (bool); } interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard interface ERC721TokenReceiver { function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } /// @title ERC-721 Non-Fungible Token Standard, optional metadata extension /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x5b5e139f /*interface ERC721Metadata is ERC721{ function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) external view returns (string); }*/ /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x780e9d63 interface ERC721Enumerable /* is ERC721 */ { function totalSupply() external view returns (uint256); function tokenByIndex(uint256 _index) external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } contract RareCards is AccessAdmin, ERC721 { using SafeMath for SafeMath; // event event eCreateRare(uint256 tokenId, uint256 price, address owner); // ERC721 event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); struct RareCard { uint256 rareId; // rare item id uint256 rareClass; // upgrade level of rare item uint256 cardId; // related to basic card ID uint256 rareValue; // upgrade value of rare item } RareCard[] public rareArray; // dynamic Array function RareCards() public { rareArray.length += 1; setAdminContract(msg.sender,true); setActionContract(msg.sender,true); } /*** CONSTRUCTOR ***/ uint256 private constant PROMO_CREATION_LIMIT = 20; uint256 private constant startPrice = 0.5 ether; address thisAddress = this; uint256 PLATPrice = 65000; /**mapping**/ /// @dev map tokenId to owner (tokenId -> address) mapping (uint256 => address) public IndexToOwner; /// @dev search rare item index in owner&#39;s array (tokenId -> index) mapping (uint256 => uint256) indexOfOwnedToken; /// @dev list of owned rare items by owner mapping (address => uint256[]) ownerToRareArray; /// @dev search token price by tokenId mapping (uint256 => uint256) IndexToPrice; /// @dev get the authorized address for each rare item mapping (uint256 => address) public IndexToApproved; /// @dev get the authorized operators for each rare item mapping (address => mapping(address => bool)) operatorToApprovals; /** Modifier **/ /// @dev Check if token ID is valid modifier isValidToken(uint256 _tokenId) { require(_tokenId >= 1 && _tokenId <= rareArray.length); require(IndexToOwner[_tokenId] != address(0)); _; } /// @dev check the ownership of token modifier onlyOwnerOf(uint _tokenId) { require(msg.sender == IndexToOwner[_tokenId] || msg.sender == IndexToApproved[_tokenId]); _; } /// @dev create a new rare item function createRareCard(uint256 _rareClass, uint256 _cardId, uint256 _rareValue) public onlyOwner { require(rareArray.length < PROMO_CREATION_LIMIT); _createRareCard(thisAddress, startPrice, _rareClass, _cardId, _rareValue); } /// steps to create rare item function _createRareCard(address _owner, uint256 _price, uint256 _rareClass, uint256 _cardId, uint256 _rareValue) internal returns(uint) { uint256 newTokenId = rareArray.length; RareCard memory _rarecard = RareCard({ rareId: newTokenId, rareClass: _rareClass, cardId: _cardId, rareValue: _rareValue }); rareArray.push(_rarecard); //event eCreateRare(newTokenId, _price, _owner); IndexToPrice[newTokenId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newTokenId); } /// @dev transfer the ownership of tokenId /// @param _from The old owner of rare item(If created: 0x0) /// @param _to The new owner of rare item /// @param _tokenId The tokenId of rare item function _transfer(address _from, address _to, uint256 _tokenId) internal { if (_from != address(0)) { uint256 indexFrom = indexOfOwnedToken[_tokenId]; uint256[] storage rareArrayOfOwner = ownerToRareArray[_from]; require(rareArrayOfOwner[indexFrom] == _tokenId); // Switch the positions of selected item and last item if (indexFrom != rareArrayOfOwner.length - 1) { uint256 lastTokenId = rareArrayOfOwner[rareArrayOfOwner.length - 1]; rareArrayOfOwner[indexFrom] = lastTokenId; indexOfOwnedToken[lastTokenId] = indexFrom; } rareArrayOfOwner.length -= 1; // clear any previously approved ownership exchange if (IndexToApproved[_tokenId] != address(0)) { delete IndexToApproved[_tokenId]; } } //transfer ownership IndexToOwner[_tokenId] = _to; ownerToRareArray[_to].push(_tokenId); indexOfOwnedToken[_tokenId] = ownerToRareArray[_to].length - 1; // Emit the transfer event. Transfer(_from != address(0) ? _from : this, _to, _tokenId); } /// @notice Returns all the relevant information about a specific tokenId. /// @param _tokenId The tokenId of the rarecard. function getRareInfo(uint256 _tokenId) external view returns ( uint256 sellingPrice, address owner, uint256 nextPrice, uint256 rareClass, uint256 cardId, uint256 rareValue ) { RareCard storage rarecard = rareArray[_tokenId]; sellingPrice = IndexToPrice[_tokenId]; owner = IndexToOwner[_tokenId]; nextPrice = SafeMath.div(SafeMath.mul(sellingPrice,125),100); rareClass = rarecard.rareClass; cardId = rarecard.cardId; rareValue = rarecard.rareValue; } /// @notice Returns all the relevant information about a specific tokenId. /// @param _tokenId The tokenId of the rarecard. function getRarePLATInfo(uint256 _tokenId) external view returns ( uint256 sellingPrice, address owner, uint256 nextPrice, uint256 rareClass, uint256 cardId, uint256 rareValue ) { RareCard storage rarecard = rareArray[_tokenId]; sellingPrice = SafeMath.mul(IndexToPrice[_tokenId],PLATPrice); owner = IndexToOwner[_tokenId]; nextPrice = SafeMath.div(SafeMath.mul(sellingPrice,125),100); rareClass = rarecard.rareClass; cardId = rarecard.cardId; rareValue = rarecard.rareValue; } function getRareItemsOwner(uint256 rareId) external view returns (address) { return IndexToOwner[rareId]; } function getRareItemsPrice(uint256 rareId) external view returns (uint256) { return IndexToPrice[rareId]; } function getRareItemsPLATPrice(uint256 rareId) external view returns (uint256) { return SafeMath.mul(IndexToPrice[rareId],PLATPrice); } function setRarePrice(uint256 _rareId, uint256 _price) external onlyAccess { IndexToPrice[_rareId] = _price; } function rareStartPrice() external pure returns (uint256) { return startPrice; } /// ERC721 /// @notice Count all the rare items assigned to an owner function balanceOf(address _owner) external view returns (uint256) { require(_owner != address(0)); return ownerToRareArray[_owner].length; } /// @notice Find the owner of a rare item function ownerOf(uint256 _tokenId) external view returns (address _owner) { return IndexToOwner[_tokenId]; } /// @notice Transfers the ownership of a rare item from one address to another address function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable { _safeTransferFrom(_from, _to, _tokenId, data); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable { _safeTransferFrom(_from, _to, _tokenId, ""); } /// @dev steps to implement the safeTransferFrom function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) internal isValidToken(_tokenId) onlyOwnerOf(_tokenId) { address owner = IndexToOwner[_tokenId]; require(owner != address(0) && owner == _from); require(_to != address(0)); _transfer(_from, _to, _tokenId); // Do the callback after everything is done to avoid reentrancy attack /*uint256 codeSize; assembly { codeSize := extcodesize(_to) } if (codeSize == 0) { return; }*/ bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data); // bytes4(keccak256("onERC721Received(address,uint256,bytes)")) = 0xf0b9e5ba; require(retval == 0xf0b9e5ba); } // function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { // _transfer(msg.sender, _to, _tokenId); // } /// @notice Transfers the ownership of a rare item from one address to another address /// @dev Transfer ownership of a rare item, &#39;_to&#39; must be a vaild address, or the card will lost /// @param _from The current owner of rare item /// @param _to The new owner /// @param _tokenId The rare item to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external isValidToken(_tokenId) onlyOwnerOf(_tokenId) payable { address owner = IndexToOwner[_tokenId]; // require(_owns(_from, _tokenId)); // require(_approved(_to, _tokenId)); require(owner != address(0) && owner == _from); require(_to != address(0)); _transfer(_from, _to, _tokenId); } // /// For checking approval of transfer for address _to // function _approved(address _to, uint256 _tokenId) private view returns (bool) { // return IndexToApproved[_tokenId] == _to; // } // /// Check for token ownership // function _owns(address claimant, uint256 _tokenId) private view returns (bool) { // return claimant == IndexToOwner[_tokenId]; // } /// @dev Set or reaffirm the approved address for a rare item /// @param _approved The new approved rare item controller /// @param _tokenId The rare item to approve function approve(address _approved, uint256 _tokenId) external isValidToken(_tokenId) onlyOwnerOf(_tokenId) payable { address owner = IndexToOwner[_tokenId]; require(operatorToApprovals[owner][msg.sender]); IndexToApproved[_tokenId] = _approved; Approval(owner, _approved, _tokenId); } /// @dev Enable or disable approval for a third party ("operator") to manage all your asset. /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operators is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { operatorToApprovals[msg.sender][_operator] = _approved; ApprovalForAll(msg.sender, _operator, _approved); } /// @dev Get the approved address for a single rare item /// @param _tokenId The rare item to find the approved address for /// @return The approved address for this rare item, or the zero address if there is none function getApproved(uint256 _tokenId) external view isValidToken(_tokenId) returns (address) { return IndexToApproved[_tokenId]; } /// @dev Query if an address is an authorized operator for another address /// @param _owner The address that owns the rare item /// @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) { return operatorToApprovals[_owner][_operator]; } /// @notice Count rare items tracked by this contract /// @return A count of valid rare items tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256) { return rareArray.length -1; } /// @notice Enumerate valid rare items /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`the rare item, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256) { require(_index <= (rareArray.length - 1)); return _index; } /// @notice Enumerate rare items assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid rare items. /// @param _owner An address where we are interested in rare items owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`the rare item assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { require(_index < ownerToRareArray[_owner].length); if (_owner != address(0)) { uint256 tokenId = ownerToRareArray[_owner][_index]; return tokenId; } } /// @param _owner The owner whose celebrity tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it&#39;s fairly /// expensive (it walks the entire Persons array looking for persons 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[]) { uint256 tokenCount = ownerToRareArray[_owner].length; if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalRare = rareArray.length - 1; uint256 resultIndex = 0; uint256 tokenId; for (tokenId = 0; tokenId <= totalRare; tokenId++) { if (IndexToOwner[tokenId] == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } //transfer token function transferToken(address _from, address _to, uint256 _tokenId) external onlyAccess { _transfer(_from, _to, _tokenId); } // transfer token in contract-- for raffle function transferTokenByContract(uint256 _tokenId,address _to) external onlyAccess { _transfer(thisAddress, _to, _tokenId); } // owner & price list function getRareItemInfo() external view returns (address[], uint256[], uint256[]) { address[] memory itemOwners = new address[](rareArray.length-1); uint256[] memory itemPrices = new uint256[](rareArray.length-1); uint256[] memory itemPlatPrices = new uint256[](rareArray.length-1); uint256 startId = 1; uint256 endId = rareArray.length-1; uint256 i; while (startId <= endId) { itemOwners[i] = IndexToOwner[startId]; itemPrices[i] = IndexToPrice[startId]; itemPlatPrices[i] = SafeMath.mul(IndexToPrice[startId],PLATPrice); i++; startId++; } return (itemOwners, itemPrices, itemPlatPrices); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Set or reaffirm the approved address for a rare item _approved The new approved rare item controller _tokenId The rare item to approve
function approve(address _approved, uint256 _tokenId) external isValidToken(_tokenId) onlyOwnerOf(_tokenId) payable { address owner = IndexToOwner[_tokenId]; require(operatorToApprovals[owner][msg.sender]); IndexToApproved[_tokenId] = _approved; Approval(owner, _approved, _tokenId); }
10,507,532
/** *Submitted for verification at Etherscan.io on 2021-07-05 */ pragma solidity =0.8.0; // SPDX-License-Identifier: MIT /** * @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 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 Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } /** * @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); } } /** * @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 External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } /// @title Locked /// @dev Smart contract to enable locking and unlocking of token holders. contract Locked is AccessControl { mapping (address => bool) public lockedList; event AddedLock(address user); event RemovedLock(address user); // Create a new role identifier for the controller role bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); modifier isController { require(hasRole(CONTROLLER_ROLE, msg.sender), "Locked::isController - Caller is not a controller"); _; } modifier isMinter { require(hasRole(MINTER_ROLE, msg.sender), "Locked::isMinter - Caller is not a minter"); _; } /// @dev terminate transaction if any of the participants is locked /// @param _from - user initiating process /// @param _to - user involved in process modifier isNotLocked(address _from, address _to) { if (!hasRole(DEFAULT_ADMIN_ROLE, _from)){ // allow contract admin on sending tokens even if recipient is locked require(!lockedList[_from], "Locked::isNotLocked - User is locked"); require(!lockedList[_to], "Locked::isNotLocked - User is locked"); } _; } /// @dev check if user has been locked /// @param _user - usr to check /// @return true or false function isLocked(address _user) public view returns (bool) { return lockedList[_user]; } /// @dev add user to lock /// @param _user to lock function addLock (address _user) public isController() { _addLock(_user); } function addLockMultiple(address[] memory _users) public isController() { uint256 length = _users.length; require(length <= 256, "Locked-addLockMultiple: List too long"); for (uint256 i = 0; i < length; i++) { _addLock(_users[i]); } } /// @dev unlock user /// @param _user - user to unlock function removeLock (address _user) isController() public { _removeLock(_user); } /// @dev add user to lock for internal needs /// @param _user to lock function _addLock(address _user) internal { lockedList[_user] = true; emit AddedLock(_user); } /// @dev unlock user for internal needs /// @param _user - user to unlock function _removeLock (address _user) internal { lockedList[_user] = false; emit RemovedLock(_user); } } pragma experimental ABIEncoderV2; contract AuditToken is Locked, ERC20, ERC20Burnable{ /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); uint8 public constant DECIMALS = 18; uint256 public constant INITIAL_SUPPLY = 250000000 * (10**uint256(DECIMALS)); address public migrationAgent; uint256 public totalMigrated; /// @dev Constructor that gives an account all initial tokens. constructor(address account) ERC20("Auditchain", "AUDT") { require(account != address(0), "AuditToken:constructor - Address can't be 0"); _mint(account, INITIAL_SUPPLY); _setupRole(DEFAULT_ADMIN_ROLE, account); } /// @dev prevent accidental sending of tokens to this token contract /// @param _self - address of this contract modifier notSelf(address _self) { require( _self != address(this), "You are trying to send tokens to this token contract" ); _; } /// @notice Overwrite parent implementation to add locked verification, notSelf modifiers and call to moveDelegates function transfer(address to, uint256 value) public override isNotLocked(msg.sender, to) notSelf(to) returns (bool) { _moveDelegates(delegates[msg.sender], delegates[to], uint96(value)); return super.transfer(to, value); } /// @notice Overwrite parent implementation to add locked verification, notSelf modifiers and call to moveDelegates function transferFrom( address from, address to, uint256 value ) public override isNotLocked(from, to) notSelf(to) returns (bool) { _moveDelegates(delegates[from], delegates[to], uint96(value)); return super.transferFrom(from, to, value); } /// @dev Function to mint tokens /// @param to address to which new minted tokens are sent /// @param amount of tokens to send /// @return A boolean that indicates if the operation was successful. function mint(address to, uint256 amount) public isMinter() returns (bool) { _mint(to, amount); return true; } /// @notice Overwrite parent implementation to add locked verification function burn (uint256 amount) public override isNotLocked(msg.sender, msg.sender) { super.burn(amount); } /// @notice Overwrite parent implementation to add locked verification function burnFrom (address user, uint256 amount) public override isNotLocked(msg.sender, msg.sender) { super.burnFrom(user, amount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "auditToken::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = uint96(balanceOf(delegator)); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "auditToken::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "auditToken::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "auditToken::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal view returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // @note this contract will allow data subscribers to claim their tokens. contract DataSubClaim { mapping (address => uint256) public amounts; mapping (address => bool) public redeemed; AuditToken private _token; event Redeemed (address user, uint256 amount); constructor(address auditToken) { amounts[0x86313dF1fb97B8B37b10aE408566a6fc80d59B99] = 15750944 * 1e16; amounts[0x6EeD353855D22d9c3137E0885272eD5d03Bcc81e] = 84003750 * 1e16; amounts[0x3855De1896983fA30D17712385931b4a837De6d9] = 26378940 * 1e16; amounts[0x361746F3FB7e93CF858EC272df366CF015Ce4fc2] = 2500000 * 1e16; amounts[0x34b2CCCE7611fF55Ee6D5Dcca38aD06E8fCB610E] = 14329834 * 1e16; amounts[0x3E158216a3348703016d7cbE855Dff2f6c131287] = 34711232 * 1e16; amounts[0x65A531419890a87CdBc026d91C09268746A71b55] = 15470360 * 1e16; amounts[0x447d606cd2A4DD77FE283d2a86740962A614BC28] = 1987785 * 1e16; amounts[0x112A8D3D6547971C8db02F8F02f95e3bEA61406a] = 13227160 * 1e16; amounts[0xd24400ae8BfEBb18cA49Be86258a3C749cf46853] = 5625000 * 1e16; amounts[0xf3d0a48EF98d47024756a523120b20252fce1C15] = 6625229 * 1e16; amounts[0xcf1f1ce5c157182455B721031121CE0c6BFC5D3f] = 81570432 * 1e16; amounts[0xf50660B36E6A591B7C4B5CDD8fF6Db89Dde749B5] = 4050000 * 1e16; amounts[0x6284D3E8D097971c26b628E6a7780754E572C858] = 557710842 * 1e16; amounts[0x41DFF620Df07Fb0cF3a9839BEde24243b7e5A02A] = 250000000 * 1e16; amounts[0xc1dAF6F317ad522f9fB6b32783A6266e8EC22db8] = 174548373 * 1e16; amounts[0x36bb02f8AFbE3eaF2683658b1A3e1d51b7a7C67a] = 31445973 * 1e16; amounts[0x234261D52E69B67F543aCe4B9dcdC865858e5aeb] = 37591713 * 1e16; amounts[0xef006d266395826652a11C71826eA9dbf780B7e8] = 26099945 * 1e16; amounts[0x3543F98F319Ea2be26B0Bdec0CCeF9dC1BFF67b8] = 5962500 * 1e16; amounts[0x2b60aeb7cD45EeeD4b6fAf05fc97bf5E8573A46B] = 14000000 * 1e16; amounts[0xdA7DFf65dF80533A61398b3d0B1001F2704b138E] = 9000000 * 1e16; amounts[0x7e28c209b2C7BC2F30c55aC141326285f47889BD] = 54706500 * 1e16; amounts[0x6045F02fB3D85FedaE61AD4f5194E1f0539D362A] = 750000 * 1e16; amounts[0x217B781ce0Ec915074f0c4a5fA73fba3dF3956EB] = 750000 * 1e16; _token = AuditToken(auditToken); } /** * @dev Function to redeem data subscriber tokens */ function redeem() public { require(amounts[msg.sender] > 0 , "DataSubClaim:redeem - You don't have any tokens to redeem."); require(!redeemed[msg.sender], "DataSubClaim:redeem - You have already redeemed your tokens."); redeemed[msg.sender] = true; _token.mint(msg.sender, amounts[msg.sender]); emit Redeemed(msg.sender, amounts[msg.sender]); } }
Delegate votes from `msg.sender` to `delegatee` delegatee The address to delegate votes to/
function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); }
1,995,263
./full_match/1/0xC68a8c6A29412827018A23058E0CEd132889Ea48/sources/src/strategies/PancakeSwapPulseStrategyV2.sol
Rebalancing goes like this: 1. Function checks the current states of the pools, and if the volatility is significant, the transaction reverts. 2. If necessary, a new position is minted on pancakeSwapVault, and the previous one is burned. 3. Tokens on erc20Vault are swapped via AggregationRouterV5 so that the proportion matches the tokens on pancakeSwapVault. 4. The strategy transfers all possible tokens from erc20Vault to pancakeSwapVault. Only users with administrator or operator roles can call the function. deadline Timestamp by which the transaction must be completed swapData Data for swap on 1inch AggregationRouterV5
function rebalance( uint256 deadline, bytes calldata swapData, uint256 minAmountOutInCaseOfSwap ) external { require(block.timestamp <= deadline, ExceptionsLibrary.TIMESTAMP); _requireAtLeastOperator(); ImmutableParams memory immutableParams_ = immutableParams; MutableParams memory mutableParams_ = mutableParams; IPancakeV3Pool pool = immutableParams_.pancakeSwapVault.pool(); checkTickDeviation(mutableParams_, pool); (uint160 sqrtPriceX96, int24 spotTick, , , , , ) = pool.slot0(); Interval memory interval = _positionsRebalance(immutableParams_, mutableParams_, spotTick, pool); forceRebalanceWidthFlag = false; _swapToTarget(immutableParams_, mutableParams_, interval, sqrtPriceX96, swapData, minAmountOutInCaseOfSwap); _pushIntoPancakeSwap(immutableParams_); emit Rebalance(tx.origin, msg.sender); }
16,471,534
./full_match/1/0x162A78B8bbB2c7dbD6D7aceC507EF9625d2b34E4/sources/contracts/savings/Bank.sol
updateTotalLoan(_token);
function update( address _token, uint256 _amount, ActionType _action ) public onlyAuthorized returns (uint256 compoundAmount) { updateTotalCompound(_token); compoundAmount = updateTotalReserve(_token, _amount, _action); return compoundAmount; }
17,083,676
./full_match/1/0x4C3c31518D525d1e1657DBef952A98AA807bC19a/sources/lib/ERC721A/contracts/ERC721A.sol
Flag that specifies whether an ownership timestamp should be updated every transfer Setting this to false effectively stores the mint time of the token./
function _updateTimestampOnTransfer() internal virtual returns(bool) { return true; }
9,736,607
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {Utilities} from "../../utils/Utilities.sol"; import "forge-std/Test.sol"; import {DamnValuableToken} from "../../../src/Contracts/DamnValuableToken.sol"; import {PuppetPool} from "../../../src/Contracts/puppet/PuppetPool.sol"; interface UniswapV1Exchange { function addLiquidity( uint256 min_liquidity, uint256 max_tokens, uint256 deadline ) external payable returns (uint256); function balanceOf(address _owner) external view returns (uint256); function tokenToEthSwapInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline ) external returns (uint256); function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256); } interface UniswapV1Factory { function initializeFactory(address template) external; function createExchange(address token) external returns (address); } contract Puppet is Test { // Uniswap exchange will start with 10 DVT and 10 ETH in liquidity uint256 internal constant UNISWAP_INITIAL_TOKEN_RESERVE = 10e18; uint256 internal constant UNISWAP_INITIAL_ETH_RESERVE = 10e18; uint256 internal constant ATTACKER_INITIAL_TOKEN_BALANCE = 1_000e18; uint256 internal constant ATTACKER_INITIAL_ETH_BALANCE = 25e18; uint256 internal constant POOL_INITIAL_TOKEN_BALANCE = 100_000e18; uint256 internal constant DEADLINE = 10_000_000; UniswapV1Exchange internal uniswapV1ExchangeTemplate; UniswapV1Exchange internal uniswapExchange; UniswapV1Factory internal uniswapV1Factory; DamnValuableToken internal dvt; PuppetPool internal puppetPool; address payable internal attacker; function setUp() public { /** SETUP SCENARIO - NO NEED TO CHANGE ANYTHING HERE */ attacker = payable( address(uint160(uint256(keccak256(abi.encodePacked("attacker"))))) ); vm.label(attacker, "Attacker"); vm.deal(attacker, ATTACKER_INITIAL_ETH_BALANCE); // Deploy token to be traded in Uniswap dvt = new DamnValuableToken(); vm.label(address(dvt), "DVT"); uniswapV1Factory = UniswapV1Factory( deployCode("./src/build-uniswap/v1/UniswapV1Factory.json") ); // Deploy a exchange that will be used as the factory template uniswapV1ExchangeTemplate = UniswapV1Exchange( deployCode("./src/build-uniswap/v1/UniswapV1Exchange.json") ); // Deploy factory, initializing it with the address of the template exchange uniswapV1Factory.initializeFactory(address(uniswapV1ExchangeTemplate)); uniswapExchange = UniswapV1Exchange( uniswapV1Factory.createExchange(address(dvt)) ); vm.label(address(uniswapExchange), "Uniswap Exchange"); // Deploy the lending pool puppetPool = new PuppetPool(address(dvt), address(uniswapExchange)); vm.label(address(puppetPool), "Puppet Pool"); // Add initial token and ETH liquidity to the pool dvt.approve(address(uniswapExchange), UNISWAP_INITIAL_TOKEN_RESERVE); uniswapExchange.addLiquidity{value: UNISWAP_INITIAL_ETH_RESERVE}( 0, // min_liquidity UNISWAP_INITIAL_TOKEN_RESERVE, // max_tokens DEADLINE // deadline ); // Ensure Uniswap exchange is working as expected assertEq( uniswapExchange.getTokenToEthInputPrice(1 ether), calculateTokenToEthInputPrice( 1 ether, UNISWAP_INITIAL_TOKEN_RESERVE, UNISWAP_INITIAL_ETH_RESERVE ) ); // Setup initial token balances of pool and attacker account dvt.transfer(attacker, ATTACKER_INITIAL_TOKEN_BALANCE); dvt.transfer(address(puppetPool), POOL_INITIAL_TOKEN_BALANCE); // Ensure correct setup of pool. assertEq( puppetPool.calculateDepositRequired(POOL_INITIAL_TOKEN_BALANCE), POOL_INITIAL_TOKEN_BALANCE * 2 ); console.log(unicode"🧨 PREPARED TO BREAK THINGS 🧨"); } function testExploit() public { /** EXPLOIT START **/ /** EXPLOIT END **/ validation(); } function validation() internal { // Attacker has taken all tokens from the pool assertEq(dvt.balanceOf(attacker), POOL_INITIAL_TOKEN_BALANCE); assertEq(dvt.balanceOf(address(puppetPool)), 0); } // Calculates how much ETH (in wei) Uniswap will pay for the given amount of tokens function calculateTokenToEthInputPrice( uint256 input_amount, uint256 input_reserve, uint256 output_reserve ) internal returns (uint256) { uint256 input_amount_with_fee = input_amount * 997; uint256 numerator = input_amount_with_fee * output_reserve; uint256 denominator = (input_reserve * 1000) + input_amount_with_fee; return numerator / denominator; } }
Attacker has taken all tokens from the pool
function validation() internal { assertEq(dvt.balanceOf(attacker), POOL_INITIAL_TOKEN_BALANCE); assertEq(dvt.balanceOf(address(puppetPool)), 0); }
6,415,748
./full_match/43114/0x594D5519c2BCBFd5D21aa9FA6755312caA31CFd4/sources/contracts/liquid-yield/LyRedistributor.sol
Account for any incoming rewards, to be distributed, as well as reward outflows in reserve
function updateRewardTotal() public { uint256 totalStaked = stakeToken.balanceOf(address(this)); for (uint256 i; rewardTokens.length > i; i++) { RewardToken storage r = rewardTokens[i]; IERC20 token = IERC20(r.token); uint256 balance = token.balanceOf(address(this)); if (balance > r.reserve) { r.cumulRewardPer1e18 += (1e18 * (balance - r.reserve)) / totalStaked; } r.reserve = balance; } }
4,513,045
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; pragma experimental ABIEncoderV2; import "contracts/v1/ARDImplementationV1.sol"; import "@openzeppelin/contracts/utils/Checkpoints.sol"; //import "hardhat/console.sol"; /** * @title Staking Token (STK) * @author Gheis Mohammadi * @dev Implements a staking Protocol using ARD token. */ contract StakingTokenV1 is ARDImplementationV1 { using SafeMath for uint256; using SafeMath for uint64; /***************************************************************** ** STRUCTS & VARIABLES ** ******************************************************************/ struct Stake { uint256 id; uint256 stakedAt; uint256 value; uint64 lockPeriod; } struct StakeHolder { uint256 totalStaked; Stake[] stakes; } struct Rate { uint256 timestamp; uint256 rate; } struct RateHistory { Rate[] rates; } /***************************************************************** ** STATES ** ******************************************************************/ /** * @dev token bank for storing the punishments */ address internal tokenBank; /** * @dev start/stop staking protocol */ bool internal stakingEnabled; /** * @dev start/stop staking protocol */ bool internal earlyUnstakingAllowed; /** * @dev The minimum amount of tokens to stake */ uint256 internal minStake; /** * @dev The id of the last stake */ uint256 internal _lastStakeID; /** * @dev staking history */ Checkpoints.History internal totalStakedHistory; /** * @dev stakeholder address map to stakes records details. */ mapping(address => StakeHolder) internal stakeholders; /** * @dev The reward rate history per locking period */ mapping(uint256 => RateHistory) internal rewardTable; /** * @dev The punishment rate history per locking period */ mapping(uint256 => RateHistory) internal punishmentTable; /***************************************************************** ** MODIFIERS ** ******************************************************************/ modifier onlyActiveStaking() { require(stakingEnabled, "staking protocol stopped"); _; } /***************************************************************** ** EVENTS ** ******************************************************************/ // staking/unstaking events event Staked(address indexed from, uint256 amount, uint256 newStake, uint256 oldStake); event Unstaked(address indexed from, uint256 amount, uint256 newStake, uint256 oldStake); // events for adding or changing reward/punishment rate event RewardRateChanged(uint256 timestamp, uint256 newRate, uint256 oldRate); event PunishmentRateChanged(uint256 timestamp, uint256 newRate, uint256 oldRate); // events for staking start/stop event StakingStatusChanged(bool _enabled); // events for stop early unstaking event earlyUnstakingAllowanceChanged(bool _isAllowed); /***************************************************************** ** FUNCTIONALITY ** ******************************************************************/ /** * This constructor serves the purpose of leaving the implementation contract in an initialized state, * which is a mitigation against certain potential attacks. An uncontrolled implementation * contract might lead to misleading state for users who accidentally interact with it. */ /// @custom:oz-upgrades-unsafe-allow constructor constructor() { //initialize(name_,symbol_); _pause(); } /** * @dev initials tokens, roles, staking settings and so on. * this serves as the constructor for the proxy but compiles to the * memory model of the Implementation contract. */ function initialize(string memory name_, string memory symbol_, address newowner_) public initializer{ _initialize(name_, symbol_, newowner_); // contract can mint the rewards _setupRole(MINTER_ROLE, address(this)); // set last stake id _lastStakeID = 0; //enable staking by default stakingEnabled=true; //enable early unstaking earlyUnstakingAllowed=true; } /** * @dev set token bank account address * @param _tb address of the token bank account */ function setTokenBank(address _tb) public notPaused onlySupplyController { tokenBank=_tb; } /** * @dev set token bank account address * @return address of the token bank account */ function getTokenBank() public view returns(address) { return tokenBank; } /////////////////////////////////////////////////////////////////////// // STAKING // /////////////////////////////////////////////////////////////////////// /** * @dev enable/disable stoking * @param _enabled enable/disable */ function enableStakingProtocol(bool _enabled) public notPaused onlySupplyController { require(stakingEnabled!=_enabled, "same as it is"); stakingEnabled=_enabled; emit StakingStatusChanged(_enabled); } /** * @dev enable/disable stoking * @return bool wheter staking protocol is enabled or not */ function isStakingProtocolEnabled() public view returns(bool) { return stakingEnabled; } /** * @dev enable/disable early unstaking * @param _enabled enable/disable */ function enableEarlyUnstaking(bool _enabled) public notPaused onlySupplyController { require(earlyUnstakingAllowed!=_enabled, "same as it is"); earlyUnstakingAllowed=_enabled; emit earlyUnstakingAllowanceChanged(_enabled); } /** * @dev check whether unstoking is allowed * @return bool wheter unstaking protocol is allowed or not */ function isEarlyUnstakingAllowed() public view returns(bool) { return earlyUnstakingAllowed; } /** * @dev set the minimum acceptable amount of tokens to stake * @param _minStake minimum token amount to stake */ function setMinimumStake(uint256 _minStake) public notPaused onlySupplyController { minStake=_minStake; } /** * @dev get the minimum acceptable amount of tokens to stake * @return uint256 minimum token amount to stake */ function minimumAllowedStake() public view returns (uint256) { return minStake; } /** * @dev A method for a stakeholder to create a stake. * @param _value The size of the stake to be created. * @param _lockPeriod the period of lock for this stake * @return uint256 new stake id */ function stake(uint256 _value, uint64 _lockPeriod) public returns(uint256) { return _stake(_msgSender(), _value, _lockPeriod); } /** * @dev A method to create a stake in behalf of a stakeholder. * @param _stakeholder address of the stake holder * @param _value The size of the stake to be created. * @param _lockPeriod the period of lock for this stake * @return uint256 new stake id */ function stakeFor(address _stakeholder, uint256 _value, uint64 _lockPeriod) public onlySupplyController returns(uint256) { return _stake(_stakeholder, _value, _lockPeriod); } /** * @dev A method for a stakeholder to remove a stake. * @param _stakedID id number of the stake * @param _value The size of the stake to be removed. */ function unstake(uint256 _stakedID, uint256 _value) public { _unstake(_msgSender(),_stakedID,_value); } /** * @dev A method for supply controller to remove a stake of a stakeholder. * @param _stakeholder The stakeholder to unstake his tokens. * @param _stakedID The unique id of the stake * @param _value The size of the stake to be removed. */ function unstakeFor(address _stakeholder, uint256 _stakedID, uint256 _value) public onlySupplyController { _unstake(_stakeholder,_stakedID,_value); } /** * @dev A method to retrieve the stake for a stakeholder. * @param _stakeholder The stakeholder to retrieve the stake for. * @return uint256 The amount of wei staked. */ function stakeOf(address _stakeholder) public view returns(uint256) { return stakeholders[_stakeholder].totalStaked; } /** * @dev A method to retrieve the stakes for a stakeholder. * @param _stakeholder The stakeholder to retrieve the stake for. * @return stakes history of the stake holder. */ function stakes(address _stakeholder) public view returns(Stake[] memory) { return(stakeholders[_stakeholder].stakes); } /** * @dev A method to get the aggregated stakes from all stakeholders. * @return uint256 The aggregated stakes from all stakeholders. */ function totalStakes() public view returns(uint256) { return Checkpoints.latest(totalStakedHistory); } /** * @dev A method to get the value of total locked stakes. * @return uint256 The total locked stakes. */ function totalValueLocked() public view returns(uint256) { return Checkpoints.latest(totalStakedHistory); } /** * @dev Returns the value in the latest stakes history, or zero if there are no stakes. * @param _stakeholder The stakeholder to retrieve the latest stake amount. */ function latest(address _stakeholder) public view returns (uint256) { uint256 pos = stakeholders[_stakeholder].stakes.length; return pos == 0 ? 0 : stakeholders[_stakeholder].stakes[pos - 1].value; } /** * @dev Stakes _value for a stake holder. It pushes a value onto a History so that it is stored as the checkpoint for the current block. * * @return uint256 new stake id */ function _stake(address _stakeholder, uint256 _value, uint64 _lockPeriod) internal notPaused onlyActiveStaking returns(uint256) { //_burn(_msgSender(), _stake); require(_stakeholder!=address(0),"zero account"); require(_value >= minStake, "less than minimum stake"); require(_value<=balanceOf(_stakeholder), "not enough balance"); require(rewardTable[_lockPeriod].rates.length > 0, "invalid period"); require(punishmentTable[_lockPeriod].rates.length > 0, "invalid period"); _transfer(_stakeholder, address(this), _value); //if(stakeholders[_msgSender()].totalStaked == 0) addStakeholder(_msgSender()); uint256 pos = stakeholders[_stakeholder].stakes.length; uint256 old = stakeholders[_stakeholder].totalStaked; if (pos > 0 && stakeholders[_stakeholder].stakes[pos - 1].stakedAt == block.timestamp && stakeholders[_stakeholder].stakes[pos - 1].lockPeriod == _lockPeriod) { stakeholders[_stakeholder].stakes[pos - 1].value = stakeholders[_stakeholder].stakes[pos - 1].value.add(_value); } else { // uint256 _id = 1; // if (pos > 0) _id = stakeholders[_stakeholder].stakes[pos - 1].id.add(1); _lastStakeID++; stakeholders[_stakeholder].stakes.push(Stake({ id: _lastStakeID, stakedAt: block.timestamp, value: _value, lockPeriod: _lockPeriod })); pos++; } stakeholders[_stakeholder].totalStaked = stakeholders[_stakeholder].totalStaked.add(_value); // checkpoint total supply _updateTotalStaked(_value, true); emit Staked(_stakeholder,_value, stakeholders[_stakeholder].totalStaked, old); return(stakeholders[_stakeholder].stakes[pos-1].id); } /** * @dev Unstake _value from specific stake for a stake holder. It calculate the reward/punishment as well. * It pushes a value onto a History so that it is stored as the checkpoint for the current block. * Returns previous value and new value. */ function _unstake(address _stakeholder, uint256 _stakedID, uint256 _value) internal notPaused onlyActiveStaking { //_burn(_msgSender(), _stake); require(_stakeholder!=address(0),"zero account"); require(_value > 0, "zero unstake"); require(_value <= stakeOf(_stakeholder) , "unstake more than staked"); uint256 old = stakeholders[_stakeholder].totalStaked; require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); uint256 stakeIndex; bool found = false; for (stakeIndex = 0; stakeIndex < stakeholders[_stakeholder].stakes.length; stakeIndex += 1){ if (stakeholders[_stakeholder].stakes[stakeIndex].id == _stakedID) { found = true; break; } } require(found,"invalid stake id"); require(_value<=stakeholders[_stakeholder].stakes[stakeIndex].value,"not enough stake"); uint256 _stakedAt = stakeholders[_stakeholder].stakes[stakeIndex].stakedAt; require(block.timestamp>=_stakedAt,"invalid stake"); // make decision about reward/punishment uint256 stakingDays = (block.timestamp - _stakedAt) / (1 days); if (stakingDays>=stakeholders[_stakeholder].stakes[stakeIndex].lockPeriod) { //Reward uint256 _reward = _calculateReward(_stakedAt, block.timestamp, _value, stakeholders[_stakeholder].stakes[stakeIndex].lockPeriod); if (_reward>0) { _mint(_stakeholder,_reward); } _transfer(address(this), _stakeholder, _value); } else { //Punishment require (earlyUnstakingAllowed, "early unstaking disabled"); uint256 _punishment = _calculatePunishment(_stakedAt, block.timestamp, _value, stakeholders[_stakeholder].stakes[stakeIndex].lockPeriod); _punishment = _punishment<_value ? _punishment : _value; //If there is punishment, send them to token bank if (_punishment>0) { _transfer(address(this), tokenBank, _punishment); } uint256 withdrawal = _value.sub( _punishment ); if (withdrawal>0) { _transfer(address(this), _stakeholder, withdrawal); } } // deduct unstaked amount from locked ARDs stakeholders[_stakeholder].stakes[stakeIndex].value = stakeholders[_stakeholder].stakes[stakeIndex].value.sub(_value); if (stakeholders[_stakeholder].stakes[stakeIndex].value==0) { removeStakeRecord(_stakeholder, stakeIndex); } stakeholders[_stakeholder].totalStaked = stakeholders[_stakeholder].totalStaked.sub(_value); // checkpoint total supply _updateTotalStaked(_value, false); //if no any stakes, remove stake holder if (stakeholders[_stakeholder].totalStaked==0) { delete stakeholders[_stakeholder]; } emit Unstaked(_stakeholder, _value, stakeholders[_stakeholder].totalStaked, old); } /** * @dev removes a record from the stake array of a specific stake holder * @param _stakeholder The stakeholder to remove stake from. * @param index the stake index (uinque ID) * Returns previous value and new value. */ function removeStakeRecord(address _stakeholder, uint index) internal { for(uint i = index; i < stakeholders[_stakeholder].stakes.length-1; i++){ stakeholders[_stakeholder].stakes[i] = stakeholders[_stakeholder].stakes[i+1]; } stakeholders[_stakeholder].stakes.pop(); } /** * @dev update the total stakes history * @param _by The amount of stake to be added or deducted from history * @param _increase true means new staked is added to history and false means it's unstake and stake should be deducted from history * Returns previous value and new value. */ function _updateTotalStaked(uint256 _by, bool _increase) internal onlyActiveStaking { uint256 currentStake = Checkpoints.latest(totalStakedHistory); uint256 newStake; if (_increase) { newStake = currentStake.add(_by); } else { newStake = currentStake.sub(_by); } // add new value to total history Checkpoints.push(totalStakedHistory, newStake); } /** * @dev A method to get last stake id. * @return uint256 returns the ID of last stake */ function lastStakeID() public view returns(uint256) { return _lastStakeID; } /////////////////////////////////////////////////////////////////////// // STAKEHOLDERS // /////////////////////////////////////////////////////////////////////// /** * @dev A method to check if an address is a stakeholder. * @param _address The address to verify. * @return bool Whether the address is a stakeholder or not */ function isStakeholder(address _address) public view returns(bool) { return (stakeholders[_address].totalStaked>0); } /////////////////////////////////////////////////////////////////////// // REWARDS / PUNISHMENTS // /////////////////////////////////////////////////////////////////////// /** * @dev set reward rate in percentage (2 decimal zeros) for a specific lock period. * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days * @param _value The reward per entire period for the given lock period */ function setReward(uint256 _lockPeriod, uint64 _value) public notPaused onlySupplyController { require(_value>=0 && _value<=10000, "invalid rate"); uint256 ratesCount = rewardTable[_lockPeriod].rates.length; uint256 oldRate = ratesCount>0 ? rewardTable[_lockPeriod].rates[ratesCount-1].rate : 0; require(_value!=oldRate, "duplicate rate"); rewardTable[_lockPeriod].rates.push(Rate({ timestamp: block.timestamp, rate: _value })); emit RewardRateChanged(block.timestamp,_value,oldRate); } /** * @dev A method for adjust rewards table by single call. Should be called after first deployment. * this method merges the new table with current reward table (if it is existed) * @param _rtbl reward table ex: * const rewards = [ * [30, 200], * [60, 300], * [180, 500], * ]; */ function setRewardTable(uint64[][] memory _rtbl) public notPaused onlySupplyController { for (uint64 _rIndex = 0; _rIndex<_rtbl.length; _rIndex++) { setReward(_rtbl[_rIndex][0], _rtbl[_rIndex][1]); } } /** * @dev A method for retrieve the latest reward rate for a give lock period * if there is no rate for given lock period, it throws error * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days */ function rewardRate(uint256 _lockPeriod) public view returns(uint256) { require(rewardTable[_lockPeriod].rates.length>0,"no rate"); return _lastRate(rewardTable[_lockPeriod]); } /** * @dev A method for retrieve the history of the reward rate for a given lock period * if there is no rate for given lock period, it throws error * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days */ function rewardRateHistory(uint256 _lockPeriod) public view returns(RateHistory memory) { require(rewardTable[_lockPeriod].rates.length>0,"no rate"); return rewardTable[_lockPeriod]; } /** * @dev set punishment rate in percentage (2 decimal zeros) for a specific lock period. * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days * @param _value The punishment per entire period for the given lock period */ function setPunishment(uint256 _lockPeriod, uint64 _value) public notPaused onlySupplyController { require(_value>=0 && _value<=2000, "invalid rate"); uint256 ratesCount = punishmentTable[_lockPeriod].rates.length; uint256 oldRate = ratesCount>0 ? punishmentTable[_lockPeriod].rates[ratesCount-1].rate : 0; require(_value!=oldRate, "same as it is"); punishmentTable[_lockPeriod].rates.push(Rate({ timestamp: block.timestamp, rate: _value })); emit PunishmentRateChanged(block.timestamp,_value,oldRate); } /** * @dev A method for adjust punishment table by single call. * this method merges the new table with current punishment table (if it is existed) * @param _ptbl punishment table ex: * const punishments = [ * [30, 200], * [60, 300], * [180, 500], * ]; */ function setPunishmentTable(uint64[][] memory _ptbl) public notPaused onlySupplyController { for (uint64 _pIndex = 0; _pIndex<_ptbl.length; _pIndex++) { setPunishment(_ptbl[_pIndex][0], _ptbl[_pIndex][1]); } } /** * @dev A method to get the latest punishment rate * if there is no rate for given lock period, it throws error * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days */ function punishmentRate(uint256 _lockPeriod) public view returns(uint256) { require(punishmentTable[_lockPeriod].rates.length>0,"no rate"); return _lastRate(punishmentTable[_lockPeriod]); } /** * @dev A method for retrieve the history of the punishment rate for a give lock period * if there is no rate for given lock period, it throws error * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days */ function punishmentRateHistory(uint256 _lockPeriod) public view returns(RateHistory memory) { require(punishmentTable[_lockPeriod].rates.length>0,"no rate"); return punishmentTable[_lockPeriod]; } /** * @dev A method to inquiry the rewards from the specific stake of the stakeholder. * @param _stakeholder The stakeholder to get the reward for his stake. * @param _stakedID The stake id. * @return uint256 The reward of the stake. */ function rewardOf(address _stakeholder, uint256 _stakedID) public view returns(uint256) { require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); // uint256 _totalRewards = 0; // for (uint256 i = 0; i < stakeholders[_stakeholder].stakes.length; i++){ // Stake storage s = stakeholders[_stakeholder].stakes[i]; // uint256 r = _calculateReward(s.stakedAt, block.timestamp, s.value, s.lockPeriod); // _totalRewards = _totalRewards.add(r); // } // return _totalRewards; return calculateRewardFor(_stakeholder,_stakedID); } /** * @dev A method to inquiry the punishment from the early unstaking of the specific stake of the stakeholder. * @param _stakeholder The stakeholder to get the punishment for early unstake. * @param _stakedID The stake id. * @return uint256 The punishment of the early unstaking of the stake. */ function punishmentOf(address _stakeholder, uint256 _stakedID) public view returns(uint256) { require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); // uint256 _totalPunishments = 0; // for (uint256 i = 0; i < stakeholders[_stakeholder].stakes.length; i++){ // Stake storage s = stakeholders[_stakeholder].stakes[i]; // uint256 r = _calculatePunishment(s.stakedAt, block.timestamp, s.value, s.lockPeriod); // _totalPunishments = _totalPunishments.add(r); // } // return _totalPunishments; return calculatePunishmentFor(_stakeholder,_stakedID); } /** * @dev A simple method to calculate the rewards for a specific stake of a stakeholder. * The rewards only is available after stakeholder unstakes the ARDs. * @param _stakeholder The stakeholder to calculate rewards for. * @param _stakedID The stake id. * @return uint256 return the reward for the stake with specific ID. */ function calculateRewardFor(address _stakeholder, uint256 _stakedID) internal view returns(uint256) { require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); uint256 stakeIndex; bool found = false; for (stakeIndex = 0; stakeIndex < stakeholders[_stakeholder].stakes.length; stakeIndex += 1){ if (stakeholders[_stakeholder].stakes[stakeIndex].id == _stakedID) { found = true; break; } } require(found,"invalid stake id"); Stake storage s = stakeholders[_stakeholder].stakes[stakeIndex]; return _calculateReward(s.stakedAt, block.timestamp, s.value, s.lockPeriod); } /** * @dev A simple method to calculates the reward for stakeholder from a given period which is set by _from and _to. * @param _from The start date of the period. * @param _to The end date of the period. * @param _value Amount of staking. * @param _lockPeriod lock period for this staking. * @return uint256 total reward for given period */ function _calculateReward(uint256 _from, uint256 _to, uint256 _value, uint256 _lockPeriod) internal view returns(uint256) { require (_to>=_from,"invalid stake time"); uint256 durationDays = _duration(_from,_to,_lockPeriod); if (durationDays<_lockPeriod) return 0; return _calculateTotal(rewardTable[_lockPeriod],_from,_to,_value,_lockPeriod); } /** * @dev A simple method to calculate punishment for early unstaking of a specific stake of the stakeholder. * The punishment is only charges after stakeholder unstakes the ARDs. * @param _stakeholder The stakeholder to calculate punishment for. * @param _stakedID The stake id. * @return uint256 return the punishment for the stake with specific ID. */ function calculatePunishmentFor(address _stakeholder, uint256 _stakedID) internal view returns(uint256) { require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); uint256 stakeIndex; bool found = false; for (stakeIndex = 0; stakeIndex < stakeholders[_stakeholder].stakes.length; stakeIndex += 1){ if (stakeholders[_stakeholder].stakes[stakeIndex].id == _stakedID) { found = true; break; } } require(found,"invalid stake id"); Stake storage s = stakeholders[_stakeholder].stakes[stakeIndex]; return _calculatePunishment(s.stakedAt, block.timestamp, s.value, s.lockPeriod); } /** * @dev A simple method that calculates the punishment for stakeholder from a given period which is set by _from and _to. * @param _from The start date of the period. * @param _to The end date of the period. * @param _value Amount of staking. * @param _lockPeriod lock period for this staking. * @return uint256 total punishment for given period */ function _calculatePunishment(uint256 _from, uint256 _to, uint256 _value, uint256 _lockPeriod) internal view returns(uint256) { require (_to>=_from,"invalid stake time"); uint256 durationDays = _to.sub(_from).div(1 days); if (durationDays>=_lockPeriod) return 0; // retrieve latest punishment rate for the lock period uint256 pos = punishmentTable[_lockPeriod].rates.length; require (pos>0, "invalid lock period"); return _value.mul(punishmentTable[_lockPeriod].rates[pos-1].rate).div(10000); //return _calculateTotal(punishmentTable[_lockPeriod],_from,_to,_value,_lockPeriod); } /** * @dev calculates the total amount of reward/punishment for a given period which is set by _from and _to. This method calculates * based on the history of rate changes. So if in this period, three times rate have had changed, this function calculates for each * of the rates separately and returns total * @param _history The history of rates * @param _from The start date of the period. * @param _to The end date of the period. * @param _value Amount of staking. * @param _lockPeriod lock period for this staking. * @return uint256 total reward/punishment for given period considering the rate changes */ function _calculateTotal(RateHistory storage _history, uint256 _from, uint256 _to, uint256 _value, uint256 _lockPeriod) internal view returns(uint256) { //find the first rate before _from require(_history.rates.length>0,"invalid period"); uint256 rIndex; for (rIndex = _history.rates.length-1; rIndex>0; rIndex-- ) { if (_history.rates[rIndex].timestamp<=_from) break; } require(_history.rates[rIndex].timestamp<=_from, "lack of history rates"); // if rate has been constant during the staking period, just calculate whole period using same rate if (rIndex==_history.rates.length-1) { return _value.mul(_history.rates[rIndex].rate).div(10000); //10000 ~ 100.00 } // otherwise we have to calculate reward per each rate change record from history /* [1.5%] [5%] [2%] Rate History: (deployed)o(R0)----------------o(R1)-------------o(R2)-----------------o(R3)-------------------- Given Period: o(from)--------------------------------------o(to) Calculations: ( 1.5%*(R1-from) + 5%*(R2-R1) + 2%*(to-R2) ) / Period */ uint256 total = 0; uint256 totalDuration = 0; uint256 prevTimestamp = _from; uint256 diff = 0; uint256 maxTotalDuration = _duration(_from,_to, _lockPeriod); for (rIndex++; rIndex<=_history.rates.length && totalDuration<maxTotalDuration; rIndex++) { if (rIndex<_history.rates.length){ diff = _duration(prevTimestamp, _history.rates[rIndex].timestamp, 0); prevTimestamp = _history.rates[rIndex].timestamp; }else { diff = _duration(prevTimestamp, _to, 0); prevTimestamp = _to; } totalDuration = totalDuration.add(diff); if (totalDuration>maxTotalDuration) { diff = diff.sub(totalDuration.sub(maxTotalDuration)); totalDuration = maxTotalDuration; } total = total.add(_history.rates[rIndex-1].rate.mul(diff)); } return _value.mul(total).div(_lockPeriod.mul(10000)); } /** * @dev this function calculates the number of days between t1 and t2 * @param t1 the period start * @param t2 the period end * @param maxDuration max duration. if the number of days is more than max, it returns max * @return uint256 number of days */ function _duration(uint256 t1, uint256 t2, uint256 maxDuration) internal pure returns(uint256) { uint256 diffDays = t2.sub(t1).div(1 days); if (maxDuration==0) return diffDays; return Math.min(diffDays,maxDuration); } /** * @dev this function retrieve last rate of a given rate history * @param _history the history of rate changes * @return uint256 the last rate which is current rate */ function _lastRate(RateHistory storage _history) internal view returns(uint256) { return _history.rates[_history.rates.length-1].rate; } // storage gap for adding new states in upgrades uint256[50] private __gap; }
initials tokens, roles, staking settings and so on. this serves as the constructor for the proxy but compiles to the memory model of the Implementation contract./ contract can mint the rewards set last stake idenable staking by defaultenable early unstaking
function initialize(string memory name_, string memory symbol_, address newowner_) public initializer{ _initialize(name_, symbol_, newowner_); _setupRole(MINTER_ROLE, address(this)); _lastStakeID = 0; stakingEnabled=true; earlyUnstakingAllowed=true; }
12,911,959
// solium-disable linebreak-style pragma solidity ^0.4.24; /** * @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 { // Owner's address address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); emit OwnerChanged(owner, _newOwner); owner = _newOwner; } event OwnerChanged(address indexed previousOwner,address indexed newOwner); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract AoraTgeCoin is IERC20, Ownable { using SafeMath for uint256; // Name of the token string public constant name = "Aora TGE Coin"; // Symbol of the token string public constant symbol = "AORATGE"; // Number of decimals for the token uint8 public constant decimals = 18; uint constant private _totalSupply = 650000000 ether; // Contract deployment block uint256 public deploymentBlock; // Address of the convertContract address public convertContract = address(0); // Address of the crowdsaleContract address public crowdsaleContract = address(0); // Token balances mapping (address => uint) balances; /** * @dev Sets the convertContract address. * In the future, there will be a need to convert Aora TGE Coins to Aora Coins. * That will be done using the Convert contract which will be deployed in the future. * Convert contract will do the functions of converting Aora TGE Coins to Aora Coins * and enforcing vesting rules. * @param _convert address of the convert contract. */ function setConvertContract(address _convert) external onlyOwner { require(address(0) != address(_convert)); convertContract = _convert; emit OnConvertContractSet(_convert); } /** * @dev Sets the crowdsaleContract address. * transfer function is modified in a way that only owner and crowdsale can call it. * That is done because crowdsale will sell the tokens, and owner will be allowed * to assign AORATGE to addresses in a way that matches the Aora business model. * @param _crowdsale address of the crowdsale contract. */ function setCrowdsaleContract(address _crowdsale) external onlyOwner { require(address(0) != address(_crowdsale)); crowdsaleContract = _crowdsale; emit OnCrowdsaleContractSet(_crowdsale); } /** * @dev only convert contract can call the modified function */ modifier onlyConvert { require(msg.sender == convertContract); _; } constructor() public { balances[msg.sender] = _totalSupply; deploymentBlock = block.number; } function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address who) external view returns (uint256) { return balances[who]; } function allowance(address owner, address spender) external view returns (uint256) { require(false); return 0; } /** * @dev Transfer token for a specified address. * Only callable by the owner or crowdsale contract, to prevent token trading. * AORA will be a tradable token. AORATGE will be exchanged for AORA in 1-1 ratio. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(msg.sender == owner || msg.sender == crowdsaleContract); require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function approve(address spender, uint256 value) external returns (bool) { require(false); return false; } /** * @dev Transfer tokens from one address to another. * Only callable by the convert contract. Used in the process of converting * AORATGE to AORA. Will be called from convert contracts convert() function. * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to. * Only 0x0 address, because of a need to prevent token recycling. * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) onlyConvert public returns (bool) { require(_value <= balances[_from]); require(_to == address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Fallback function. Can't send ether to this contract. */ function () external payable { revert(); } /** * @dev This method can be used by the owner to extract mistakenly sent tokens * or Ether sent to this contract. * @param _token address The address of the token contract that you want to * recover set to 0 in case you want to extract ether. It can't be ElpisToken. */ function claimTokens(address _token) public onlyOwner { if (_token == address(0)) { owner.transfer(address(this).balance); return; } IERC20 tokenReference = IERC20(_token); uint balance = tokenReference.balanceOf(address(this)); tokenReference.transfer(owner, balance); emit OnClaimTokens(_token, owner, balance); } /** * @param crowdsaleAddress crowdsale contract address */ event OnCrowdsaleContractSet(address indexed crowdsaleAddress); /** * @param convertAddress crowdsale contract address */ event OnConvertContractSet(address indexed convertAddress); /** * @param token claimed token * @param owner who owns the contract * @param amount amount of the claimed token */ event OnClaimTokens(address indexed token, address indexed owner, uint256 amount); }
Transfer tokens from one address to another. Only callable by the convert contract. Used in the process of converting AORATGE to AORA. Will be called from convert contracts convert() function. _from address The address which you want to send tokens from _to address The address which you want to transfer to. Only 0x0 address, because of a need to prevent token recycling. _value uint256 the amount of tokens to be transferred/
function transferFrom( address _from, address _to, uint256 _value ) onlyConvert public returns (bool) { require(_value <= balances[_from]); require(_to == address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; }
7,290,000
pragma solidity ^0.4.17; import './Ownable.sol'; contract WhiteListAccess is Ownable { mapping (address => bool) whitelist; modifier onlyWhitelisted {require(whitelist[msg.sender]); _;} function isAddressWhiteList(address _address) public view returns (bool) { return whitelist[_address]; } /** * @dev Adds single address to whitelist. * @param trusted Address to be added to the whitelist */ function addToWhiteList(address trusted) external onlyOwner { whitelist[trusted] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param untrusted Address to be removed to the whitelist */ function removeFromWhiteList(address untrusted) external onlyOwner { require(whitelist[untrusted]); whitelist[untrusted] = false; } }
Adds single address to whitelist. trusted Address to be added to the whitelist/
function addToWhiteList(address trusted) external onlyOwner { whitelist[trusted] = true; }
5,490,041
./partial_match/1/0x44BFaa83cb8E4645d91A27De0866762Bbd63F2dE/sources/VaultXPStake.sol
A method for a stakeholder to remove a stake. _stake The size of the stake to be removed./Tax users 5%
function removeStake(uint256 _stake) public { stakes[msg.sender] = stakes[msg.sender].sub(_stake); if(stakes[msg.sender] == 0) removeStakeholder(msg.sender); _burn(msg.sender, _stake); }
2,596,281
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_759(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,454,472
// SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.0; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol'; import './interfaces/IToken.sol'; import './interfaces/IAuction.sol'; import './interfaces/IStaking.sol'; import './interfaces/ISubBalances.sol'; import './interfaces/IStakingV1.sol'; contract Staking is IStaking, Initializable, AccessControlUpgradeable { using SafeMathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /** Events */ event Stake( address indexed account, uint256 indexed sessionId, uint256 amount, uint256 start, uint256 end, uint256 shares ); event MaxShareUpgrade( address indexed account, uint256 indexed sessionId, uint256 amount, uint256 newAmount, uint256 shares, uint256 newShares, uint256 start, uint256 end ); event Unstake( address indexed account, uint256 indexed sessionId, uint256 amount, uint256 start, uint256 end, uint256 shares ); event MakePayout( uint256 indexed value, uint256 indexed sharesTotalSupply, uint256 indexed time ); event AccountRegistered( address indexed account, uint256 indexed totalShares ); event WithdrawLiquidDiv( address indexed account, address indexed tokenAddress, uint256 indexed interest ); /** Structs */ struct Payout { uint256 payout; uint256 sharesTotalSupply; } struct Session { uint256 amount; uint256 start; uint256 end; uint256 shares; uint256 firstPayout; uint256 lastPayout; bool withdrawn; uint256 payout; } struct Addresses { address mainToken; address auction; address subBalances; } Addresses public addresses; IStakingV1 public stakingV1; /** Roles */ bytes32 public constant MIGRATOR_ROLE = keccak256('MIGRATOR_ROLE'); bytes32 public constant EXTERNAL_STAKER_ROLE = keccak256('EXTERNAL_STAKER_ROLE'); bytes32 public constant MANAGER_ROLE = keccak256('MANAGER_ROLE'); /** Public Variables */ uint256 public shareRate; uint256 public sharesTotalSupply; uint256 public nextPayoutCall; uint256 public stepTimestamp; uint256 public startContract; uint256 public globalPayout; uint256 public globalPayin; uint256 public lastSessionId; uint256 public lastSessionIdV1; /** Mappings / Arrays */ mapping(address => mapping(uint256 => Session)) public sessionDataOf; mapping(address => uint256[]) public sessionsOf; Payout[] public payouts; /** Booleans */ bool public init_; uint256 public basePeriod; uint256 public totalStakedAmount; bool private maxShareEventActive; uint16 private maxShareMaxDays; uint256 private shareRateScalingFactor; uint256 internal totalVcaRegisteredShares; mapping(address => uint256) internal tokenPricePerShare; EnumerableSetUpgradeable.AddressSet internal divTokens; mapping(address => bool) internal isVcaRegistered; mapping(address => uint256) internal totalSharesOf; mapping(address => mapping(address => uint256)) internal deductBalances; bool internal paused; /* New variables must go below here. */ modifier onlyManager() { require(hasRole(MANAGER_ROLE, _msgSender()), 'Caller is not a manager'); _; } modifier onlyMigrator() { require( hasRole(MIGRATOR_ROLE, _msgSender()), 'Caller is not a migrator' ); _; } modifier onlyExternalStaker() { require( hasRole(EXTERNAL_STAKER_ROLE, _msgSender()), 'Caller is not a external staker' ); _; } modifier onlyAuction() { require(msg.sender == addresses.auction, 'Caller is not the auction'); _; } modifier pausable() { require( paused == false || hasRole(MIGRATOR_ROLE, _msgSender()), 'Contract is paused' ); _; } function initialize(address _manager, address _migrator) public initializer { _setupRole(MANAGER_ROLE, _manager); _setupRole(MIGRATOR_ROLE, _migrator); init_ = false; } function sessionsOf_(address account) external view returns (uint256[] memory) { return sessionsOf[account]; } function stake(uint256 amount, uint256 stakingDays) external pausable { require(stakingDays != 0, 'Staking: Staking days < 1'); require(stakingDays <= 5555, 'Staking: Staking days > 5555'); stakeInternal(amount, stakingDays, msg.sender); IToken(addresses.mainToken).burn(msg.sender, amount); } function externalStake( uint256 amount, uint256 stakingDays, address staker ) external override onlyExternalStaker pausable { require(stakingDays != 0, 'Staking: Staking days < 1'); require(stakingDays <= 5555, 'Staking: Staking days > 5555'); stakeInternal(amount, stakingDays, staker); } function stakeInternal( uint256 amount, uint256 stakingDays, address staker ) internal { if (now >= nextPayoutCall) makePayout(); if (isVcaRegistered[staker] == false) setTotalSharesOfAccountInternal(staker); uint256 start = now; uint256 end = now.add(stakingDays.mul(stepTimestamp)); lastSessionId = lastSessionId.add(1); stakeInternalCommon( lastSessionId, amount, start, end, stakingDays, payouts.length, staker ); } function _initPayout(address to, uint256 amount) internal { IToken(addresses.mainToken).mint(to, amount); globalPayout = globalPayout.add(amount); } function calculateStakingInterest( uint256 firstPayout, uint256 lastPayout, uint256 shares ) public view returns (uint256) { uint256 stakingInterest; uint256 lastIndex = MathUpgradeable.min(payouts.length, lastPayout); for (uint256 i = firstPayout; i < lastIndex; i++) { uint256 payout = payouts[i].payout.mul(shares).div(payouts[i].sharesTotalSupply); stakingInterest = stakingInterest.add(payout); } return stakingInterest; } function unstake(uint256 sessionId) external pausable { Session storage session = sessionDataOf[msg.sender][sessionId]; require( session.shares != 0 && session.withdrawn == false, 'Staking: Stake withdrawn or not set' ); uint256 actualEnd = now; uint256 amountOut = unstakeInternal(session, sessionId, actualEnd); // To account _initPayout(msg.sender, amountOut); } function unstakeV1(uint256 sessionId) external pausable { require(sessionId <= lastSessionIdV1, 'Staking: Invalid sessionId'); Session storage session = sessionDataOf[msg.sender][sessionId]; // Unstaked already require( session.shares == 0 && session.withdrawn == false, 'Staking: Stake withdrawn' ); ( uint256 amount, uint256 start, uint256 end, uint256 shares, uint256 firstPayout ) = stakingV1.sessionDataOf(msg.sender, sessionId); // Unstaked in v1 / doesn't exist require(shares != 0, 'Staking: Stake withdrawn or not set'); uint256 stakingDays = (end - start) / stepTimestamp; uint256 lastPayout = stakingDays + firstPayout; uint256 actualEnd = now; uint256 amountOut = unstakeV1Internal( sessionId, amount, start, end, actualEnd, shares, firstPayout, lastPayout, stakingDays ); // To account _initPayout(msg.sender, amountOut); } function getAmountOutAndPenalty( uint256 amount, uint256 start, uint256 end, uint256 stakingInterest ) public view returns (uint256, uint256) { uint256 stakingSeconds = end.sub(start); uint256 stakingDays = stakingSeconds.div(stepTimestamp); uint256 secondsStaked = now.sub(start); uint256 daysStaked = secondsStaked.div(stepTimestamp); uint256 amountAndInterest = amount.add(stakingInterest); // Early if (stakingDays > daysStaked) { uint256 payOutAmount = amountAndInterest.mul(secondsStaked).div(stakingSeconds); uint256 earlyUnstakePenalty = amountAndInterest.sub(payOutAmount); return (payOutAmount, earlyUnstakePenalty); // In time } else if (daysStaked < stakingDays.add(14)) { return (amountAndInterest, 0); // Late } else if (daysStaked < stakingDays.add(714)) { uint256 daysAfterStaking = daysStaked - stakingDays; uint256 payOutAmount = amountAndInterest.mul(uint256(714).sub(daysAfterStaking)).div( 700 ); uint256 lateUnstakePenalty = amountAndInterest.sub(payOutAmount); return (payOutAmount, lateUnstakePenalty); // Nothing } else { return (0, amountAndInterest); } } function makePayout() public { require(now >= nextPayoutCall, 'Staking: Wrong payout time'); uint256 payout = _getPayout(); payouts.push( Payout({payout: payout, sharesTotalSupply: sharesTotalSupply}) ); nextPayoutCall = nextPayoutCall.add(stepTimestamp); updateShareRate(payout); emit MakePayout(payout, sharesTotalSupply, now); } function readPayout() external view returns (uint256) { uint256 amountTokenInDay = IERC20Upgradeable(addresses.mainToken).balanceOf(address(this)); uint256 currentTokenTotalSupply = (IERC20Upgradeable(addresses.mainToken).totalSupply()).add( globalPayin ); uint256 inflation = uint256(8).mul(currentTokenTotalSupply.add(totalStakedAmount)).div( 36500 ); return amountTokenInDay.add(inflation); } function _getPayout() internal returns (uint256) { uint256 amountTokenInDay = IERC20Upgradeable(addresses.mainToken).balanceOf(address(this)); globalPayin = globalPayin.add(amountTokenInDay); if (globalPayin > globalPayout) { globalPayin = globalPayin.sub(globalPayout); globalPayout = 0; } else { globalPayin = 0; globalPayout = 0; } uint256 currentTokenTotalSupply = (IERC20Upgradeable(addresses.mainToken).totalSupply()).add( globalPayin ); IToken(addresses.mainToken).burn(address(this), amountTokenInDay); uint256 inflation = uint256(8).mul(currentTokenTotalSupply.add(totalStakedAmount)).div( 36500 ); globalPayin = globalPayin.add(inflation); return amountTokenInDay.add(inflation); } function _getStakersSharesAmount( uint256 amount, uint256 start, uint256 end ) internal view returns (uint256) { uint256 stakingDays = (end.sub(start)).div(stepTimestamp); uint256 numerator = amount.mul(uint256(1819).add(stakingDays)); uint256 denominator = uint256(1820).mul(shareRate); return (numerator).mul(1e18).div(denominator); } function _getShareRate( uint256 amount, uint256 shares, uint256 start, uint256 end, uint256 stakingInterest ) internal view returns (uint256) { uint256 stakingDays = (end.sub(start)).div(stepTimestamp); uint256 numerator = (amount.add(stakingInterest)).mul(uint256(1819).add(stakingDays)); uint256 denominator = uint256(1820).mul(shares); return (numerator).mul(1e18).div(denominator); } function restake( uint256 sessionId, uint256 stakingDays, uint256 topup ) external pausable { require(stakingDays != 0, 'Staking: Staking days < 1'); require(stakingDays <= 5555, 'Staking: Staking days > 5555'); Session storage session = sessionDataOf[msg.sender][sessionId]; require( session.shares != 0 && session.withdrawn == false, 'Staking: Stake withdrawn/invalid' ); uint256 actualEnd = now; require(session.end <= actualEnd, 'Staking: Stake not mature'); uint256 amountOut = unstakeInternal(session, sessionId, actualEnd); if (topup != 0) { IToken(addresses.mainToken).burn(msg.sender, topup); amountOut = amountOut.add(topup); } stakeInternal(amountOut, stakingDays, msg.sender); } function restakeV1( uint256 sessionId, uint256 stakingDays, uint256 topup ) external pausable { require(sessionId <= lastSessionIdV1, 'Staking: Invalid sessionId'); require(stakingDays != 0, 'Staking: Staking days < 1'); require(stakingDays <= 5555, 'Staking: Staking days > 5555'); Session storage session = sessionDataOf[msg.sender][sessionId]; require( session.shares == 0 && session.withdrawn == false, 'Staking: Stake withdrawn' ); ( uint256 amount, uint256 start, uint256 end, uint256 shares, uint256 firstPayout ) = stakingV1.sessionDataOf(msg.sender, sessionId); // Unstaked in v1 / doesn't exist require(shares != 0, 'Staking: Stake withdrawn'); uint256 actualEnd = now; require(end <= actualEnd, 'Staking: Stake not mature'); uint256 sessionStakingDays = (end - start) / stepTimestamp; uint256 lastPayout = sessionStakingDays + firstPayout; uint256 amountOut = unstakeV1Internal( sessionId, amount, start, end, actualEnd, shares, firstPayout, lastPayout, sessionStakingDays ); if (topup != 0) { IToken(addresses.mainToken).burn(msg.sender, topup); amountOut = amountOut.add(topup); } stakeInternal(amountOut, stakingDays, msg.sender); } function unstakeInternal( Session storage session, uint256 sessionId, uint256 actualEnd ) internal returns (uint256) { uint256 amountOut = unstakeInternalCommon( sessionId, session.amount, session.start, session.end, actualEnd, session.shares, session.firstPayout, session.lastPayout ); uint256 stakingDays = (session.end - session.start) / stepTimestamp; if (stakingDays >= basePeriod) { ISubBalances(addresses.subBalances).callOutcomeStakerTrigger( sessionId, session.start, session.end, actualEnd, session.shares ); } session.end = actualEnd; session.withdrawn = true; session.payout = amountOut; return amountOut; } function unstakeV1Internal( uint256 sessionId, uint256 amount, uint256 start, uint256 end, uint256 actualEnd, uint256 shares, uint256 firstPayout, uint256 lastPayout, uint256 stakingDays ) internal returns (uint256) { uint256 amountOut = unstakeInternalCommon( sessionId, amount, start, end, actualEnd, shares, firstPayout, lastPayout ); if (stakingDays >= basePeriod) { ISubBalances(addresses.subBalances).callOutcomeStakerTriggerV1( msg.sender, sessionId, start, end, actualEnd, shares ); } sessionDataOf[msg.sender][sessionId] = Session({ amount: amount, start: start, end: actualEnd, shares: shares, firstPayout: firstPayout, lastPayout: lastPayout, withdrawn: true, payout: amountOut }); sessionsOf[msg.sender].push(sessionId); return amountOut; } function unstakeInternalCommon( uint256 sessionId, uint256 amount, uint256 start, uint256 end, uint256 actualEnd, uint256 shares, uint256 firstPayout, uint256 lastPayout ) internal returns (uint256) { if (now >= nextPayoutCall) makePayout(); if (isVcaRegistered[msg.sender] == false) setTotalSharesOfAccountInternal(msg.sender); uint256 stakingInterest = calculateStakingInterest(firstPayout, lastPayout, shares); sharesTotalSupply = sharesTotalSupply.sub(shares); totalStakedAmount = totalStakedAmount.sub(amount); totalVcaRegisteredShares = totalVcaRegisteredShares.sub(shares); uint256 oldTotalSharesOf = totalSharesOf[msg.sender]; totalSharesOf[msg.sender] = totalSharesOf[msg.sender].sub(shares); rebalance(msg.sender, oldTotalSharesOf); (uint256 amountOut, uint256 penalty) = getAmountOutAndPenalty(amount, start, end, stakingInterest); // To auction if (penalty != 0) { _initPayout(addresses.auction, penalty); IAuction(addresses.auction).callIncomeDailyTokensTrigger(penalty); } emit Unstake( msg.sender, sessionId, amountOut, start, actualEnd, shares ); return amountOut; } function stakeInternalCommon( uint256 sessionId, uint256 amount, uint256 start, uint256 end, uint256 stakingDays, uint256 firstPayout, address staker ) internal { uint256 shares = _getStakersSharesAmount(amount, start, end); sharesTotalSupply = sharesTotalSupply.add(shares); totalStakedAmount = totalStakedAmount.add(amount); totalVcaRegisteredShares = totalVcaRegisteredShares.add(shares); uint256 oldTotalSharesOf = totalSharesOf[staker]; totalSharesOf[staker] = totalSharesOf[staker].add(shares); rebalance(staker, oldTotalSharesOf); sessionDataOf[staker][sessionId] = Session({ amount: amount, start: start, end: end, shares: shares, firstPayout: firstPayout, lastPayout: firstPayout + stakingDays, withdrawn: false, payout: 0 }); sessionsOf[staker].push(sessionId); if (stakingDays >= basePeriod) { ISubBalances(addresses.subBalances).callIncomeStakerTrigger( staker, sessionId, start, end, shares ); } emit Stake(staker, sessionId, amount, start, end, shares); } function withdrawDivToken(address tokenAddress) external { uint256 tokenInterestEarned = getTokenInterestEarnedInternal(msg.sender, tokenAddress); /** 0xFF... is our ethereum placeholder address */ if ( tokenAddress != address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF) ) { IERC20Upgradeable(tokenAddress).transfer( msg.sender, tokenInterestEarned ); } else { msg.sender.transfer(tokenInterestEarned); } deductBalances[msg.sender][tokenAddress] = totalSharesOf[msg.sender] .mul(tokenPricePerShare[tokenAddress]); emit WithdrawLiquidDiv(msg.sender, tokenAddress, tokenInterestEarned); } function getTokenInterestEarned( address accountAddress, address tokenAddress ) external view returns (uint256) { return getTokenInterestEarnedInternal(accountAddress, tokenAddress); } function getTokenInterestEarnedInternal( address accountAddress, address tokenAddress ) internal view returns (uint256) { return totalSharesOf[accountAddress] .mul(tokenPricePerShare[tokenAddress]) .sub(deductBalances[accountAddress][tokenAddress]) .div(10**36); } function rebalance(address staker, uint256 oldTotalSharesOf) internal { for (uint8 i = 0; i < divTokens.length(); i++) { uint256 tokenInterestEarned = oldTotalSharesOf.mul(tokenPricePerShare[divTokens.at(i)]).sub( deductBalances[staker][divTokens.at(i)] ); deductBalances[staker][divTokens.at(i)] = totalSharesOf[staker] .mul(tokenPricePerShare[divTokens.at(i)]) .sub(tokenInterestEarned); } } function setTotalSharesOfAccountInternal(address account) internal pausable { require( isVcaRegistered[account] == false || hasRole(MIGRATOR_ROLE, msg.sender), 'STAKING: Account already registered.' ); uint256 totalShares; uint256[] storage sessionsOfAccount = sessionsOf[account]; for (uint256 i = 0; i < sessionsOfAccount.length; i++) { if (sessionDataOf[account][sessionsOfAccount[i]].withdrawn) continue; totalShares = totalShares.add( sessionDataOf[account][sessionsOfAccount[i]].shares ); } uint256[] memory v1SessionsOfAccount = stakingV1.sessionsOf_(account); for (uint256 i = 0; i < v1SessionsOfAccount.length; i++) { if (sessionDataOf[account][v1SessionsOfAccount[i]].shares != 0) continue; if (v1SessionsOfAccount[i] > lastSessionIdV1) continue; ( uint256 amount, uint256 start, uint256 end, uint256 shares, uint256 firstPayout ) = stakingV1.sessionDataOf(account, v1SessionsOfAccount[i]); (amount); (start); (end); (firstPayout); if (shares == 0) continue; totalShares = totalShares.add(shares); } isVcaRegistered[account] = true; if (totalShares != 0) { totalSharesOf[account] = totalShares; totalVcaRegisteredShares = totalVcaRegisteredShares.add( totalShares ); for (uint256 i = 0; i < divTokens.length(); i++) { deductBalances[account][divTokens.at(i)] = totalShares.mul( tokenPricePerShare[divTokens.at(i)] ); } } emit AccountRegistered(account, totalShares); } function setTotalSharesOfAccount(address _address) external { setTotalSharesOfAccountInternal(_address); } function updateTokenPricePerShare( address payable bidderAddress, address payable originAddress, address tokenAddress, uint256 amountBought ) external payable override onlyAuction { // uint256 amountForBidder = amountBought.mul(10526315789473685).div(1e17); uint256 amountForOrigin = amountBought.mul(5).div(100); uint256 amountForBidder = amountBought.mul(10).div(100); uint256 amountForDivs = amountBought.sub(amountForOrigin).sub(amountForBidder); if ( tokenAddress != address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF) ) { IERC20Upgradeable(tokenAddress).transfer( bidderAddress, amountForBidder ); IERC20Upgradeable(tokenAddress).transfer( originAddress, amountForOrigin ); } else { bidderAddress.transfer(amountForBidder); originAddress.transfer(amountForOrigin); } tokenPricePerShare[tokenAddress] = tokenPricePerShare[tokenAddress].add( amountForDivs.mul(10**36).div(totalVcaRegisteredShares) ); } function addDivToken(address tokenAddress) external override onlyAuction { if (!divTokens.contains(tokenAddress)) { divTokens.add(tokenAddress); } } function updateShareRate(uint256 _payout) internal { uint256 currentTokenTotalSupply = IERC20Upgradeable(addresses.mainToken).totalSupply(); uint256 growthFactor = _payout.mul(1e18).div( currentTokenTotalSupply + totalStakedAmount + 1 ); if (shareRateScalingFactor == 0) { shareRateScalingFactor = 1; } shareRate = shareRate .mul(1e18 + shareRateScalingFactor.mul(growthFactor)) .div(1e18); } function setShareRateScalingFactor(uint256 _scalingFactor) external onlyManager { shareRateScalingFactor = _scalingFactor; } function maxShare(uint256 sessionId) external pausable { Session storage session = sessionDataOf[msg.sender][sessionId]; require( session.shares != 0 && session.withdrawn == false, 'STAKING: Stake withdrawn or not set' ); ( uint256 newStart, uint256 newEnd, uint256 newAmount, uint256 newShares ) = maxShareUpgrade( session.firstPayout, session.lastPayout, session.shares, session.amount ); uint256 stakingDays = (session.end - session.start) / stepTimestamp; if (stakingDays >= basePeriod) { ISubBalances(addresses.subBalances).createMaxShareSession( sessionId, newStart, newEnd, newShares, session.shares ); } else { ISubBalances(addresses.subBalances).callIncomeStakerTrigger( msg.sender, sessionId, newStart, newEnd, newShares ); } maxShareInternal( sessionId, session.shares, newShares, session.amount, newAmount, newStart, newEnd ); sessionDataOf[msg.sender][sessionId].amount = newAmount; sessionDataOf[msg.sender][sessionId].end = newEnd; sessionDataOf[msg.sender][sessionId].start = newStart; sessionDataOf[msg.sender][sessionId].shares = newShares; sessionDataOf[msg.sender][sessionId].firstPayout = payouts.length; sessionDataOf[msg.sender][sessionId].lastPayout = payouts.length + 5555; } function maxShareV1(uint256 sessionId) external pausable { require(sessionId <= lastSessionIdV1, 'STAKING: Invalid sessionId'); Session storage session = sessionDataOf[msg.sender][sessionId]; require( session.shares == 0 && session.withdrawn == false, 'STAKING: Stake withdrawn' ); ( uint256 amount, uint256 start, uint256 end, uint256 shares, uint256 firstPayout ) = stakingV1.sessionDataOf(msg.sender, sessionId); uint256 stakingDays = (end - start) / stepTimestamp; uint256 lastPayout = stakingDays + firstPayout; ( uint256 newStart, uint256 newEnd, uint256 newAmount, uint256 newShares ) = maxShareUpgrade(firstPayout, lastPayout, shares, amount); if (stakingDays >= basePeriod) { ISubBalances(addresses.subBalances).createMaxShareSessionV1( msg.sender, sessionId, newStart, newEnd, newShares, // new shares shares // old shares ); } else { ISubBalances(addresses.subBalances).callIncomeStakerTrigger( msg.sender, sessionId, newStart, newEnd, newShares ); } sessionDataOf[msg.sender][sessionId] = Session({ amount: newAmount, start: newStart, end: newEnd, shares: newShares, firstPayout: payouts.length, lastPayout: payouts.length + 5555, withdrawn: false, payout: 0 }); sessionsOf[msg.sender].push(sessionId); maxShareInternal( sessionId, shares, newShares, amount, newAmount, newStart, newEnd ); } function maxShareUpgrade( uint256 firstPayout, uint256 lastPayout, uint256 shares, uint256 amount ) internal view returns ( uint256, uint256, uint256, uint256 ) { require( maxShareEventActive == true, 'STAKING: Max Share event is not active' ); require( lastPayout - firstPayout <= maxShareMaxDays, 'STAKING: Max Share Upgrade - Stake must be less then max share max days' ); uint256 stakingInterest = calculateStakingInterest(firstPayout, lastPayout, shares); uint256 newStart = now; uint256 newEnd = newStart + (stepTimestamp * 5555); uint256 newAmount = stakingInterest + amount; uint256 newShares = _getStakersSharesAmount(newAmount, newStart, newEnd); require( newShares > shares, 'STAKING: New shares are not greater then previous shares' ); return (newStart, newEnd, newAmount, newShares); } function maxShareInternal( uint256 sessionId, uint256 oldShares, uint256 newShares, uint256 oldAmount, uint256 newAmount, uint256 newStart, uint256 newEnd ) internal { if (now >= nextPayoutCall) makePayout(); if (isVcaRegistered[msg.sender] == false) setTotalSharesOfAccountInternal(msg.sender); sharesTotalSupply = sharesTotalSupply.add(newShares - oldShares); totalStakedAmount = totalStakedAmount.add(newAmount - oldAmount); totalVcaRegisteredShares = totalVcaRegisteredShares.add( newShares - oldShares ); uint256 oldTotalSharesOf = totalSharesOf[msg.sender]; totalSharesOf[msg.sender] = totalSharesOf[msg.sender].add( newShares - oldShares ); rebalance(msg.sender, oldTotalSharesOf); emit MaxShareUpgrade( msg.sender, sessionId, oldAmount, newAmount, oldShares, newShares, newStart, newEnd ); } // stepTimestamp // startContract function calculateStepsFromStart() public view returns (uint256) { return now.sub(startContract).div(stepTimestamp); } /** Set Max Shares */ function setMaxShareEventActive(bool _active) external onlyManager { maxShareEventActive = _active; } function getMaxShareEventActive() external view returns (bool) { return maxShareEventActive; } function setMaxShareMaxDays(uint16 _maxShareMaxDays) external onlyManager { maxShareMaxDays = _maxShareMaxDays; } function setTotalVcaRegisteredShares(uint256 _shares) external onlyMigrator { totalVcaRegisteredShares = _shares; } function setPaused(bool _paused) external { require( hasRole(MIGRATOR_ROLE, msg.sender) || hasRole(MANAGER_ROLE, msg.sender), 'STAKING: User must be manager or migrator' ); paused = _paused; } function getPaused() external view returns (bool) { return paused; } function getMaxShareMaxDays() external view returns (uint16) { return maxShareMaxDays; } /** Roles management - only for multi sig address */ function setupRole(bytes32 role, address account) external onlyManager { _setupRole(role, account); } function getDivTokens() external view returns (address[] memory) { address[] memory divTokenAddresses = new address[](divTokens.length()); for (uint8 i = 0; i < divTokens.length(); i++) { divTokenAddresses[i] = divTokens.at(i); } return divTokenAddresses; } function getTotalSharesOf(address account) external view returns (uint256) { return totalSharesOf[account]; } function getTotalVcaRegisteredShares() external view returns (uint256) { return totalVcaRegisteredShares; } } // 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 pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../GSN/ContextUpgradeable.sol"; import "../proxy/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, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // 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; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IToken { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IAuction { function callIncomeDailyTokensTrigger(uint256 amount) external; function callIncomeWeeklyTokensTrigger(uint256 amount) external; function addReservesToAuction(uint256 daysInFuture, uint256 amount) external returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IStaking { function externalStake( uint256 amount, uint256 stakingDays, address staker ) external; function updateTokenPricePerShare( address payable bidderAddress, address payable originAddress, address tokenAddress, uint256 amountBought ) external payable; function addDivToken(address tokenAddress) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface ISubBalances { function callIncomeStakerTrigger( address staker, uint256 sessionId, uint256 start, uint256 end, uint256 shares ) external; function callOutcomeStakerTrigger( uint256 sessionId, uint256 start, uint256 end, uint256 actualEnd, uint256 shares ) external; function callOutcomeStakerTriggerV1( address staker, uint256 sessionId, uint256 start, uint256 end, uint256 actualEnd, uint256 shares ) external; function createMaxShareSession( uint256 sessionId, uint256 start, uint256 end, uint256 newShares, uint256 oldShares ) external; function createMaxShareSessionV1( address staker, uint256 sessionId, uint256 start, uint256 end, uint256 newShares, uint256 oldShares ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IStakingV1 { function sessionDataOf(address, uint256) external view returns (uint256, uint256, uint256, uint256, uint256); function sessionsOf_(address) external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // 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; } }
uint256 amountForBidder = amountBought.mul(10526315789473685).div(1e17);
function updateTokenPricePerShare( address payable bidderAddress, address payable originAddress, address tokenAddress, uint256 amountBought ) external payable override onlyAuction { uint256 amountForOrigin = amountBought.mul(5).div(100); uint256 amountForBidder = amountBought.mul(10).div(100); uint256 amountForDivs = amountBought.sub(amountForOrigin).sub(amountForBidder); if ( tokenAddress != address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF) ) { IERC20Upgradeable(tokenAddress).transfer( bidderAddress, amountForBidder ); IERC20Upgradeable(tokenAddress).transfer( originAddress, amountForOrigin ); bidderAddress.transfer(amountForBidder); originAddress.transfer(amountForOrigin); } tokenPricePerShare[tokenAddress] = tokenPricePerShare[tokenAddress].add( amountForDivs.mul(10**36).div(totalVcaRegisteredShares) ); }
1,552,342
//Address: 0xca6bea8e144b0a6aebbb412e6ad0e7ff1959235e //Contract name: EtherConsole //Balance: 0 Ether //Verification Date: 2/24/2018 //Transacion Count: 19 // CODE STARTS HERE pragma solidity ^0.4.18; /// Item23s :3 /// @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 approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); } contract EtherConsole is ERC721 { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new item23 comes into existence. event Birth(uint256 tokenId, string name, address owner); /// @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ //uint256 private startingPrice = 0.001 ether; /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CrypoConsoles"; // solhint-disable-line string public constant SYMBOL = "CryptoConsole"; // solhint-disable-line /*** STORAGE ***/ /// @dev A mapping from item23 IDs to the address that owns them. All item23s have /// some valid owner address. mapping (uint256 => address) public item23IndexToOwner; // @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 Item23IDs to an address that has been approved to call /// transferFrom(). Each Item23 can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public item23IndexToApproved; // @dev A mapping from Item23IDs to the price of the token. mapping (uint256 => uint256) private item23IndexToPrice; /// @dev A mapping from Item23IDs to the previpus price of the token. Used /// to calculate price delta for payouts mapping (uint256 => uint256) private item23IndexToPreviousPrice; // @dev A mapping from item23Id to the 7 last owners. mapping (uint256 => address[5]) private item23IndexToPreviousOwners; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; /*** DATATYPES ***/ struct Item23 { string name; } Item23[] private item23s; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** CONSTRUCTOR ***/ function EtherConsole() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /*** 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(_owns(msg.sender, _tokenId)); item23IndexToApproved[_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]; } /// @dev Creates a new Item23 with the given name. function createContractItem23(string _name , string _startingP ) public onlyCOO { _createItem23(_name, address(this), stringToUint( _startingP)); } function stringToUint(string _amount) internal constant returns (uint result) { bytes memory b = bytes(_amount); uint i; uint counterBeforeDot; uint counterAfterDot; result = 0; uint totNum = b.length; totNum--; bool hasDot = false; for (i = 0; i < b.length; i++) { uint c = uint(b[i]); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); counterBeforeDot ++; totNum--; } if(c == 46){ hasDot = true; break; } } if(hasDot) { for (uint j = counterBeforeDot + 1; j < 18; j++) { uint m = uint(b[j]); if (m >= 48 && m <= 57) { result = result * 10 + (m - 48); counterAfterDot ++; totNum--; } if(totNum == 0){ break; } } } if(counterAfterDot < 18){ uint addNum = 18 - counterAfterDot; uint multuply = 10 ** addNum; return result = result * multuply; } return result; } /// @notice Returns all the relevant information about a specific item23. /// @param _tokenId The tokenId of the item23 of interest. function getItem23(uint256 _tokenId) public view returns ( string item23Name, uint256 sellingPrice, address owner, uint256 previousPrice, address[5] previousOwners ) { Item23 storage item23 = item23s[_tokenId]; item23Name = item23.name; sellingPrice = item23IndexToPrice[_tokenId]; owner = item23IndexToOwner[_tokenId]; previousPrice = item23IndexToPreviousPrice[_tokenId]; previousOwners = item23IndexToPreviousOwners[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// 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) { owner = item23IndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = item23IndexToOwner[_tokenId]; address newOwner = msg.sender; address[5] storage previousOwners = item23IndexToPreviousOwners[_tokenId]; uint256 sellingPrice = item23IndexToPrice[_tokenId]; uint256 previousPrice = item23IndexToPreviousPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 priceDelta = SafeMath.sub(sellingPrice, previousPrice); uint256 ownerPayout = SafeMath.add(previousPrice, SafeMath.mul(SafeMath.div(priceDelta, 100), 40)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); item23IndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100); item23IndexToPreviousPrice[_tokenId] = sellingPrice; uint256 strangePrice = uint256(SafeMath.mul(SafeMath.div(priceDelta, 100), 10)); uint256 strangePrice2 = uint256(0); // Pay previous tokenOwner if owner is not contract // and if previous price is not 0 if (oldOwner != address(this)) { // old owner gets entire initial payment back oldOwner.transfer(ownerPayout); } else { strangePrice = SafeMath.add(ownerPayout, strangePrice); } // Next distribute payout Total among previous Owners for (uint i = 0; i < 5; i++) { if (previousOwners[i] != address(this)) { strangePrice2+=uint256(SafeMath.mul(SafeMath.div(priceDelta, 100), 10)); } else { strangePrice = SafeMath.add(strangePrice, uint256(SafeMath.mul(SafeMath.div(priceDelta, 100), 10))); } } ceoAddress.transfer(strangePrice+strangePrice2); //ceoAddress.transfer(strangePrice2); _transfer(oldOwner, newOwner, _tokenId); //TokenSold(_tokenId, sellingPrice, item23IndexToPrice[_tokenId], oldOwner, newOwner, item23s[_tokenId].name); msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return item23IndexToPrice[_tokenId]; } /// @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) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @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 { address newOwner = msg.sender; address oldOwner = item23IndexToOwner[_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 item23 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 Item23s array looking for item23s 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) public 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 totalItem23s = totalSupply(); uint256 resultIndex = 0; uint256 item23Id; for (item23Id = 0; item23Id <= totalItem23s; item23Id++) { if (item23IndexToOwner[item23Id] == _owner) { result[resultIndex] = item23Id; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return item23s.length; } /// 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(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _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(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return item23IndexToApproved[_tokenId] == _to; } /// For creating Item23 function _createItem23(string _name, address _owner, uint256 _price) private { Item23 memory _item23 = Item23({ name: _name }); uint256 newItem23Id = item23s.push(_item23) - 1; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newItem23Id == uint256(uint32(newItem23Id))); Birth(newItem23Id, _name, _owner); item23IndexToPrice[newItem23Id] = _price; item23IndexToPreviousPrice[newItem23Id] = 0; item23IndexToPreviousOwners[newItem23Id] = [address(this), address(this), address(this), address(this)]; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newItem23Id); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == item23IndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @dev Assigns ownership of a specific Item23 to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of item23s is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership item23IndexToOwner[_tokenId] = _to; // When creating new item23s _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete item23IndexToApproved[_tokenId]; } // Update the item23IndexToPreviousOwners item23IndexToPreviousOwners[_tokenId][4]=item23IndexToPreviousOwners[_tokenId][3]; item23IndexToPreviousOwners[_tokenId][3]=item23IndexToPreviousOwners[_tokenId][2]; item23IndexToPreviousOwners[_tokenId][2]=item23IndexToPreviousOwners[_tokenId][1]; item23IndexToPreviousOwners[_tokenId][1]=item23IndexToPreviousOwners[_tokenId][0]; // the _from address for creation is 0, so instead set it to the contract address if (_from != address(0)) { item23IndexToPreviousOwners[_tokenId][0]=_from; } else { item23IndexToPreviousOwners[_tokenId][0]=address(this); } // Emit the transfer event. Transfer(_from, _to, _tokenId); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
For querying owner of token _tokenId The tokenID for owner inquiry Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = item23IndexToOwner[_tokenId]; require(owner != address(0)); }
15,808,961
pragma solidity >=0.5.0 <0.6.0; import "./AltBn128.sol"; import "./LSAG.sol"; contract Heiswap { // Events event Deposited(address, uint256 etherAmount, uint256 idx); // Default Relayer Address address payable public relayerAddress = 0x20a4b066fc4F70b0245B43e2F5a781C6d1030748; // Maximum number of participants in a ring uint256 constant ringMaxParticipants = 6; struct Ring { // Ring created on block number X uint256 createdBlockNumber; // Ring hash will be available once // there is 5 participants in the ring // TODO: Manually call the function "closeRing" bytes32 ringHash; // In a ring, everyone deposits // the same amount of ETH. Otherwise // the sender and receiver can be identified // which defeats the whole purpose of this // application uint256 amountDeposited; // Number of participants who've deposited uint8 dParticipantsNo; // The Public Key (stealth addresses) mapping (uint256 => uint256[2]) publicKeys; // Number of participants who've withdrawn uint8 wParticipantsNo; // Key Images of participants who have withdrawn // Used to determine if a participant is trying to // double withdraw mapping (uint256 => uint256[2]) keyImages; } // Fixed amounts allowed to be inserted into the rings uint256[10] allowedAmounts = [ 1 ether, 2 ether, 4 ether, 8 ether, 16 ether, 32 ether, 64 ether ]; // Mimics dynamic 'lists' // allowedAmount => numberOfRings (in the current amount) mapping(uint256 => uint256) ringsNo; // allowedAmount => ringIndex => Ring mapping (uint256 => mapping(uint256 => Ring)) rings; function deposit(uint256[2] memory publicKey) public payable { // Get amount sent uint256 receivedEther = floorEtherAndCheck(msg.value); // Returns non-exact value ETH // Gets the value of the first decimal place // in ETH deposited // i.e. 2.1 will give 1, 2.6 will give 6 // if it's greater than 1, then refund the // amounts (we'll count 0.1 ETH as a donation to our relayer ;)) uint256 etherDecimalVal = (msg.value / (1 ether / 10)) % 10; if (etherDecimalVal > 1) { uint256 refundEtherDecimalVal = (etherDecimalVal - 1) * (1 ether / 10); relayerAddress.transfer(1 ether / 10); msg.sender.transfer(refundEtherDecimalVal); } // Gets the current ring for the amounts uint256 curIndex = ringsNo[receivedEther]; Ring storage ring = rings[receivedEther][curIndex]; if (!AltBn128.onCurve(uint256(publicKey[0]), uint256(publicKey[1]))) { revert("Public Key no on Curve"); } // Make sure that public key (stealth address) // isn't already in there for (uint8 i = 0; i < ring.dParticipantsNo; i++) { if (ring.publicKeys[i][0] == publicKey[0] && ring.publicKeys[i][1] == publicKey[1]) { revert("Address already in current Ring"); } } // If its a new ring // set createdBlockNum size if (ring.dParticipantsNo == 0) { ring.createdBlockNumber = block.number - 1; } // Update ring params ring.publicKeys[ring.dParticipantsNo] = publicKey; ring.dParticipantsNo++; ring.amountDeposited += receivedEther; // Create new ring if current ring has exceeded number of participants if (ring.dParticipantsNo >= ringMaxParticipants) { // Set ringHash ring.ringHash = createRingHash(receivedEther / (1 ether), curIndex); // Add new Ring pool ringsNo[receivedEther] += 1; } // Broadcast Event emit Deposited(msg.sender, receivedEther, curIndex); } // User can only withdraw if the ring is closed // NOTE: Convert to ether // i.e. there is a ringHash function withdraw( address payable receiver, uint256 amountEther, uint256 index, uint256 c0, uint256[2] memory keyImage, uint256[] memory s ) public { uint i; uint256 startGas = gasleft(); // Get amount sent in whole number uint256 withdrawEther = floorEtherAndCheck(amountEther * 1 ether); // Gets the current ring, given the amount and idx Ring storage ring = rings[withdrawEther][index]; if (receiver == 0x0000000000000000000000000000000000000000) { revert("No zero address receiver"); } // If everyone has withdrawn if (ring.wParticipantsNo >= ringMaxParticipants) { revert("All funds from current Ring has been withdrawn"); } // Ring needs to be closed first if (ring.ringHash == bytes32(0x00)) { revert("Ring isn't closed"); } // Convert public key to dynamic array // Based on number of people who have // deposited uint256[2][] memory publicKeys = new uint256[2][](ring.dParticipantsNo); for (i = 0; i < ring.dParticipantsNo; i++) { publicKeys[i] = [ uint256(ring.publicKeys[uint8(i)][0]), uint256(ring.publicKeys[uint8(i)][1]) ]; } // Attempts to verify ring signature bool signatureVerified = LSAG.verify( abi.encodePacked(ring.ringHash, receiver), // Convert to bytes c0, keyImage, s, publicKeys ); if (!signatureVerified) { revert("Invalid signature"); } // Checks if Key Image has been used // AKA No double withdraw for (i = 0; i < ring.wParticipantsNo; i++) { if (ring.keyImages[uint8(i)][0] == keyImage[0] && ring.keyImages[uint8(i)][1] == keyImage[1]) { revert("Signature has been used!"); } } // Otherwise adds key image to the current key image // And adjusts params accordingly ring.keyImages[ring.wParticipantsNo] = keyImage; ring.wParticipantsNo += 1; // Send ETH to receiver // Calculate gasUsage fees uint256 gasUsed = (startGas - gasleft()) * tx.gasprice; // Calculate relayer fees (1.33%) uint256 relayerFees = (withdrawEther / 75); // Total fees uint256 fees = gasUsed + relayerFees; // Relayer gets compensated msg.sender.transfer(fees); // Reciever then gets the remaining ETH receiver.transfer(withdrawEther - fees); } /* Helper functions */ // TODO: Use safemath library // Creates ring hash (used for signing) function createRingHash(uint256 amountEther, uint256 index) internal view returns (bytes32) { uint256[2][ringMaxParticipants] memory publicKeys; uint256 receivedEther = floorEtherAndCheck(amountEther * 1 ether); Ring storage r = rings[receivedEther][index]; for (uint8 i = 0; i < ringMaxParticipants; i++) { publicKeys[i] = r.publicKeys[i]; } bytes memory b = abi.encodePacked( blockhash(block.number - 1), r.createdBlockNumber, r.amountDeposited, r.dParticipantsNo, publicKeys ); return keccak256(b); } // Gets ring hash needed to generate signature function getRingHash(uint256 amountEther, uint256 index) public view returns (bytes memory) { uint256 receivedEther = floorEtherAndCheck(amountEther * 1 ether); Ring memory r = rings[receivedEther][index]; // If the ringhash hasn't been closed // return the hash needed to close the // ring if (r.ringHash == bytes32(0x00)) { return abi.encodePacked("closeRing", receivedEther, index); } return abi.encodePacked(r.ringHash); } // Gets all addresses in a Ring // Converting to Bytes32 cause web3.js has a bug that doesn't convert // BigNum correctly.... function getPublicKeys(uint256 amountEther, uint256 index) public view returns (bytes32[2][ringMaxParticipants] memory) { uint256 receivedEther = floorEtherAndCheck(amountEther * 1 ether); bytes32[2][ringMaxParticipants] memory publicKeys; for (uint i = 0; i < ringMaxParticipants; i++) { publicKeys[i][0] = bytes32(rings[receivedEther][index].publicKeys[i][0]); publicKeys[i][1] = bytes32(rings[receivedEther][index].publicKeys[i][1]); } return publicKeys; } // Gets number of participants who // have deposited and withdrawn // ret: (dParticipants, wParticipants) function getParticipants(uint256 amountEther, uint256 index) public view returns (uint8, uint8) { uint256 receivedEther = floorEtherAndCheck(amountEther * 1 ether); Ring memory r = rings[receivedEther][index]; return (r.dParticipantsNo, r.wParticipantsNo); } // Gets the max nunmber of ring participants function getRingMaxParticipants() public pure returns (uint256) { return ringMaxParticipants; } // Gets the current ring index // for the given amount of ether // Used to estimate the current idx for better UX function getCurrentRingIdx(uint256 amountEther) public view returns (uint256) { uint256 receivedEther = floorEtherAndCheck(amountEther * 1 ether); return ringsNo[receivedEther]; } // Floors the current ether values // Makes sure the values needs to in `allowedAmounts` function floorEtherAndCheck(uint256 receivedAmount) internal view returns (uint256) { uint256 i; bool allowed = false; // Floors received ether uint256 receivedEther = (receivedAmount / 1 ether) * 1 ether; for (i = 0; i < 10; i ++) { if (allowedAmounts[i] == receivedEther) { allowed = true; } if (allowed) { break; } } // Revert if ETH sent isn't in the allowed fixed amounts require(allowed, "Only ETH values of 1, 2, 4, 6, 8 ... 32 are allowed"); return receivedEther; } }
Floors the current ether values Makes sure the values needs to in `allowedAmounts` Floors received ether
function floorEtherAndCheck(uint256 receivedAmount) internal view returns (uint256) { uint256 i; bool allowed = false; uint256 receivedEther = (receivedAmount / 1 ether) * 1 ether; for (i = 0; i < 10; i ++) { if (allowedAmounts[i] == receivedEther) { allowed = true; } if (allowed) { break; } } return receivedEther; }
12,901,990
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // 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; } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol 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; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ 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; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.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 {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Capped.sol pragma solidity ^0.6.0; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20CappedUpgradeSafe is Initializable, ERC20UpgradeSafe { 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; } // File: contracts/IERC20VoteableUpgradeSafe.sol pragma solidity 0.6.12; interface IERC20VoteableUpgradeSafe { function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256); } // File: contracts/ERC20VoteableUpgradeSafe.sol pragma solidity 0.6.12; abstract contract ERC20VoteableUpgradeSafe is ERC20UpgradeSafe, IERC20VoteableUpgradeSafe { struct Checkpoint { uint256 fromBlock; uint256 votes; } event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); bytes32 public constant DELEGATION_TYPEHASH = keccak256( "Delegation(address delegatee,uint256 nonce,uint256 expiry)" ); bytes32 public constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); mapping(address => address) _delegates; mapping(address => mapping(uint256 => Checkpoint)) public _checkpoints; mapping(address => uint256) public _numCheckpoints; mapping(address => uint256) public _nonces; /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit( address owner, address spender, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { uint256 amount; bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), _getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, rawAmount, _nonces[owner]++, deadline ) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "ERC20VoteableUpgradeSafe: permit: invalid signature" ); require( signatory == owner, "ERC20VoteableUpgradeSafe: permit: unauthorized" ); require( now <= deadline, "ERC20VoteableUpgradeSafe: permit: signature expired" ); _approve(owner, spender, amount); emit Approval(owner, spender, amount); } /** * @notice Delegate votes from `_msgSender()` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(_msgSender(), delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), _getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "ERC20VoteableUpgradeSafe: delegateBySig: invalid signature" ); require( nonce == _nonces[signatory]++, "ERC20VoteableUpgradeSafe: delegateBySig: invalid nonce" ); require( now <= expiry, "ERC20VoteableUpgradeSafe: delegateBySig: signature expired" ); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint256 nCheckpoints = _numCheckpoints[account]; return nCheckpoints > 0 ? _checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public override view returns (uint256) { require( blockNumber < block.number, "ERC20VoteableUpgradeSafe: 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 _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint256 srcRepNum = _numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? _checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint256 dstRepNum = _numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? _checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { if ( nCheckpoints > 0 && _checkpoints[delegatee][nCheckpoints - 1].fromBlock == block.number ) { _checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { _checkpoints[delegatee][nCheckpoints] = Checkpoint( block.number, newVotes ); _numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); _moveDelegates(_delegates[from], _delegates[to], amount); } } // File: contracts/CF.sol pragma solidity 0.6.12; contract CF is ERC20UpgradeSafe, ERC20VoteableUpgradeSafe, ERC20CappedUpgradeSafe, OwnableUpgradeSafe { event AuthorizeMinter(address minter, address operator); event RevokeMinter(address minter, address operator); address[] public minters; mapping(address => bool) public isMinter; function initialize() public initializer { __ERC20_init("Consensus Finance", "CF"); __ERC20Capped_init(1000_000e18); __Ownable_init(); } function mint(address to, uint256 amount) public { require(isMinter[_msgSender()], "CF: caller is not an operator for CF"); _mint(to, amount); } function authorizeMinter(address minter) public onlyOwner { for (uint256 i = 0; i < minters.length; i++) { if (minters[i] == minter) revert("CF: minter exists"); } minters.push(minter); isMinter[minter] = true; emit AuthorizeMinter(minter, _msgSender()); } function revokeMinter(address minter) public onlyOwner { bool has; uint256 minterIndex; for (uint256 i = 0; i < minters.length; i++) { if (minters[i] == minter) { has = true; minterIndex = i; break; } } require(has, "CF: minter not found"); address lastMinter = minters[minters.length - 1]; if (lastMinter != minter) minters[minterIndex] = lastMinter; minters.pop(); delete isMinter[minter]; emit RevokeMinter(minter, _msgSender()); } function mintersLength() public view returns (uint256) { return minters.length; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override( ERC20UpgradeSafe, ERC20VoteableUpgradeSafe, ERC20CappedUpgradeSafe ) { super._beforeTokenTransfer(from, to, amount); } } // File: contracts/GenesisOffering.sol pragma solidity 0.6.12; contract GenesisOffering is ContextUpgradeSafe { using SafeMath for uint256; CF public token; uint256 public totalEther; uint256 public totalToken; uint256 public start; uint256 public end; uint256 public constant maxStockPerAddress = 100 ether; mapping(address => uint256) public holders; function initialize( address _tokenAddress, uint256 _totalToken, uint256 _start, uint256 _end ) public initializer { assert( _tokenAddress != address(0) && _totalToken > 0 && _start > 0 && _end > start ); __Context_init(); token = CF(_tokenAddress); totalToken = _totalToken; start = _start; end = _end; } modifier ensureStarted() { assert(block.timestamp >= start && block.timestamp < end); _; } modifier ensureEnded() { assert(block.timestamp > end); _; } function purchase() public payable ensureStarted { assert(holders[_msgSender()].add(msg.value) <= maxStockPerAddress); totalEther = totalEther.add(msg.value); holders[_msgSender()] = holders[_msgSender()].add(msg.value); } function claim() public ensureEnded { uint256 bidAmount = holders[_msgSender()]; assert(bidAmount > 0); holders[_msgSender()] = 0; token.mint(_msgSender(), totalToken.mul(bidAmount).div(totalEther)); } function devClaim() public ensureEnded { address payable devTeam = address(uint160(token.owner())); devTeam.transfer(address(this).balance); } }
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint256 blockNumber) public override view returns (uint256) { require( blockNumber < block.number, "ERC20VoteableUpgradeSafe: getPriorVotes: not yet determined" ); uint256 nCheckpoints = _numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (_checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return _checkpoints[account][nCheckpoints - 1].votes; } if (_checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint256 lower = 0; uint256 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = _checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return _checkpoints[account][lower].votes; }
417,497
./partial_match/1/0xe324C8cF74899461Ef7aD2c3EB952DA7819aabc5/sources/ResolveToken.sol
Big red exit button to pull all of a holder's Ethereum value from the contract
function getMeOutOfHere() public { sellAllBonds(); withdraw( resolveEarnings(msg.sender) ); }
9,382,038
/* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol"; import "./migrations/LibBootstrap.sol"; import "./features/Bootstrap.sol"; import "./storage/LibProxyStorage.sol"; import "./errors/LibProxyRichErrors.sol"; /// @dev An extensible proxy contract that serves as a universal entry point for /// interacting with the 0x protocol. contract ZeroEx { // solhint-disable separate-by-one-line-in-contract,indent,var-name-mixedcase using LibBytesV06 for bytes; /// @dev Construct this contract and register the `Bootstrap` feature. /// After constructing this contract, `bootstrap()` should be called /// to seed the initial feature set. constructor() public { // Temporarily create and register the bootstrap feature. // It will deregister itself after `bootstrap()` has been called. Bootstrap bootstrap = new Bootstrap(msg.sender); LibProxyStorage.getStorage().impls[bootstrap.bootstrap.selector] = address(bootstrap); } // solhint-disable state-visibility /// @dev Forwards calls to the appropriate implementation contract. fallback() external payable { bytes4 selector = msg.data.readBytes4(0); address impl = getFunctionImplementation(selector); if (impl == address(0)) { _revertWithData(LibProxyRichErrors.NotImplementedError(selector)); } (bool success, bytes memory resultData) = impl.delegatecall(msg.data); if (!success) { _revertWithData(resultData); } _returnWithData(resultData); } /// @dev Fallback for just receiving ether. receive() external payable {} // solhint-enable state-visibility /// @dev Get the implementation contract of a registered function. /// @param selector The function selector. /// @return impl The implementation contract address. function getFunctionImplementation(bytes4 selector) public view returns (address impl) { return LibProxyStorage.getStorage().impls[selector]; } /// @dev Revert with arbitrary bytes. /// @param data Revert data. function _revertWithData(bytes memory data) private pure { assembly { revert(add(data, 32), mload(data)) } } /// @dev Return with arbitrary bytes. /// @param data Return data. function _returnWithData(bytes memory data) private pure { assembly { return(add(data, 32), mload(data)) } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; import "./errors/LibBytesRichErrorsV06.sol"; import "./errors/LibRichErrorsV06.sol"; library LibBytesV06 { using LibBytesV06 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) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // 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. /// When `from == 0`, the original array will match the slice. /// In other cases its state will be corrupted. /// @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) function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // 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) { if (b.length == 0) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, b.length, 0 )); } // 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 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) { if (b.length < index + 20) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // 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 { if (b.length < index + 20) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // 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) { if (b.length < index + 32) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // 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 { if (b.length < index + 32) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // 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) { if (b.length < index + 4) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, b.length, index + 4 )); } // 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 Writes a new length to a byte array. /// Decreasing length will lead to removing the corresponding lower order bytes from the byte array. /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. function writeLength(bytes memory b, uint256 length) internal pure { assembly { mstore(b, length) } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibBytesRichErrorsV06 { enum InvalidByteOperationErrorCodes { FromLessThanOrEqualsToRequired, ToLessThanOrEqualsLengthRequired, LengthGreaterThanZeroRequired, LengthGreaterThanOrEqualsFourRequired, LengthGreaterThanOrEqualsTwentyRequired, LengthGreaterThanOrEqualsThirtyTwoRequired, LengthGreaterThanOrEqualsNestedBytesLengthRequired, DestinationLengthGreaterThanOrEqualSourceLengthRequired } // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)")) bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = 0x28006595; // solhint-disable func-name-mixedcase function InvalidByteOperationError( InvalidByteOperationErrorCodes errorCode, uint256 offset, uint256 required ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INVALID_BYTE_OPERATION_ERROR_SELECTOR, errorCode, offset, required ); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibRichErrorsV06 { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError(string memory message) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../errors/LibProxyRichErrors.sol"; library LibBootstrap { /// @dev Magic bytes returned by the bootstrapper to indicate success. /// This is `keccack('BOOTSTRAP_SUCCESS')`. bytes4 internal constant BOOTSTRAP_SUCCESS = 0xd150751b; using LibRichErrorsV06 for bytes; /// @dev Perform a delegatecall and ensure it returns the magic bytes. /// @param target The call target. /// @param data The call data. function delegatecallBootstrapFunction( address target, bytes memory data ) internal { (bool success, bytes memory resultData) = target.delegatecall(data); if (!success || resultData.length != 32 || abi.decode(resultData, (bytes4)) != BOOTSTRAP_SUCCESS) { LibProxyRichErrors.BootstrapCallFailedError(target, resultData).rrevert(); } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibProxyRichErrors { // solhint-disable func-name-mixedcase function NotImplementedError(bytes4 selector) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("NotImplementedError(bytes4)")), selector ); } function InvalidBootstrapCallerError(address actual, address expected) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("InvalidBootstrapCallerError(address,address)")), actual, expected ); } function InvalidDieCallerError(address actual, address expected) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("InvalidDieCallerError(address,address)")), actual, expected ); } function BootstrapCallFailedError(address target, bytes memory resultData) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("BootstrapCallFailedError(address,bytes)")), target, resultData ); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../migrations/LibBootstrap.sol"; import "../storage/LibProxyStorage.sol"; import "./IBootstrap.sol"; /// @dev Detachable `bootstrap()` feature. contract Bootstrap is IBootstrap { // solhint-disable state-visibility,indent /// @dev The ZeroEx contract. /// This has to be immutable to persist across delegatecalls. address immutable private _deployer; /// @dev The implementation address of this contract. /// This has to be immutable to persist across delegatecalls. address immutable private _implementation; /// @dev The deployer. /// This has to be immutable to persist across delegatecalls. address immutable private _bootstrapCaller; // solhint-enable state-visibility,indent using LibRichErrorsV06 for bytes; /// @dev Construct this contract and set the bootstrap migration contract. /// After constructing this contract, `bootstrap()` should be called /// to seed the initial feature set. /// @param bootstrapCaller The allowed caller of `bootstrap()`. constructor(address bootstrapCaller) public { _deployer = msg.sender; _implementation = address(this); _bootstrapCaller = bootstrapCaller; } /// @dev Bootstrap the initial feature set of this contract by delegatecalling /// into `target`. Before exiting the `bootstrap()` function will /// deregister itself from the proxy to prevent being called again. /// @param target The bootstrapper contract address. /// @param callData The call data to execute on `target`. function bootstrap(address target, bytes calldata callData) external override { // Only the bootstrap caller can call this function. if (msg.sender != _bootstrapCaller) { LibProxyRichErrors.InvalidBootstrapCallerError( msg.sender, _bootstrapCaller ).rrevert(); } // Deregister. LibProxyStorage.getStorage().impls[this.bootstrap.selector] = address(0); // Self-destruct. Bootstrap(_implementation).die(); // Call the bootstrapper. LibBootstrap.delegatecallBootstrapFunction(target, callData); } /// @dev Self-destructs this contract. /// Can only be called by the deployer. function die() external { if (msg.sender != _deployer) { LibProxyRichErrors.InvalidDieCallerError(msg.sender, _deployer).rrevert(); } selfdestruct(msg.sender); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "./LibStorage.sol"; /// @dev Storage helpers for the proxy contract. library LibProxyStorage { /// @dev Storage bucket for proxy contract. struct Storage { // Mapping of function selector -> function implementation mapping(bytes4 => address) impls; // The owner of the proxy contract. address owner; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.getStorageSlot( LibStorage.StorageId.Proxy ); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor_slot := storageSlot } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; /// @dev Common storage helpers library LibStorage { /// @dev What to bit-shift a storage ID by to get its slot. /// This gives us a maximum of 2**128 inline fields in each bucket. uint256 private constant STORAGE_SLOT_EXP = 128; /// @dev Storage IDs for feature storage buckets. /// WARNING: APPEND-ONLY. enum StorageId { Proxy, SimpleFunctionRegistry, Ownable, TokenSpender, TransformERC20 } /// @dev Get the storage slot given a storage ID. We assign unique, well-spaced /// slots to storage bucket variables to ensure they do not overlap. /// See: https://solidity.readthedocs.io/en/v0.6.6/assembly.html#access-to-external-variables-functions-and-libraries /// @param storageId An entry in `StorageId` /// @return slot The storage slot. function getStorageSlot(StorageId storageId) internal pure returns (uint256 slot) { // This should never overflow with a reasonable `STORAGE_SLOT_EXP` // because Solidity will do a range check on `storageId` during the cast. return (uint256(storageId) + 1) << STORAGE_SLOT_EXP; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; /// @dev Detachable `bootstrap()` feature. interface IBootstrap { /// @dev Bootstrap the initial feature set of this contract by delegatecalling /// into `target`. Before exiting the `bootstrap()` function will /// deregister itself from the proxy to prevent being called again. /// @param target The bootstrapper contract address. /// @param callData The call data to execute on `target`. function bootstrap(address target, bytes calldata callData) external; } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibCommonRichErrors { // solhint-disable func-name-mixedcase function OnlyCallableBySelfError(address sender) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("OnlyCallableBySelfError(address)")), sender ); } function IllegalReentrancyError() internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("IllegalReentrancyError()")) ); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibOwnableRichErrors { // solhint-disable func-name-mixedcase function OnlyOwnerError( address sender, address owner ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("OnlyOwnerError(address,address)")), sender, owner ); } function TransferOwnerToZeroError() internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("TransferOwnerToZeroError()")) ); } function MigrateCallFailedError(address target, bytes memory resultData) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("MigrateCallFailedError(address,bytes)")), target, resultData ); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibSimpleFunctionRegistryRichErrors { // solhint-disable func-name-mixedcase function NotInRollbackHistoryError(bytes4 selector, address targetImpl) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("NotInRollbackHistoryError(bytes4,address)")), selector, targetImpl ); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibSpenderRichErrors { // solhint-disable func-name-mixedcase function SpenderERC20TransferFromFailedError( address token, address owner, address to, uint256 amount, bytes memory errorData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("SpenderERC20TransferFromFailedError(address,address,address,uint256,bytes)")), token, owner, to, amount, errorData ); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibTransformERC20RichErrors { // solhint-disable func-name-mixedcase,separate-by-one-line-in-contract function InsufficientEthAttachedError( uint256 ethAttached, uint256 ethNeeded ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("InsufficientEthAttachedError(uint256,uint256)")), ethAttached, ethNeeded ); } function IncompleteTransformERC20Error( address outputToken, uint256 outputTokenAmount, uint256 minOutputTokenAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("IncompleteTransformERC20Error(address,uint256,uint256)")), outputToken, outputTokenAmount, minOutputTokenAmount ); } function NegativeTransformERC20OutputError( address outputToken, uint256 outputTokenLostAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("NegativeTransformERC20OutputError(address,uint256)")), outputToken, outputTokenLostAmount ); } function TransformerFailedError( address transformer, bytes memory transformerData, bytes memory resultData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("TransformerFailedError(address,bytes,bytes)")), transformer, transformerData, resultData ); } // Common Transformer errors /////////////////////////////////////////////// function OnlyCallableByDeployerError( address caller, address deployer ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("OnlyCallableByDeployerError(address,address)")), caller, deployer ); } function InvalidExecutionContextError( address actualContext, address expectedContext ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("InvalidExecutionContextError(address,address)")), actualContext, expectedContext ); } enum InvalidTransformDataErrorCode { INVALID_TOKENS, INVALID_ARRAY_LENGTH } function InvalidTransformDataError( InvalidTransformDataErrorCode errorCode, bytes memory transformData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("InvalidTransformDataError(uint8,bytes)")), errorCode, transformData ); } // FillQuoteTransformer errors ///////////////////////////////////////////// function IncompleteFillSellQuoteError( address sellToken, uint256 soldAmount, uint256 sellAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("IncompleteFillSellQuoteError(address,uint256,uint256)")), sellToken, soldAmount, sellAmount ); } function IncompleteFillBuyQuoteError( address buyToken, uint256 boughtAmount, uint256 buyAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("IncompleteFillBuyQuoteError(address,uint256,uint256)")), buyToken, boughtAmount, buyAmount ); } function InsufficientTakerTokenError( uint256 tokenBalance, uint256 tokensNeeded ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("InsufficientTakerTokenError(uint256,uint256)")), tokenBalance, tokensNeeded ); } function InsufficientProtocolFeeError( uint256 ethBalance, uint256 ethNeeded ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("InsufficientProtocolFeeError(uint256,uint256)")), ethBalance, ethNeeded ); } function InvalidERC20AssetDataError( bytes memory assetData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("InvalidERC20AssetDataError(bytes)")), assetData ); } function InvalidTakerFeeTokenError( address token ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("InvalidTakerFeeTokenError(address)")), token ); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibWalletRichErrors { // solhint-disable func-name-mixedcase function WalletExecuteCallFailedError( address wallet, address callTarget, bytes memory callData, uint256 callValue, bytes memory errorData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("WalletExecuteCallFailedError(address,address,bytes,uint256,bytes)")), wallet, callTarget, callData, callValue, errorData ); } function WalletExecuteDelegateCallFailedError( address wallet, address callTarget, bytes memory callData, bytes memory errorData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("WalletExecuteDelegateCallFailedError(address,address,bytes,bytes)")), wallet, callTarget, callData, errorData ); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/AuthorizableV06.sol"; import "../errors/LibSpenderRichErrors.sol"; import "./IAllowanceTarget.sol"; /// @dev The allowance target for the TokenSpender feature. contract AllowanceTarget is IAllowanceTarget, AuthorizableV06 { // solhint-disable no-unused-vars,indent,no-empty-blocks using LibRichErrorsV06 for bytes; /// @dev Execute an arbitrary call. Only an authority can call this. /// @param target The call target. /// @param callData The call data. /// @return resultData The data returned by the call. function executeCall( address payable target, bytes calldata callData ) external override onlyAuthorized returns (bytes memory resultData) { bool success; (success, resultData) = target.call(callData); if (!success) { resultData.rrevert(); } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; import "./interfaces/IAuthorizableV06.sol"; import "./errors/LibRichErrorsV06.sol"; import "./errors/LibAuthorizableRichErrorsV06.sol"; import "./OwnableV06.sol"; // solhint-disable no-empty-blocks contract AuthorizableV06 is OwnableV06, IAuthorizableV06 { /// @dev Only authorized addresses can invoke functions with this modifier. modifier onlyAuthorized { _assertSenderIsAuthorized(); _; } // @dev Whether an address is authorized to call privileged functions. // @param 0 Address to query. // @return 0 Whether the address is authorized. mapping (address => bool) public override authorized; // @dev Whether an address is authorized to call privileged functions. // @param 0 Index of authorized address. // @return 0 Authorized address. address[] public override authorities; /// @dev Initializes the `owner` address. constructor() public OwnableV06() {} /// @dev Authorizes an address. /// @param target Address to authorize. function addAuthorizedAddress(address target) external override onlyOwner { _addAuthorizedAddress(target); } /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. function removeAuthorizedAddress(address target) external override onlyOwner { if (!authorized[target]) { LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.TargetNotAuthorizedError(target)); } for (uint256 i = 0; i < authorities.length; i++) { if (authorities[i] == target) { _removeAuthorizedAddressAtIndex(target, i); break; } } } /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. /// @param index Index of target in authorities array. function removeAuthorizedAddressAtIndex( address target, uint256 index ) external override onlyOwner { _removeAuthorizedAddressAtIndex(target, index); } /// @dev Gets all authorized addresses. /// @return Array of authorized addresses. function getAuthorizedAddresses() external override view returns (address[] memory) { return authorities; } /// @dev Reverts if msg.sender is not authorized. function _assertSenderIsAuthorized() internal view { if (!authorized[msg.sender]) { LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.SenderNotAuthorizedError(msg.sender)); } } /// @dev Authorizes an address. /// @param target Address to authorize. function _addAuthorizedAddress(address target) internal { // Ensure that the target is not the zero address. if (target == address(0)) { LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.ZeroCantBeAuthorizedError()); } // Ensure that the target is not already authorized. if (authorized[target]) { LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.TargetAlreadyAuthorizedError(target)); } authorized[target] = true; authorities.push(target); emit AuthorizedAddressAdded(target, msg.sender); } /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. /// @param index Index of target in authorities array. function _removeAuthorizedAddressAtIndex( address target, uint256 index ) internal { if (!authorized[target]) { LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.TargetNotAuthorizedError(target)); } if (index >= authorities.length) { LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.IndexOutOfBoundsError( index, authorities.length )); } if (authorities[index] != target) { LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.AuthorizedAddressMismatchError( authorities[index], target )); } delete authorized[target]; authorities[index] = authorities[authorities.length - 1]; authorities.pop(); emit AuthorizedAddressRemoved(target, msg.sender); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; import "./IOwnableV06.sol"; interface IAuthorizableV06 is IOwnableV06 { // Event logged when a new address is authorized. event AuthorizedAddressAdded( address indexed target, address indexed caller ); // Event logged when a currently authorized address is unauthorized. event AuthorizedAddressRemoved( address indexed target, address indexed caller ); /// @dev Authorizes an address. /// @param target Address to authorize. function addAuthorizedAddress(address target) external; /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. function removeAuthorizedAddress(address target) external; /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. /// @param index Index of target in authorities array. function removeAuthorizedAddressAtIndex( address target, uint256 index ) external; /// @dev Gets all authorized addresses. /// @return authorizedAddresses Array of authorized addresses. function getAuthorizedAddresses() external view returns (address[] memory authorizedAddresses); /// @dev Whether an adderss is authorized to call privileged functions. /// @param addr Address to query. /// @return isAuthorized Whether the address is authorized. function authorized(address addr) external view returns (bool isAuthorized); /// @dev All addresseses authorized to call privileged functions. /// @param idx Index of authorized address. /// @return addr Authorized address. function authorities(uint256 idx) external view returns (address addr); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; interface IOwnableV06 { /// @dev Emitted by Ownable when ownership is transferred. /// @param previousOwner The previous owner of the contract. /// @param newOwner The new owner of the contract. event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @dev Transfers ownership of the contract to a new address. /// @param newOwner The address that will become the owner. function transferOwnership(address newOwner) external; /// @dev The owner of this contract. /// @return ownerAddress The owner address. function owner() external view returns (address ownerAddress); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibAuthorizableRichErrorsV06 { // bytes4(keccak256("AuthorizedAddressMismatchError(address,address)")) bytes4 internal constant AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR = 0x140a84db; // bytes4(keccak256("IndexOutOfBoundsError(uint256,uint256)")) bytes4 internal constant INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR = 0xe9f83771; // bytes4(keccak256("SenderNotAuthorizedError(address)")) bytes4 internal constant SENDER_NOT_AUTHORIZED_ERROR_SELECTOR = 0xb65a25b9; // bytes4(keccak256("TargetAlreadyAuthorizedError(address)")) bytes4 internal constant TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR = 0xde16f1a0; // bytes4(keccak256("TargetNotAuthorizedError(address)")) bytes4 internal constant TARGET_NOT_AUTHORIZED_ERROR_SELECTOR = 0xeb5108a2; // bytes4(keccak256("ZeroCantBeAuthorizedError()")) bytes internal constant ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES = hex"57654fe4"; // solhint-disable func-name-mixedcase function AuthorizedAddressMismatchError( address authorized, address target ) internal pure returns (bytes memory) { return abi.encodeWithSelector( AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR, authorized, target ); } function IndexOutOfBoundsError( uint256 index, uint256 length ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR, index, length ); } function SenderNotAuthorizedError(address sender) internal pure returns (bytes memory) { return abi.encodeWithSelector( SENDER_NOT_AUTHORIZED_ERROR_SELECTOR, sender ); } function TargetAlreadyAuthorizedError(address target) internal pure returns (bytes memory) { return abi.encodeWithSelector( TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR, target ); } function TargetNotAuthorizedError(address target) internal pure returns (bytes memory) { return abi.encodeWithSelector( TARGET_NOT_AUTHORIZED_ERROR_SELECTOR, target ); } function ZeroCantBeAuthorizedError() internal pure returns (bytes memory) { return ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES; } } /* 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.5; import "./interfaces/IOwnableV06.sol"; import "./errors/LibRichErrorsV06.sol"; import "./errors/LibOwnableRichErrorsV06.sol"; contract OwnableV06 is IOwnableV06 { /// @dev The owner of this contract. /// @return 0 The owner address. address public override owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { _assertSenderIsOwner(); _; } /// @dev Change the owner of this contract. /// @param newOwner New owner address. function transferOwnership(address newOwner) public override onlyOwner { if (newOwner == address(0)) { LibRichErrorsV06.rrevert(LibOwnableRichErrorsV06.TransferOwnerToZeroError()); } else { owner = newOwner; emit OwnershipTransferred(msg.sender, newOwner); } } function _assertSenderIsOwner() internal view { if (msg.sender != owner) { LibRichErrorsV06.rrevert(LibOwnableRichErrorsV06.OnlyOwnerError( msg.sender, owner )); } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibOwnableRichErrorsV06 { // bytes4(keccak256("OnlyOwnerError(address,address)")) bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR = 0x1de45ad1; // bytes4(keccak256("TransferOwnerToZeroError()")) bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES = hex"e69edc3e"; // solhint-disable func-name-mixedcase function OnlyOwnerError( address sender, address owner ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ONLY_OWNER_ERROR_SELECTOR, sender, owner ); } function TransferOwnerToZeroError() internal pure returns (bytes memory) { return TRANSFER_OWNER_TO_ZERO_ERROR_BYTES; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/interfaces/IAuthorizableV06.sol"; /// @dev The allowance target for the TokenSpender feature. interface IAllowanceTarget is IAuthorizableV06 { /// @dev Execute an arbitrary call. Only an authority can call this. /// @param target The call target. /// @param callData The call data. /// @return resultData The data returned by the call. function executeCall( address payable target, bytes calldata callData ) external returns (bytes memory resultData); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/errors/LibOwnableRichErrorsV06.sol"; import "../errors/LibWalletRichErrors.sol"; import "./IFlashWallet.sol"; /// @dev A contract that can execute arbitrary calls from its owner. contract FlashWallet is IFlashWallet { // solhint-disable no-unused-vars,indent,no-empty-blocks using LibRichErrorsV06 for bytes; // solhint-disable /// @dev Store the owner/deployer as an immutable to make this contract stateless. address public override immutable owner; // solhint-enable constructor() public { // The deployer is the owner. owner = msg.sender; } /// @dev Allows only the (immutable) owner to call a function. modifier onlyOwner() virtual { if (msg.sender != owner) { LibOwnableRichErrorsV06.OnlyOwnerError( msg.sender, owner ).rrevert(); } _; } /// @dev Execute an arbitrary call. Only an authority can call this. /// @param target The call target. /// @param callData The call data. /// @param value Ether to attach to the call. /// @return resultData The data returned by the call. function executeCall( address payable target, bytes calldata callData, uint256 value ) external payable override onlyOwner returns (bytes memory resultData) { bool success; (success, resultData) = target.call{value: value}(callData); if (!success) { LibWalletRichErrors .WalletExecuteCallFailedError( address(this), target, callData, value, resultData ) .rrevert(); } } /// @dev Execute an arbitrary delegatecall, in the context of this puppet. /// Only an authority can call this. /// @param target The call target. /// @param callData The call data. /// @return resultData The data returned by the call. function executeDelegateCall( address payable target, bytes calldata callData ) external payable override onlyOwner returns (bytes memory resultData) { bool success; (success, resultData) = target.delegatecall(callData); if (!success) { LibWalletRichErrors .WalletExecuteDelegateCallFailedError( address(this), target, callData, resultData ) .rrevert(); } } // solhint-disable /// @dev Allows this contract to receive ether. receive() external override payable {} // solhint-enable /// @dev Signal support for receiving ERC1155 tokens. /// @param interfaceID The interface ID, as per ERC-165 rules. /// @return hasSupport `true` if this contract supports an ERC-165 interface. function supportsInterface(bytes4 interfaceID) external pure returns (bool hasSupport) { return interfaceID == this.supportsInterface.selector || interfaceID == this.onERC1155Received.selector ^ this.onERC1155BatchReceived.selector || interfaceID == this.tokenFallback.selector; } /// @dev Allow this contract to receive ERC1155 tokens. /// @return success `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` function onERC1155Received( address, // operator, address, // from, uint256, // id, uint256, // value, bytes calldata //data ) external pure returns (bytes4 success) { return this.onERC1155Received.selector; } /// @dev Allow this contract to receive ERC1155 tokens. /// @return success `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` function onERC1155BatchReceived( address, // operator, address, // from, uint256[] calldata, // ids, uint256[] calldata, // values, bytes calldata // data ) external pure returns (bytes4 success) { return this.onERC1155BatchReceived.selector; } /// @dev Allows this contract to receive ERC223 tokens. function tokenFallback( address, // from, uint256, // value, bytes calldata // value ) external pure {} } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/interfaces/IOwnableV06.sol"; /// @dev A contract that can execute arbitrary calls from its owner. interface IFlashWallet { /// @dev Execute an arbitrary call. Only an authority can call this. /// @param target The call target. /// @param callData The call data. /// @param value Ether to attach to the call. /// @return resultData The data returned by the call. function executeCall( address payable target, bytes calldata callData, uint256 value ) external payable returns (bytes memory resultData); /// @dev Execute an arbitrary delegatecall, in the context of this puppet. /// Only an authority can call this. /// @param target The call target. /// @param callData The call data. /// @return resultData The data returned by the call. function executeDelegateCall( address payable target, bytes calldata callData ) external payable returns (bytes memory resultData); /// @dev Allows the puppet to receive ETH. receive() external payable; /// @dev Fetch the immutable owner/deployer of this contract. /// @return owner_ The immutable owner/deployer/ function owner() external view returns (address owner_); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/AuthorizableV06.sol"; /// @dev A contract with a `die()` function. interface IKillable { function die() external; } /// @dev Deployer contract for ERC20 transformers. /// Only authorities may call `deploy()` and `kill()`. contract TransformerDeployer is AuthorizableV06 { /// @dev Emitted when a contract is deployed via `deploy()`. /// @param deployedAddress The address of the deployed contract. /// @param nonce The deployment nonce. /// @param sender The caller of `deploy()`. event Deployed(address deployedAddress, uint256 nonce, address sender); /// @dev Emitted when a contract is killed via `kill()`. /// @param target The address of the contract being killed.. /// @param sender The caller of `kill()`. event Killed(address target, address sender); // @dev The current nonce of this contract. uint256 public nonce = 1; // @dev Mapping of deployed contract address to deployment nonce. mapping (address => uint256) public toDeploymentNonce; /// @dev Create this contract and register authorities. constructor(address[] memory authorities) public { for (uint256 i = 0; i < authorities.length; ++i) { _addAuthorizedAddress(authorities[i]); } } /// @dev Deploy a new contract. Only callable by an authority. /// Any attached ETH will also be forwarded. function deploy(bytes memory bytecode) public payable onlyAuthorized returns (address deployedAddress) { uint256 deploymentNonce = nonce; nonce += 1; assembly { deployedAddress := create(callvalue(), add(bytecode, 32), mload(bytecode)) } toDeploymentNonce[deployedAddress] = deploymentNonce; emit Deployed(deployedAddress, deploymentNonce, msg.sender); } /// @dev Call `die()` on a contract. Only callable by an authority. function kill(IKillable target) public onlyAuthorized { target.die(); emit Killed(address(target), msg.sender); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; /// @dev Basic interface for a feature contract. interface IFeature { // solhint-disable func-name-mixedcase /// @dev The name of this feature set. function FEATURE_NAME() external view returns (string memory name); /// @dev The version of this feature set. function FEATURE_VERSION() external view returns (uint256 version); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/interfaces/IOwnableV06.sol"; // solhint-disable no-empty-blocks /// @dev Owner management and migration features. interface IOwnable is IOwnableV06 { /// @dev Emitted when `migrate()` is called. /// @param caller The caller of `migrate()`. /// @param migrator The migration contract. /// @param newOwner The address of the new owner. event Migrated(address caller, address migrator, address newOwner); /// @dev Execute a migration function in the context of the ZeroEx contract. /// The result of the function being called should be the magic bytes /// 0x2c64c5ef (`keccack('MIGRATE_SUCCESS')`). Only callable by the owner. /// The owner will be temporarily set to `address(this)` inside the call. /// Before returning, the owner will be set to `newOwner`. /// @param target The migrator contract address. /// @param newOwner The address of the new owner. /// @param data The call data. function migrate(address target, bytes calldata data, address newOwner) external; } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; /// @dev Basic registry management features. interface ISimpleFunctionRegistry { /// @dev A function implementation was updated via `extend()` or `rollback()`. /// @param selector The function selector. /// @param oldImpl The implementation contract address being replaced. /// @param newImpl The replacement implementation contract address. event ProxyFunctionUpdated(bytes4 indexed selector, address oldImpl, address newImpl); /// @dev Roll back to a prior implementation of a function. /// @param selector The function selector. /// @param targetImpl The address of an older implementation of the function. function rollback(bytes4 selector, address targetImpl) external; /// @dev Register or replace a function. /// @param selector The function selector. /// @param impl The implementation contract for the function. function extend(bytes4 selector, address impl) external; /// @dev Retrieve the length of the rollback history for a function. /// @param selector The function selector. /// @return rollbackLength The number of items in the rollback history for /// the function. function getRollbackLength(bytes4 selector) external view returns (uint256 rollbackLength); /// @dev Retrieve an entry in the rollback history for a function. /// @param selector The function selector. /// @param idx The index in the rollback history. /// @return impl An implementation address for the function at /// index `idx`. function getRollbackEntryAtIndex(bytes4 selector, uint256 idx) external view returns (address impl); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; /// @dev Feature that allows spending token allowances. interface ITokenSpender { /// @dev Transfers ERC20 tokens from `owner` to `to`. /// Only callable from within. /// @param token The token to spend. /// @param owner The owner of the tokens. /// @param to The recipient of the tokens. /// @param amount The amount of `token` to transfer. function _spendERC20Tokens( IERC20TokenV06 token, address owner, address to, uint256 amount ) external; /// @dev Gets the maximum amount of an ERC20 token `token` that can be /// pulled from `owner`. /// @param token The token to spend. /// @param owner The owner of the tokens. /// @return amount The amount of tokens that can be pulled. function getSpendableERC20BalanceOf(IERC20TokenV06 token, address owner) external view returns (uint256 amount); /// @dev Get the address of the allowance target. /// @return target The target of token allowances. function getAllowanceTarget() external view returns (address target); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; interface IERC20TokenV06 { // solhint-disable 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 ); /// @dev 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 True if transfer was successful function transfer(address to, uint256 value) external returns (bool); /// @dev 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 True if transfer was successful function transferFrom( address from, address to, uint256 value ) external returns (bool); /// @dev `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 wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution function approve(address spender, uint256 value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token function totalSupply() external view returns (uint256); /// @dev Get the balance of `owner`. /// @param owner The address from which the balance will be retrieved /// @return Balance of owner function balanceOf(address owner) external view returns (uint256); /// @dev Get the allowance for `spender` to spend from `owner`. /// @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) external view returns (uint256); /// @dev Get the number of decimals this token has. function decimals() external view returns (uint8); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../transformers/IERC20Transformer.sol"; import "../external/IFlashWallet.sol"; /// @dev Feature to composably transform between ERC20 tokens. interface ITransformERC20 { /// @dev Defines a transformation to run in `transformERC20()`. struct Transformation { // The deployment nonce for the transformer. // The address of the transformer contract will be derived from this // value. uint32 deploymentNonce; // Arbitrary data to pass to the transformer. bytes data; } /// @dev Raised upon a successful `transformERC20`. /// @param taker The taker (caller) address. /// @param inputToken The token being provided by the taker. /// If `0xeee...`, ETH is implied and should be provided with the call.` /// @param outputToken The token to be acquired by the taker. /// `0xeee...` implies ETH. /// @param inputTokenAmount The amount of `inputToken` to take from the taker. /// @param outputTokenAmount The amount of `outputToken` received by the taker. event TransformedERC20( address indexed taker, address inputToken, address outputToken, uint256 inputTokenAmount, uint256 outputTokenAmount ); /// @dev Raised when `setTransformerDeployer()` is called. /// @param transformerDeployer The new deployer address. event TransformerDeployerUpdated(address transformerDeployer); /// @dev Replace the allowed deployer for transformers. /// Only callable by the owner. /// @param transformerDeployer The address of the trusted deployer for transformers. function setTransformerDeployer(address transformerDeployer) external; /// @dev Deploy a new flash wallet instance and replace the current one with it. /// Useful if we somehow break the current wallet instance. /// Anyone can call this. /// @return wallet The new wallet instance. function createTransformWallet() external returns (IFlashWallet wallet); /// @dev Executes a series of transformations to convert an ERC20 `inputToken` /// to an ERC20 `outputToken`. /// @param inputToken The token being provided by the sender. /// If `0xeee...`, ETH is implied and should be provided with the call.` /// @param outputToken The token to be acquired by the sender. /// `0xeee...` implies ETH. /// @param inputTokenAmount The amount of `inputToken` to take from the sender. /// @param minOutputTokenAmount The minimum amount of `outputToken` the sender /// must receive for the entire transformation to succeed. /// @param transformations The transformations to execute on the token balance(s) /// in sequence. /// @return outputTokenAmount The amount of `outputToken` received by the sender. function transformERC20( IERC20TokenV06 inputToken, IERC20TokenV06 outputToken, uint256 inputTokenAmount, uint256 minOutputTokenAmount, Transformation[] calldata transformations ) external payable returns (uint256 outputTokenAmount); /// @dev Internal version of `transformERC20()`. Only callable from within. /// @param callDataHash Hash of the ingress calldata. /// @param taker The taker address. /// @param inputToken The token being provided by the taker. /// If `0xeee...`, ETH is implied and should be provided with the call.` /// @param outputToken The token to be acquired by the taker. /// `0xeee...` implies ETH. /// @param inputTokenAmount The amount of `inputToken` to take from the taker. /// @param minOutputTokenAmount The minimum amount of `outputToken` the taker /// must receive for the entire transformation to succeed. /// @param transformations The transformations to execute on the token balance(s) /// in sequence. /// @return outputTokenAmount The amount of `outputToken` received by the taker. function _transformERC20( bytes32 callDataHash, address payable taker, IERC20TokenV06 inputToken, IERC20TokenV06 outputToken, uint256 inputTokenAmount, uint256 minOutputTokenAmount, Transformation[] calldata transformations ) external payable returns (uint256 outputTokenAmount); /// @dev Return the current wallet instance that will serve as the execution /// context for transformations. /// @return wallet The wallet instance. function getTransformWallet() external view returns (IFlashWallet wallet); /// @dev Return the allowed deployer for transformers. /// @return deployer The transform deployer address. function getTransformerDeployer() external view returns (address deployer); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; /// @dev A transformation callback used in `TransformERC20.transformERC20()`. interface IERC20Transformer { /// @dev Called from `TransformERC20.transformERC20()`. This will be /// delegatecalled in the context of the FlashWallet instance being used. /// @param callDataHash The hash of the `TransformERC20.transformERC20()` calldata. /// @param taker The taker address (caller of `TransformERC20.transformERC20()`). /// @param data Arbitrary data to pass to the transformer. /// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`). function transform( bytes32 callDataHash, address payable taker, bytes calldata data ) external returns (bytes4 success); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../fixins/FixinCommon.sol"; import "../errors/LibOwnableRichErrors.sol"; import "../storage/LibOwnableStorage.sol"; import "../migrations/LibBootstrap.sol"; import "../migrations/LibMigrate.sol"; import "./IFeature.sol"; import "./IOwnable.sol"; import "./SimpleFunctionRegistry.sol"; /// @dev Owner management features. contract Ownable is IFeature, IOwnable, FixinCommon { // solhint-disable /// @dev Name of this feature. string public constant override FEATURE_NAME = "Ownable"; /// @dev Version of this feature. uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0); /// @dev The deployed address of this contract. address immutable private _implementation; // solhint-enable using LibRichErrorsV06 for bytes; constructor() public { _implementation = address(this); } /// @dev Initializes this feature. The intial owner will be set to this (ZeroEx) /// to allow the bootstrappers to call `extend()`. Ownership should be /// transferred to the real owner by the bootstrapper after /// bootstrapping is complete. /// @return success Magic bytes if successful. function bootstrap() external returns (bytes4 success) { // Set the owner to ourselves to allow bootstrappers to call `extend()`. LibOwnableStorage.getStorage().owner = address(this); // Register feature functions. SimpleFunctionRegistry(address(this))._extendSelf(this.transferOwnership.selector, _implementation); SimpleFunctionRegistry(address(this))._extendSelf(this.owner.selector, _implementation); SimpleFunctionRegistry(address(this))._extendSelf(this.migrate.selector, _implementation); return LibBootstrap.BOOTSTRAP_SUCCESS; } /// @dev Change the owner of this contract. /// Only directly callable by the owner. /// @param newOwner New owner address. function transferOwnership(address newOwner) external override onlyOwner { LibOwnableStorage.Storage storage proxyStor = LibOwnableStorage.getStorage(); if (newOwner == address(0)) { LibOwnableRichErrors.TransferOwnerToZeroError().rrevert(); } else { proxyStor.owner = newOwner; emit OwnershipTransferred(msg.sender, newOwner); } } /// @dev Execute a migration function in the context of the ZeroEx contract. /// The result of the function being called should be the magic bytes /// 0x2c64c5ef (`keccack('MIGRATE_SUCCESS')`). Only callable by the owner. /// Temporarily sets the owner to ourselves so we can perform admin functions. /// Before returning, the owner will be set to `newOwner`. /// @param target The migrator contract address. /// @param data The call data. /// @param newOwner The address of the new owner. function migrate(address target, bytes calldata data, address newOwner) external override onlyOwner { if (newOwner == address(0)) { LibOwnableRichErrors.TransferOwnerToZeroError().rrevert(); } LibOwnableStorage.Storage storage stor = LibOwnableStorage.getStorage(); // The owner will be temporarily set to `address(this)` inside the call. stor.owner = address(this); // Perform the migration. LibMigrate.delegatecallMigrateFunction(target, data); // Update the owner. stor.owner = newOwner; emit Migrated(msg.sender, target, newOwner); } /// @dev Get the owner of this contract. /// @return owner_ The owner of this contract. function owner() external override view returns (address owner_) { return LibOwnableStorage.getStorage().owner; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../errors/LibCommonRichErrors.sol"; import "../errors/LibOwnableRichErrors.sol"; import "../features/IOwnable.sol"; /// @dev Common feature utilities. contract FixinCommon { using LibRichErrorsV06 for bytes; /// @dev The caller must be this contract. modifier onlySelf() virtual { if (msg.sender != address(this)) { LibCommonRichErrors.OnlyCallableBySelfError(msg.sender).rrevert(); } _; } /// @dev The caller of this function must be the owner. modifier onlyOwner() virtual { { address owner = IOwnable(address(this)).owner(); if (msg.sender != owner) { LibOwnableRichErrors.OnlyOwnerError( msg.sender, owner ).rrevert(); } } _; } /// @dev Encode a feature version as a `uint256`. /// @param major The major version number of the feature. /// @param minor The minor version number of the feature. /// @param revision The revision number of the feature. /// @return encodedVersion The encoded version number. function _encodeVersion(uint32 major, uint32 minor, uint32 revision) internal pure returns (uint256 encodedVersion) { return (major << 64) | (minor << 32) | revision; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "./LibStorage.sol"; /// @dev Storage helpers for the `Ownable` feature. library LibOwnableStorage { /// @dev Storage bucket for this feature. struct Storage { // The owner of this contract. address owner; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.getStorageSlot( LibStorage.StorageId.Ownable ); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor_slot := storageSlot } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../errors/LibOwnableRichErrors.sol"; library LibMigrate { /// @dev Magic bytes returned by a migrator to indicate success. /// This is `keccack('MIGRATE_SUCCESS')`. bytes4 internal constant MIGRATE_SUCCESS = 0x2c64c5ef; using LibRichErrorsV06 for bytes; /// @dev Perform a delegatecall and ensure it returns the magic bytes. /// @param target The call target. /// @param data The call data. function delegatecallMigrateFunction( address target, bytes memory data ) internal { (bool success, bytes memory resultData) = target.delegatecall(data); if (!success || resultData.length != 32 || abi.decode(resultData, (bytes4)) != MIGRATE_SUCCESS) { LibOwnableRichErrors.MigrateCallFailedError(target, resultData).rrevert(); } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../fixins/FixinCommon.sol"; import "../storage/LibProxyStorage.sol"; import "../storage/LibSimpleFunctionRegistryStorage.sol"; import "../errors/LibSimpleFunctionRegistryRichErrors.sol"; import "../migrations/LibBootstrap.sol"; import "./IFeature.sol"; import "./ISimpleFunctionRegistry.sol"; /// @dev Basic registry management features. contract SimpleFunctionRegistry is IFeature, ISimpleFunctionRegistry, FixinCommon { // solhint-disable /// @dev Name of this feature. string public constant override FEATURE_NAME = "SimpleFunctionRegistry"; /// @dev Version of this feature. uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0); /// @dev The deployed address of this contract. address private immutable _implementation; // solhint-enable using LibRichErrorsV06 for bytes; constructor() public { _implementation = address(this); } /// @dev Initializes this feature, registering its own functions. /// @return success Magic bytes if successful. function bootstrap() external returns (bytes4 success) { // Register the registration functions (inception vibes). _extend(this.extend.selector, _implementation); _extend(this._extendSelf.selector, _implementation); // Register the rollback function. _extend(this.rollback.selector, _implementation); // Register getters. _extend(this.getRollbackLength.selector, _implementation); _extend(this.getRollbackEntryAtIndex.selector, _implementation); return LibBootstrap.BOOTSTRAP_SUCCESS; } /// @dev Roll back to a prior implementation of a function. /// Only directly callable by an authority. /// @param selector The function selector. /// @param targetImpl The address of an older implementation of the function. function rollback(bytes4 selector, address targetImpl) external override onlyOwner { ( LibSimpleFunctionRegistryStorage.Storage storage stor, LibProxyStorage.Storage storage proxyStor ) = _getStorages(); address currentImpl = proxyStor.impls[selector]; if (currentImpl == targetImpl) { // Do nothing if already at targetImpl. return; } // Walk history backwards until we find the target implementation. address[] storage history = stor.implHistory[selector]; uint256 i = history.length; for (; i > 0; --i) { address impl = history[i - 1]; history.pop(); if (impl == targetImpl) { break; } } if (i == 0) { LibSimpleFunctionRegistryRichErrors.NotInRollbackHistoryError( selector, targetImpl ).rrevert(); } proxyStor.impls[selector] = targetImpl; emit ProxyFunctionUpdated(selector, currentImpl, targetImpl); } /// @dev Register or replace a function. /// Only directly callable by an authority. /// @param selector The function selector. /// @param impl The implementation contract for the function. function extend(bytes4 selector, address impl) external override onlyOwner { _extend(selector, impl); } /// @dev Register or replace a function. /// Only callable from within. /// This function is only used during the bootstrap process and /// should be deregistered by the deployer after bootstrapping is /// complete. /// @param selector The function selector. /// @param impl The implementation contract for the function. function _extendSelf(bytes4 selector, address impl) external onlySelf { _extend(selector, impl); } /// @dev Retrieve the length of the rollback history for a function. /// @param selector The function selector. /// @return rollbackLength The number of items in the rollback history for /// the function. function getRollbackLength(bytes4 selector) external override view returns (uint256 rollbackLength) { return LibSimpleFunctionRegistryStorage.getStorage().implHistory[selector].length; } /// @dev Retrieve an entry in the rollback history for a function. /// @param selector The function selector. /// @param idx The index in the rollback history. /// @return impl An implementation address for the function at /// index `idx`. function getRollbackEntryAtIndex(bytes4 selector, uint256 idx) external override view returns (address impl) { return LibSimpleFunctionRegistryStorage.getStorage().implHistory[selector][idx]; } /// @dev Register or replace a function. /// @param selector The function selector. /// @param impl The implementation contract for the function. function _extend(bytes4 selector, address impl) private { ( LibSimpleFunctionRegistryStorage.Storage storage stor, LibProxyStorage.Storage storage proxyStor ) = _getStorages(); address oldImpl = proxyStor.impls[selector]; address[] storage history = stor.implHistory[selector]; history.push(oldImpl); proxyStor.impls[selector] = impl; emit ProxyFunctionUpdated(selector, oldImpl, impl); } /// @dev Get the storage buckets for this feature and the proxy. /// @return stor Storage bucket for this feature. /// @return proxyStor age bucket for the proxy. function _getStorages() private pure returns ( LibSimpleFunctionRegistryStorage.Storage storage stor, LibProxyStorage.Storage storage proxyStor ) { return ( LibSimpleFunctionRegistryStorage.getStorage(), LibProxyStorage.getStorage() ); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "./LibStorage.sol"; /// @dev Storage helpers for the `SimpleFunctionRegistry` feature. library LibSimpleFunctionRegistryStorage { /// @dev Storage bucket for this feature. struct Storage { // Mapping of function selector -> implementation history. mapping(bytes4 => address[]) implHistory; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.getStorageSlot( LibStorage.StorageId.SimpleFunctionRegistry ); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor_slot := storageSlot } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "../errors/LibSpenderRichErrors.sol"; import "../fixins/FixinCommon.sol"; import "../migrations/LibMigrate.sol"; import "../external/IAllowanceTarget.sol"; import "../storage/LibTokenSpenderStorage.sol"; import "./ITokenSpender.sol"; import "./IFeature.sol"; import "./ISimpleFunctionRegistry.sol"; /// @dev Feature that allows spending token allowances. contract TokenSpender is IFeature, ITokenSpender, FixinCommon { // solhint-disable /// @dev Name of this feature. string public constant override FEATURE_NAME = "TokenSpender"; /// @dev Version of this feature. uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0); /// @dev The implementation address of this feature. address private immutable _implementation; // solhint-enable using LibRichErrorsV06 for bytes; constructor() public { _implementation = address(this); } /// @dev Initialize and register this feature. Should be delegatecalled /// into during a `Migrate.migrate()`. /// @param allowanceTarget An `allowanceTarget` instance, configured to have /// the ZeroeEx contract as an authority. /// @return success `MIGRATE_SUCCESS` on success. function migrate(IAllowanceTarget allowanceTarget) external returns (bytes4 success) { LibTokenSpenderStorage.getStorage().allowanceTarget = allowanceTarget; ISimpleFunctionRegistry(address(this)) .extend(this.getAllowanceTarget.selector, _implementation); ISimpleFunctionRegistry(address(this)) .extend(this._spendERC20Tokens.selector, _implementation); ISimpleFunctionRegistry(address(this)) .extend(this.getSpendableERC20BalanceOf.selector, _implementation); return LibMigrate.MIGRATE_SUCCESS; } /// @dev Transfers ERC20 tokens from `owner` to `to`. Only callable from within. /// @param token The token to spend. /// @param owner The owner of the tokens. /// @param to The recipient of the tokens. /// @param amount The amount of `token` to transfer. function _spendERC20Tokens( IERC20TokenV06 token, address owner, address to, uint256 amount ) external override onlySelf { IAllowanceTarget spender = LibTokenSpenderStorage.getStorage().allowanceTarget; // Have the allowance target execute an ERC20 `transferFrom()`. (bool didSucceed, bytes memory resultData) = address(spender).call( abi.encodeWithSelector( IAllowanceTarget.executeCall.selector, address(token), abi.encodeWithSelector( IERC20TokenV06.transferFrom.selector, owner, to, amount ) ) ); if (didSucceed) { resultData = abi.decode(resultData, (bytes)); } if (!didSucceed || !LibERC20TokenV06.isSuccessfulResult(resultData)) { LibSpenderRichErrors.SpenderERC20TransferFromFailedError( address(token), owner, to, amount, resultData ).rrevert(); } } /// @dev Gets the maximum amount of an ERC20 token `token` that can be /// pulled from `owner` by the token spender. /// @param token The token to spend. /// @param owner The owner of the tokens. /// @return amount The amount of tokens that can be pulled. function getSpendableERC20BalanceOf(IERC20TokenV06 token, address owner) external override view returns (uint256 amount) { return LibSafeMathV06.min256( token.allowance(owner, address(LibTokenSpenderStorage.getStorage().allowanceTarget)), token.balanceOf(owner) ); } /// @dev Get the address of the allowance target. /// @return target The target of token allowances. function getAllowanceTarget() external override view returns (address target) { return address(LibTokenSpenderStorage.getStorage().allowanceTarget); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; import "./errors/LibRichErrorsV06.sol"; import "./errors/LibSafeMathRichErrorsV06.sol"; library LibSafeMathV06 { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a != b) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, a, b )); } return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO, a, b )); } uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { if (b > a) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, a, b )); } return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c < a) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW, a, b )); } return c; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibSafeMathRichErrorsV06 { // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)")) bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = 0xe946c1bb; // bytes4(keccak256("Uint256DowncastError(uint8,uint256)")) bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = 0xc996af7b; enum BinOpErrorCodes { ADDITION_OVERFLOW, MULTIPLICATION_OVERFLOW, SUBTRACTION_UNDERFLOW, DIVISION_BY_ZERO } enum DowncastErrorCodes { VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96 } // solhint-disable func-name-mixedcase function Uint256BinOpError( BinOpErrorCodes errorCode, uint256 a, uint256 b ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_BINOP_ERROR_SELECTOR, errorCode, a, b ); } function Uint256DowncastError( DowncastErrorCodes errorCode, uint256 a ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_DOWNCAST_ERROR_SELECTOR, errorCode, a ); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol"; import "./IERC20TokenV06.sol"; library LibERC20TokenV06 { bytes constant private DECIMALS_CALL_DATA = hex"313ce567"; /// @dev Calls `IERC20TokenV06(token).approve()`. /// Reverts if the result fails `isSuccessfulResult()` or the call reverts. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param allowance The allowance to set. function compatApprove( IERC20TokenV06 token, address spender, uint256 allowance ) internal { bytes memory callData = abi.encodeWithSelector( token.approve.selector, spender, allowance ); _callWithOptionalBooleanResult(address(token), callData); } /// @dev Calls `IERC20TokenV06(token).approve()` and sets the allowance to the /// maximum if the current approval is not already >= an amount. /// Reverts if the result fails `isSuccessfulResult()` or the call reverts. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param amount The minimum allowance needed. function approveIfBelow( IERC20TokenV06 token, address spender, uint256 amount ) internal { if (token.allowance(address(this), spender) < amount) { compatApprove(token, spender, uint256(-1)); } } /// @dev Calls `IERC20TokenV06(token).transfer()`. /// Reverts if the result fails `isSuccessfulResult()` or the call reverts. /// @param token The address of the token contract. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function compatTransfer( IERC20TokenV06 token, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( token.transfer.selector, to, amount ); _callWithOptionalBooleanResult(address(token), callData); } /// @dev Calls `IERC20TokenV06(token).transferFrom()`. /// Reverts if the result fails `isSuccessfulResult()` or the call reverts. /// @param token The address of the token contract. /// @param from The owner of the tokens. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function compatTransferFrom( IERC20TokenV06 token, address from, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( token.transferFrom.selector, from, to, amount ); _callWithOptionalBooleanResult(address(token), callData); } /// @dev Retrieves the number of decimals for a token. /// Returns `18` if the call reverts. /// @param token The address of the token contract. /// @return tokenDecimals The number of decimals places for the token. function compatDecimals(IERC20TokenV06 token) internal view returns (uint8 tokenDecimals) { tokenDecimals = 18; (bool didSucceed, bytes memory resultData) = address(token).staticcall(DECIMALS_CALL_DATA); if (didSucceed && resultData.length == 32) { tokenDecimals = uint8(LibBytesV06.readUint256(resultData, 0)); } } /// @dev Retrieves the allowance for a token, owner, and spender. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @param spender The address the spender. /// @return allowance_ The allowance for a token, owner, and spender. function compatAllowance(IERC20TokenV06 token, address owner, address spender) internal view returns (uint256 allowance_) { (bool didSucceed, bytes memory resultData) = address(token).staticcall( abi.encodeWithSelector( token.allowance.selector, owner, spender ) ); if (didSucceed && resultData.length == 32) { allowance_ = LibBytesV06.readUint256(resultData, 0); } } /// @dev Retrieves the balance for a token owner. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @return balance The token balance of an owner. function compatBalanceOf(IERC20TokenV06 token, address owner) internal view returns (uint256 balance) { (bool didSucceed, bytes memory resultData) = address(token).staticcall( abi.encodeWithSelector( token.balanceOf.selector, owner ) ); if (didSucceed && resultData.length == 32) { balance = LibBytesV06.readUint256(resultData, 0); } } /// @dev Check if the data returned by a non-static call to an ERC20 token /// is a successful result. Supported functions are `transfer()`, /// `transferFrom()`, and `approve()`. /// @param resultData The raw data returned by a non-static call to the ERC20 token. /// @return isSuccessful Whether the result data indicates success. function isSuccessfulResult(bytes memory resultData) internal pure returns (bool isSuccessful) { if (resultData.length == 0) { return true; } if (resultData.length == 32) { uint256 result = LibBytesV06.readUint256(resultData, 0); if (result == 1) { return true; } } } /// @dev Executes a call on address `target` with calldata `callData` /// and asserts that either nothing was returned or a single boolean /// was returned equal to `true`. /// @param target The call target. /// @param callData The abi-encoded call data. function _callWithOptionalBooleanResult( address target, bytes memory callData ) private { (bool didSucceed, bytes memory resultData) = target.call(callData); if (didSucceed && isSuccessfulResult(resultData)) { return; } LibRichErrorsV06.rrevert(resultData); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "./LibStorage.sol"; import "../external/IAllowanceTarget.sol"; /// @dev Storage helpers for the `TokenSpender` feature. library LibTokenSpenderStorage { /// @dev Storage bucket for this feature. struct Storage { // Allowance target contract. IAllowanceTarget allowanceTarget; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.getStorageSlot( LibStorage.StorageId.TokenSpender ); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor_slot := storageSlot } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "../errors/LibTransformERC20RichErrors.sol"; import "../fixins/FixinCommon.sol"; import "../migrations/LibMigrate.sol"; import "../external/IFlashWallet.sol"; import "../external/FlashWallet.sol"; import "../storage/LibTransformERC20Storage.sol"; import "../transformers/IERC20Transformer.sol"; import "../transformers/LibERC20Transformer.sol"; import "./ITransformERC20.sol"; import "./ITokenSpender.sol"; import "./IFeature.sol"; import "./ISimpleFunctionRegistry.sol"; /// @dev Feature to composably transform between ERC20 tokens. contract TransformERC20 is IFeature, ITransformERC20, FixinCommon { /// @dev Stack vars for `_transformERC20Private()`. struct TransformERC20PrivateState { IFlashWallet wallet; address transformerDeployer; uint256 takerOutputTokenBalanceBefore; uint256 takerOutputTokenBalanceAfter; } // solhint-disable /// @dev Name of this feature. string public constant override FEATURE_NAME = "TransformERC20"; /// @dev Version of this feature. uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0); /// @dev The implementation address of this feature. address private immutable _implementation; // solhint-enable using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; constructor() public { _implementation = address(this); } /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @param transformerDeployer The trusted deployer for transformers. /// @return success `LibMigrate.SUCCESS` on success. function migrate(address transformerDeployer) external returns (bytes4 success) { ISimpleFunctionRegistry(address(this)) .extend(this.getTransformerDeployer.selector, _implementation); ISimpleFunctionRegistry(address(this)) .extend(this.createTransformWallet.selector, _implementation); ISimpleFunctionRegistry(address(this)) .extend(this.getTransformWallet.selector, _implementation); ISimpleFunctionRegistry(address(this)) .extend(this.setTransformerDeployer.selector, _implementation); ISimpleFunctionRegistry(address(this)) .extend(this.transformERC20.selector, _implementation); ISimpleFunctionRegistry(address(this)) .extend(this._transformERC20.selector, _implementation); createTransformWallet(); LibTransformERC20Storage.getStorage().transformerDeployer = transformerDeployer; return LibMigrate.MIGRATE_SUCCESS; } /// @dev Replace the allowed deployer for transformers. /// Only callable by the owner. /// @param transformerDeployer The address of the trusted deployer for transformers. function setTransformerDeployer(address transformerDeployer) external override onlyOwner { LibTransformERC20Storage.getStorage().transformerDeployer = transformerDeployer; emit TransformerDeployerUpdated(transformerDeployer); } /// @dev Return the allowed deployer for transformers. /// @return deployer The transform deployer address. function getTransformerDeployer() public override view returns (address deployer) { return LibTransformERC20Storage.getStorage().transformerDeployer; } /// @dev Deploy a new wallet instance and replace the current one with it. /// Useful if we somehow break the current wallet instance. /// Anyone can call this. /// @return wallet The new wallet instance. function createTransformWallet() public override returns (IFlashWallet wallet) { wallet = new FlashWallet(); LibTransformERC20Storage.getStorage().wallet = wallet; } /// @dev Executes a series of transformations to convert an ERC20 `inputToken` /// to an ERC20 `outputToken`. /// @param inputToken The token being provided by the sender. /// If `0xeee...`, ETH is implied and should be provided with the call.` /// @param outputToken The token to be acquired by the sender. /// `0xeee...` implies ETH. /// @param inputTokenAmount The amount of `inputToken` to take from the sender. /// If set to `uint256(-1)`, the entire spendable balance of the taker /// will be solt. /// @param minOutputTokenAmount The minimum amount of `outputToken` the sender /// must receive for the entire transformation to succeed. If set to zero, /// the minimum output token transfer will not be asserted. /// @param transformations The transformations to execute on the token balance(s) /// in sequence. /// @return outputTokenAmount The amount of `outputToken` received by the sender. function transformERC20( IERC20TokenV06 inputToken, IERC20TokenV06 outputToken, uint256 inputTokenAmount, uint256 minOutputTokenAmount, Transformation[] memory transformations ) public override payable returns (uint256 outputTokenAmount) { return _transformERC20Private( keccak256(msg.data), msg.sender, inputToken, outputToken, inputTokenAmount, minOutputTokenAmount, transformations ); } /// @dev Internal version of `transformERC20()`. Only callable from within. /// @param callDataHash Hash of the ingress calldata. /// @param taker The taker address. /// @param inputToken The token being provided by the taker. /// If `0xeee...`, ETH is implied and should be provided with the call.` /// @param outputToken The token to be acquired by the taker. /// `0xeee...` implies ETH. /// @param inputTokenAmount The amount of `inputToken` to take from the taker. /// If set to `uint256(-1)`, the entire spendable balance of the taker /// will be solt. /// @param minOutputTokenAmount The minimum amount of `outputToken` the taker /// must receive for the entire transformation to succeed. If set to zero, /// the minimum output token transfer will not be asserted. /// @param transformations The transformations to execute on the token balance(s) /// in sequence. /// @return outputTokenAmount The amount of `outputToken` received by the taker. function _transformERC20( bytes32 callDataHash, address payable taker, IERC20TokenV06 inputToken, IERC20TokenV06 outputToken, uint256 inputTokenAmount, uint256 minOutputTokenAmount, Transformation[] memory transformations ) public override payable onlySelf returns (uint256 outputTokenAmount) { return _transformERC20Private( callDataHash, taker, inputToken, outputToken, inputTokenAmount, minOutputTokenAmount, transformations ); } /// @dev Private version of `transformERC20()`. /// @param callDataHash Hash of the ingress calldata. /// @param taker The taker address. /// @param inputToken The token being provided by the taker. /// If `0xeee...`, ETH is implied and should be provided with the call.` /// @param outputToken The token to be acquired by the taker. /// `0xeee...` implies ETH. /// @param inputTokenAmount The amount of `inputToken` to take from the taker. /// If set to `uint256(-1)`, the entire spendable balance of the taker /// will be solt. /// @param minOutputTokenAmount The minimum amount of `outputToken` the taker /// must receive for the entire transformation to succeed. If set to zero, /// the minimum output token transfer will not be asserted. /// @param transformations The transformations to execute on the token balance(s) /// in sequence. /// @return outputTokenAmount The amount of `outputToken` received by the taker. function _transformERC20Private( bytes32 callDataHash, address payable taker, IERC20TokenV06 inputToken, IERC20TokenV06 outputToken, uint256 inputTokenAmount, uint256 minOutputTokenAmount, Transformation[] memory transformations ) private returns (uint256 outputTokenAmount) { // If the input token amount is -1, transform the taker's entire // spendable balance. if (inputTokenAmount == uint256(-1)) { inputTokenAmount = ITokenSpender(address(this)) .getSpendableERC20BalanceOf(inputToken, taker); } TransformERC20PrivateState memory state; state.wallet = getTransformWallet(); state.transformerDeployer = getTransformerDeployer(); // Remember the initial output token balance of the taker. state.takerOutputTokenBalanceBefore = LibERC20Transformer.getTokenBalanceOf(outputToken, taker); // Pull input tokens from the taker to the wallet and transfer attached ETH. _transferInputTokensAndAttachedEth( inputToken, taker, address(state.wallet), inputTokenAmount ); // Perform transformations. for (uint256 i = 0; i < transformations.length; ++i) { _executeTransformation( state.wallet, transformations[i], state.transformerDeployer, taker, callDataHash ); } // Compute how much output token has been transferred to the taker. state.takerOutputTokenBalanceAfter = LibERC20Transformer.getTokenBalanceOf(outputToken, taker); if (state.takerOutputTokenBalanceAfter > state.takerOutputTokenBalanceBefore) { outputTokenAmount = state.takerOutputTokenBalanceAfter.safeSub( state.takerOutputTokenBalanceBefore ); } else if (state.takerOutputTokenBalanceAfter < state.takerOutputTokenBalanceBefore) { LibTransformERC20RichErrors.NegativeTransformERC20OutputError( address(outputToken), state.takerOutputTokenBalanceBefore - state.takerOutputTokenBalanceAfter ).rrevert(); } // Ensure enough output token has been sent to the taker. if (outputTokenAmount < minOutputTokenAmount) { LibTransformERC20RichErrors.IncompleteTransformERC20Error( address(outputToken), outputTokenAmount, minOutputTokenAmount ).rrevert(); } // Emit an event. emit TransformedERC20( taker, address(inputToken), address(outputToken), inputTokenAmount, outputTokenAmount ); } /// @dev Return the current wallet instance that will serve as the execution /// context for transformations. /// @return wallet The wallet instance. function getTransformWallet() public override view returns (IFlashWallet wallet) { return LibTransformERC20Storage.getStorage().wallet; } /// @dev Transfer input tokens from the taker and any attached ETH to `to` /// @param inputToken The token to pull from the taker. /// @param from The from (taker) address. /// @param to The recipient of tokens and ETH. /// @param amount Amount of `inputToken` tokens to transfer. function _transferInputTokensAndAttachedEth( IERC20TokenV06 inputToken, address from, address payable to, uint256 amount ) private { // Transfer any attached ETH. if (msg.value != 0) { to.transfer(msg.value); } // Transfer input tokens. if (!LibERC20Transformer.isTokenETH(inputToken)) { // Token is not ETH, so pull ERC20 tokens. ITokenSpender(address(this))._spendERC20Tokens( inputToken, from, to, amount ); } else if (msg.value < amount) { // Token is ETH, so the caller must attach enough ETH to the call. LibTransformERC20RichErrors.InsufficientEthAttachedError( msg.value, amount ).rrevert(); } } /// @dev Executs a transformer in the context of `wallet`. /// @param wallet The wallet instance. /// @param transformation The transformation. /// @param transformerDeployer The address of the transformer deployer. /// @param taker The taker address. /// @param callDataHash Hash of the calldata. function _executeTransformation( IFlashWallet wallet, Transformation memory transformation, address transformerDeployer, address payable taker, bytes32 callDataHash ) private { // Derive the transformer address from the deployment nonce. address payable transformer = LibERC20Transformer.getDeployedAddress( transformerDeployer, transformation.deploymentNonce ); // Call `transformer.transform()` as the wallet. bytes memory resultData = wallet.executeDelegateCall( // The call target. transformer, // Call data. abi.encodeWithSelector( IERC20Transformer.transform.selector, callDataHash, taker, transformation.data ) ); // Ensure the transformer returned the magic bytes. if (resultData.length != 32 || abi.decode(resultData, (bytes4)) != LibERC20Transformer.TRANSFORMER_SUCCESS ) { LibTransformERC20RichErrors.TransformerFailedError( transformer, transformation.data, resultData ).rrevert(); } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "./LibStorage.sol"; import "../external/IFlashWallet.sol"; /// @dev Storage helpers for the `TokenSpender` feature. library LibTransformERC20Storage { /// @dev Storage bucket for this feature. struct Storage { // The current wallet instance. IFlashWallet wallet; // The transformer deployer address. address transformerDeployer; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.getStorageSlot( LibStorage.StorageId.TransformERC20 ); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor_slot := storageSlot } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; library LibERC20Transformer { using LibERC20TokenV06 for IERC20TokenV06; /// @dev ETH pseudo-token address. address constant internal ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Return value indicating success in `IERC20Transformer.transform()`. /// This is just `keccak256('TRANSFORMER_SUCCESS')`. bytes4 constant internal TRANSFORMER_SUCCESS = 0x13c9929e; /// @dev Transfer ERC20 tokens and ETH. /// @param token An ERC20 or the ETH pseudo-token address (`ETH_TOKEN_ADDRESS`). /// @param to The recipient. /// @param amount The transfer amount. function transformerTransfer( IERC20TokenV06 token, address payable to, uint256 amount ) internal { if (isTokenETH(token)) { to.transfer(amount); } else { token.compatTransfer(to, amount); } } /// @dev Check if a token is the ETH pseudo-token. /// @param token The token to check. /// @return isETH `true` if the token is the ETH pseudo-token. function isTokenETH(IERC20TokenV06 token) internal pure returns (bool isETH) { return address(token) == ETH_TOKEN_ADDRESS; } /// @dev Check the balance of an ERC20 token or ETH. /// @param token An ERC20 or the ETH pseudo-token address (`ETH_TOKEN_ADDRESS`). /// @param owner Holder of the tokens. /// @return tokenBalance The balance of `owner`. function getTokenBalanceOf(IERC20TokenV06 token, address owner) internal view returns (uint256 tokenBalance) { if (isTokenETH(token)) { return owner.balance; } return token.balanceOf(owner); } /// @dev RLP-encode a 32-bit or less account nonce. /// @param nonce A positive integer in the range 0 <= nonce < 2^32. /// @return rlpNonce The RLP encoding. function rlpEncodeNonce(uint32 nonce) internal pure returns (bytes memory rlpNonce) { // See https://github.com/ethereum/wiki/wiki/RLP for RLP encoding rules. if (nonce == 0) { rlpNonce = new bytes(1); rlpNonce[0] = 0x80; } else if (nonce < 0x80) { rlpNonce = new bytes(1); rlpNonce[0] = byte(uint8(nonce)); } else if (nonce <= 0xFF) { rlpNonce = new bytes(2); rlpNonce[0] = 0x81; rlpNonce[1] = byte(uint8(nonce)); } else if (nonce <= 0xFFFF) { rlpNonce = new bytes(3); rlpNonce[0] = 0x82; rlpNonce[1] = byte(uint8((nonce & 0xFF00) >> 8)); rlpNonce[2] = byte(uint8(nonce)); } else if (nonce <= 0xFFFFFF) { rlpNonce = new bytes(4); rlpNonce[0] = 0x83; rlpNonce[1] = byte(uint8((nonce & 0xFF0000) >> 16)); rlpNonce[2] = byte(uint8((nonce & 0xFF00) >> 8)); rlpNonce[3] = byte(uint8(nonce)); } else { rlpNonce = new bytes(5); rlpNonce[0] = 0x84; rlpNonce[1] = byte(uint8((nonce & 0xFF000000) >> 24)); rlpNonce[2] = byte(uint8((nonce & 0xFF0000) >> 16)); rlpNonce[3] = byte(uint8((nonce & 0xFF00) >> 8)); rlpNonce[4] = byte(uint8(nonce)); } } /// @dev Compute the expected deployment address by `deployer` at /// the nonce given by `deploymentNonce`. /// @param deployer The address of the deployer. /// @param deploymentNonce The nonce that the deployer had when deploying /// a contract. /// @return deploymentAddress The deployment address. function getDeployedAddress(address deployer, uint32 deploymentNonce) internal pure returns (address payable deploymentAddress) { // The address of if a deployed contract is the lower 20 bytes of the // hash of the RLP-encoded deployer's account address + account nonce. // See: https://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed bytes memory rlpNonce = rlpEncodeNonce(deploymentNonce); return address(uint160(uint256(keccak256(abi.encodePacked( byte(uint8(0xC0 + 21 + rlpNonce.length)), byte(uint8(0x80 + 20)), deployer, rlpNonce ))))); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../ZeroEx.sol"; import "../features/IOwnable.sol"; import "../features/TokenSpender.sol"; import "../features/TransformERC20.sol"; import "../external/AllowanceTarget.sol"; import "./InitialMigration.sol"; /// @dev A contract for deploying and configuring the full ZeroEx contract. contract FullMigration { // solhint-disable no-empty-blocks,indent /// @dev Features to add the the proxy contract. struct Features { SimpleFunctionRegistry registry; Ownable ownable; TokenSpender tokenSpender; TransformERC20 transformERC20; } /// @dev Parameters needed to initialize features. struct MigrateOpts { address transformerDeployer; } /// @dev The allowed caller of `deploy()`. address public immutable deployer; /// @dev The initial migration contract. InitialMigration private _initialMigration; /// @dev Instantiate this contract and set the allowed caller of `deploy()` /// to `deployer`. /// @param deployer_ The allowed caller of `deploy()`. constructor(address payable deployer_) public { deployer = deployer_; // Create an initial migration contract with this contract set to the // allowed deployer. _initialMigration = new InitialMigration(address(this)); } /// @dev Deploy the `ZeroEx` contract with the full feature set, /// transfer ownership to `owner`, then self-destruct. /// @param owner The owner of the contract. /// @param features Features to add to the proxy. /// @return zeroEx The deployed and configured `ZeroEx` contract. /// @param migrateOpts Parameters needed to initialize features. function deploy( address payable owner, Features memory features, MigrateOpts memory migrateOpts ) public returns (ZeroEx zeroEx) { require(msg.sender == deployer, "FullMigration/INVALID_SENDER"); // Perform the initial migration with the owner set to this contract. zeroEx = _initialMigration.deploy( address(uint160(address(this))), InitialMigration.BootstrapFeatures({ registry: features.registry, ownable: features.ownable }) ); // Add features. _addFeatures(zeroEx, owner, features, migrateOpts); // Transfer ownership to the real owner. IOwnable(address(zeroEx)).transferOwnership(owner); // Self-destruct. this.die(owner); } /// @dev Destroy this contract. Only callable from ourselves (from `deploy()`). /// @param ethRecipient Receiver of any ETH in this contract. function die(address payable ethRecipient) external virtual { require(msg.sender == address(this), "FullMigration/INVALID_SENDER"); // This contract should not hold any funds but we send // them to the ethRecipient just in case. selfdestruct(ethRecipient); } /// @dev Deploy and register features to the ZeroEx contract. /// @param zeroEx The bootstrapped ZeroEx contract. /// @param owner The ultimate owner of the ZeroEx contract. /// @param features Features to add to the proxy. /// @param migrateOpts Parameters needed to initialize features. function _addFeatures( ZeroEx zeroEx, address owner, Features memory features, MigrateOpts memory migrateOpts ) private { IOwnable ownable = IOwnable(address(zeroEx)); // TokenSpender { // Create the allowance target. AllowanceTarget allowanceTarget = new AllowanceTarget(); // Let the ZeroEx contract use the allowance target. allowanceTarget.addAuthorizedAddress(address(zeroEx)); // Transfer ownership of the allowance target to the (real) owner. allowanceTarget.transferOwnership(owner); // Register the feature. ownable.migrate( address(features.tokenSpender), abi.encodeWithSelector( TokenSpender.migrate.selector, allowanceTarget ), address(this) ); } // TransformERC20 { // Register the feature. ownable.migrate( address(features.transformERC20), abi.encodeWithSelector( TransformERC20.migrate.selector, migrateOpts.transformerDeployer ), address(this) ); } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../ZeroEx.sol"; import "../features/IBootstrap.sol"; import "../features/SimpleFunctionRegistry.sol"; import "../features/Ownable.sol"; import "./LibBootstrap.sol"; /// @dev A contract for deploying and configuring a minimal ZeroEx contract. contract InitialMigration { /// @dev Features to bootstrap into the the proxy contract. struct BootstrapFeatures { SimpleFunctionRegistry registry; Ownable ownable; } /// @dev The allowed caller of `deploy()`. In production, this would be /// the governor. address public immutable deployer; /// @dev The real address of this contract. address private immutable _implementation; /// @dev Instantiate this contract and set the allowed caller of `deploy()` /// to `deployer_`. /// @param deployer_ The allowed caller of `deploy()`. constructor(address deployer_) public { deployer = deployer_; _implementation = address(this); } /// @dev Deploy the `ZeroEx` contract with the minimum feature set, /// transfers ownership to `owner`, then self-destructs. /// Only callable by `deployer` set in the contstructor. /// @param owner The owner of the contract. /// @param features Features to bootstrap into the proxy. /// @return zeroEx The deployed and configured `ZeroEx` contract. function deploy(address payable owner, BootstrapFeatures memory features) public virtual returns (ZeroEx zeroEx) { // Must be called by the allowed deployer. require(msg.sender == deployer, "InitialMigration/INVALID_SENDER"); // Deploy the ZeroEx contract, setting ourselves as the bootstrapper. zeroEx = new ZeroEx(); // Bootstrap the initial feature set. IBootstrap(address(zeroEx)).bootstrap( address(this), abi.encodeWithSelector(this.bootstrap.selector, owner, features) ); // Self-destruct. This contract should not hold any funds but we send // them to the owner just in case. this.die(owner); } /// @dev Sets up the initial state of the `ZeroEx` contract. /// The `ZeroEx` contract will delegatecall into this function. /// @param owner The new owner of the ZeroEx contract. /// @param features Features to bootstrap into the proxy. /// @return success Magic bytes if successful. function bootstrap(address owner, BootstrapFeatures memory features) public virtual returns (bytes4 success) { // Deploy and migrate the initial features. // Order matters here. // Initialize Registry. LibBootstrap.delegatecallBootstrapFunction( address(features.registry), abi.encodeWithSelector( SimpleFunctionRegistry.bootstrap.selector ) ); // Initialize Ownable. LibBootstrap.delegatecallBootstrapFunction( address(features.ownable), abi.encodeWithSelector( Ownable.bootstrap.selector ) ); // De-register `SimpleFunctionRegistry._extendSelf`. SimpleFunctionRegistry(address(this)).rollback( SimpleFunctionRegistry._extendSelf.selector, address(0) ); // Transfer ownership to the real owner. Ownable(address(this)).transferOwnership(owner); success = LibBootstrap.BOOTSTRAP_SUCCESS; } /// @dev Self-destructs this contract. Only callable by this contract. /// @param ethRecipient Who to transfer outstanding ETH to. function die(address payable ethRecipient) public virtual { require(msg.sender == _implementation, "InitialMigration/INVALID_SENDER"); selfdestruct(ethRecipient); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "../errors/LibTransformERC20RichErrors.sol"; import "./Transformer.sol"; import "./LibERC20Transformer.sol"; /// @dev A transformer that transfers tokens to arbitrary addresses. contract AffiliateFeeTransformer is Transformer { // solhint-disable no-empty-blocks using LibRichErrorsV06 for bytes; using LibSafeMathV06 for uint256; using LibERC20Transformer for IERC20TokenV06; /// @dev Information for a single fee. struct TokenFee { // The token to transfer to `recipient`. IERC20TokenV06 token; // Amount of each `token` to transfer to `recipient`. // If `amount == uint256(-1)`, the entire balance of `token` will be // transferred. uint256 amount; // Recipient of `token`. address payable recipient; } uint256 private constant MAX_UINT256 = uint256(-1); /// @dev Create this contract. constructor() public Transformer() {} /// @dev Transfers tokens to recipients. /// @param data ABI-encoded `TokenFee[]`, indicating which tokens to transfer. /// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`). function transform( bytes32, // callDataHash, address payable, // taker, bytes calldata data ) external override returns (bytes4 success) { TokenFee[] memory fees = abi.decode(data, (TokenFee[])); // Transfer tokens to recipients. for (uint256 i = 0; i < fees.length; ++i) { uint256 amount = fees[i].amount; if (amount == MAX_UINT256) { amount = LibERC20Transformer.getTokenBalanceOf(fees[i].token, address(this)); } if (amount != 0) { fees[i].token.transformerTransfer(fees[i].recipient, amount); } } return LibERC20Transformer.TRANSFORMER_SUCCESS; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../errors/LibTransformERC20RichErrors.sol"; import "./IERC20Transformer.sol"; /// @dev Abstract base class for transformers. abstract contract Transformer is IERC20Transformer { using LibRichErrorsV06 for bytes; /// @dev The address of the deployer. address public immutable deployer; /// @dev The original address of this contract. address private immutable _implementation; /// @dev Create this contract. constructor() public { deployer = msg.sender; _implementation = address(this); } /// @dev Destruct this contract. Only callable by the deployer and will not /// succeed in the context of a delegatecall (from another contract). /// @param ethRecipient The recipient of ETH held in this contract. function die(address payable ethRecipient) external virtual { // Only the deployer can call this. if (msg.sender != deployer) { LibTransformERC20RichErrors .OnlyCallableByDeployerError(msg.sender, deployer) .rrevert(); } // Must be executing our own context. if (address(this) != _implementation) { LibTransformERC20RichErrors .InvalidExecutionContextError(address(this), _implementation) .rrevert(); } selfdestruct(ethRecipient); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibMathV06.sol"; import "../errors/LibTransformERC20RichErrors.sol"; import "../vendor/v3/IExchange.sol"; import "./Transformer.sol"; import "./LibERC20Transformer.sol"; /// @dev A transformer that fills an ERC20 market sell/buy quote. contract FillQuoteTransformer is Transformer { using LibERC20TokenV06 for IERC20TokenV06; using LibERC20Transformer for IERC20TokenV06; using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; /// @dev Whether we are performing a market sell or buy. enum Side { Sell, Buy } /// @dev Transform data to ABI-encode and pass into `transform()`. struct TransformData { // Whether we aer performing a market sell or buy. Side side; // The token being sold. // This should be an actual token, not the ETH pseudo-token. IERC20TokenV06 sellToken; // The token being bought. // This should be an actual token, not the ETH pseudo-token. IERC20TokenV06 buyToken; // The orders to fill. IExchange.Order[] orders; // Signatures for each respective order in `orders`. bytes[] signatures; // Maximum fill amount for each order. This may be shorter than the // number of orders, where missing entries will be treated as `uint256(-1)`. // For sells, this will be the maximum sell amount (taker asset). // For buys, this will be the maximum buy amount (maker asset). uint256[] maxOrderFillAmounts; // Amount of `sellToken` to sell or `buyToken` to buy. // For sells, this may be `uint256(-1)` to sell the entire balance of // `sellToken`. uint256 fillAmount; } /// @dev Results of a call to `_fillOrder()`. struct FillOrderResults { // The amount of taker tokens sold, according to balance checks. uint256 takerTokenSoldAmount; // The amount of maker tokens sold, according to balance checks. uint256 makerTokenBoughtAmount; // The amount of protocol fee paid. uint256 protocolFeePaid; } /// @dev The Exchange ERC20Proxy ID. bytes4 private constant ERC20_ASSET_PROXY_ID = 0xf47261b0; /// @dev Maximum uint256 value. uint256 private constant MAX_UINT256 = uint256(-1); /// @dev The Exchange contract. IExchange public immutable exchange; /// @dev The ERC20Proxy address. address public immutable erc20Proxy; /// @dev Create this contract. /// @param exchange_ The Exchange V3 instance. constructor(IExchange exchange_) public Transformer() { exchange = exchange_; erc20Proxy = exchange_.getAssetProxy(ERC20_ASSET_PROXY_ID); } /// @dev Sell this contract's entire balance of of `sellToken` in exchange /// for `buyToken` by filling `orders`. Protocol fees should be attached /// to this call. `buyToken` and excess ETH will be transferred back to the caller. /// @param data_ ABI-encoded `TransformData`. /// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`). function transform( bytes32, // callDataHash, address payable, // taker, bytes calldata data_ ) external override returns (bytes4 success) { TransformData memory data = abi.decode(data_, (TransformData)); // Validate data fields. if (data.sellToken.isTokenETH() || data.buyToken.isTokenETH()) { LibTransformERC20RichErrors.InvalidTransformDataError( LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_TOKENS, data_ ).rrevert(); } if (data.orders.length != data.signatures.length) { LibTransformERC20RichErrors.InvalidTransformDataError( LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_ARRAY_LENGTH, data_ ).rrevert(); } if (data.side == Side.Sell && data.fillAmount == MAX_UINT256) { // If `sellAmount == -1 then we are selling // the entire balance of `sellToken`. This is useful in cases where // the exact sell amount is not exactly known in advance, like when // unwrapping Chai/cUSDC/cDAI. data.fillAmount = data.sellToken.getTokenBalanceOf(address(this)); } // Approve the ERC20 proxy to spend `sellToken`. data.sellToken.approveIfBelow(erc20Proxy, data.fillAmount); // Fill the orders. uint256 singleProtocolFee = exchange.protocolFeeMultiplier().safeMul(tx.gasprice); uint256 ethRemaining = address(this).balance; uint256 boughtAmount = 0; uint256 soldAmount = 0; for (uint256 i = 0; i < data.orders.length; ++i) { // Check if we've hit our targets. if (data.side == Side.Sell) { // Market sell check. if (soldAmount >= data.fillAmount) { break; } } else { // Market buy check. if (boughtAmount >= data.fillAmount) { break; } } // Ensure we have enough ETH to cover the protocol fee. if (ethRemaining < singleProtocolFee) { LibTransformERC20RichErrors .InsufficientProtocolFeeError(ethRemaining, singleProtocolFee) .rrevert(); } // Fill the order. FillOrderResults memory results; if (data.side == Side.Sell) { // Market sell. results = _sellToOrder( data.buyToken, data.sellToken, data.orders[i], data.signatures[i], data.fillAmount.safeSub(soldAmount).min256( data.maxOrderFillAmounts.length > i ? data.maxOrderFillAmounts[i] : MAX_UINT256 ), singleProtocolFee ); } else { // Market buy. results = _buyFromOrder( data.buyToken, data.sellToken, data.orders[i], data.signatures[i], data.fillAmount.safeSub(boughtAmount).min256( data.maxOrderFillAmounts.length > i ? data.maxOrderFillAmounts[i] : MAX_UINT256 ), singleProtocolFee ); } // Accumulate totals. soldAmount = soldAmount.safeAdd(results.takerTokenSoldAmount); boughtAmount = boughtAmount.safeAdd(results.makerTokenBoughtAmount); ethRemaining = ethRemaining.safeSub(results.protocolFeePaid); } // Ensure we hit our targets. if (data.side == Side.Sell) { // Market sell check. if (soldAmount < data.fillAmount) { LibTransformERC20RichErrors .IncompleteFillSellQuoteError( address(data.sellToken), soldAmount, data.fillAmount ).rrevert(); } } else { // Market buy check. if (boughtAmount < data.fillAmount) { LibTransformERC20RichErrors .IncompleteFillBuyQuoteError( address(data.buyToken), boughtAmount, data.fillAmount ).rrevert(); } } return LibERC20Transformer.TRANSFORMER_SUCCESS; } /// @dev Try to sell up to `sellAmount` from an order. /// @param makerToken The maker/buy token. /// @param takerToken The taker/sell token. /// @param order The order to fill. /// @param signature The signature for `order`. /// @param sellAmount Amount of taker token to sell. /// @param protocolFee The protocol fee needed to fill `order`. function _sellToOrder( IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, IExchange.Order memory order, bytes memory signature, uint256 sellAmount, uint256 protocolFee ) private returns (FillOrderResults memory results) { IERC20TokenV06 takerFeeToken = _getTokenFromERC20AssetData(order.takerFeeAssetData); uint256 takerTokenFillAmount = sellAmount; if (order.takerFee != 0) { if (takerFeeToken == makerToken) { // Taker fee is payable in the maker token, so we need to // approve the proxy to spend the maker token. // It isn't worth computing the actual taker fee // since `approveIfBelow()` will set the allowance to infinite. We // just need a reasonable upper bound to avoid unnecessarily re-approving. takerFeeToken.approveIfBelow(erc20Proxy, order.takerFee); } else if (takerFeeToken == takerToken){ // Taker fee is payable in the taker token, so we need to // reduce the fill amount to cover the fee. // takerTokenFillAmount' = // (takerTokenFillAmount * order.takerAssetAmount) / // (order.takerAssetAmount + order.takerFee) takerTokenFillAmount = LibMathV06.getPartialAmountCeil( order.takerAssetAmount, order.takerAssetAmount.safeAdd(order.takerFee), sellAmount ); } else { // Only support taker or maker asset denominated taker fees. LibTransformERC20RichErrors.InvalidTakerFeeTokenError( address(takerFeeToken) ).rrevert(); } } // Clamp fill amount to order size. takerTokenFillAmount = LibSafeMathV06.min256( takerTokenFillAmount, order.takerAssetAmount ); // Perform the fill. return _fillOrder( order, signature, takerTokenFillAmount, protocolFee, makerToken, takerFeeToken == takerToken ); } /// @dev Try to buy up to `buyAmount` from an order. /// @param makerToken The maker/buy token. /// @param takerToken The taker/sell token. /// @param order The order to fill. /// @param signature The signature for `order`. /// @param buyAmount Amount of maker token to buy. /// @param protocolFee The protocol fee needed to fill `order`. function _buyFromOrder( IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, IExchange.Order memory order, bytes memory signature, uint256 buyAmount, uint256 protocolFee ) private returns (FillOrderResults memory results) { IERC20TokenV06 takerFeeToken = _getTokenFromERC20AssetData(order.takerFeeAssetData); // Compute the default taker token fill amount. uint256 takerTokenFillAmount = LibMathV06.getPartialAmountCeil( buyAmount, order.makerAssetAmount, order.takerAssetAmount ); if (order.takerFee != 0) { if (takerFeeToken == makerToken) { // Taker fee is payable in the maker token. // Adjust the taker token fill amount to account for maker // tokens being lost to the taker fee. // takerTokenFillAmount' = // (order.takerAssetAmount * buyAmount) / // (order.makerAssetAmount - order.takerFee) takerTokenFillAmount = LibMathV06.getPartialAmountCeil( buyAmount, order.makerAssetAmount.safeSub(order.takerFee), order.takerAssetAmount ); // Approve the proxy to spend the maker token. // It isn't worth computing the actual taker fee // since `approveIfBelow()` will set the allowance to infinite. We // just need a reasonable upper bound to avoid unnecessarily re-approving. takerFeeToken.approveIfBelow(erc20Proxy, order.takerFee); } else if (takerFeeToken != takerToken) { // Only support taker or maker asset denominated taker fees. LibTransformERC20RichErrors.InvalidTakerFeeTokenError( address(takerFeeToken) ).rrevert(); } } // Clamp to order size. takerTokenFillAmount = LibSafeMathV06.min256( order.takerAssetAmount, takerTokenFillAmount ); // Perform the fill. return _fillOrder( order, signature, takerTokenFillAmount, protocolFee, makerToken, takerFeeToken == takerToken ); } /// @dev Attempt to fill an order. If the fill reverts, the revert will be /// swallowed and `results` will be zeroed out. /// @param order The order to fill. /// @param signature The order signature. /// @param takerAssetFillAmount How much taker asset to fill. /// @param protocolFee The protocol fee needed to fill this order. /// @param makerToken The maker token. /// @param isTakerFeeInTakerToken Whether the taker fee token is the same as the /// taker token. function _fillOrder( IExchange.Order memory order, bytes memory signature, uint256 takerAssetFillAmount, uint256 protocolFee, IERC20TokenV06 makerToken, bool isTakerFeeInTakerToken ) private returns (FillOrderResults memory results) { // Track changes in the maker token balance. uint256 initialMakerTokenBalance = makerToken.balanceOf(address(this)); try exchange.fillOrder {value: protocolFee} (order, takerAssetFillAmount, signature) returns (IExchange.FillResults memory fillResults) { // Update maker quantity based on changes in token balances. results.makerTokenBoughtAmount = makerToken.balanceOf(address(this)) .safeSub(initialMakerTokenBalance); // We can trust the other fill result quantities. results.protocolFeePaid = fillResults.protocolFeePaid; results.takerTokenSoldAmount = fillResults.takerAssetFilledAmount; // If the taker fee is payable in the taker asset, include the // taker fee in the total amount sold. if (isTakerFeeInTakerToken) { results.takerTokenSoldAmount = results.takerTokenSoldAmount.safeAdd(fillResults.takerFeePaid); } } catch (bytes memory) { // Swallow failures, leaving all results as zero. } } /// @dev Extract the token from plain ERC20 asset data. /// If the asset-data is empty, a zero token address will be returned. /// @param assetData The order asset data. function _getTokenFromERC20AssetData(bytes memory assetData) private pure returns (IERC20TokenV06 token) { if (assetData.length == 0) { return IERC20TokenV06(address(0)); } if (assetData.length != 36 || LibBytesV06.readBytes4(assetData, 0) != ERC20_ASSET_PROXY_ID) { LibTransformERC20RichErrors .InvalidERC20AssetDataError(assetData) .rrevert(); } return IERC20TokenV06(LibBytesV06.readAddress(assetData, 16)); } } /* 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.5; import "./LibSafeMathV06.sol"; import "./errors/LibRichErrorsV06.sol"; import "./errors/LibMathRichErrorsV06.sol"; library LibMathV06 { using LibSafeMathV06 for uint256; /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return partialAmount Partial value of target rounded down. function safeGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorFloor( numerator, denominator, target )) { LibRichErrorsV06.rrevert(LibMathRichErrorsV06.RoundingError( numerator, denominator, target )); } partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return partialAmount Partial value of target rounded up. function safeGetPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorCeil( numerator, denominator, target )) { LibRichErrorsV06.rrevert(LibMathRichErrorsV06.RoundingError( numerator, denominator, target )); } // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = numerator.safeMul(target) .safeAdd(denominator.safeSub(1)) .safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return partialAmount Partial value of target rounded down. function getPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return partialAmount Partial value of target rounded up. function getPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = numerator.safeMul(target) .safeAdd(denominator.safeSub(1)) .safeDiv(denominator); return partialAmount; } /// @dev Checks if rounding error >= 0.1% when rounding down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return isError Rounding error is present. function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrorsV06.rrevert(LibMathRichErrorsV06.DivisionByZeroError()); } // The absolute rounding error is the difference between the rounded // value and the ideal value. The relative rounding error is the // absolute rounding error divided by the absolute value of the // ideal value. This is undefined when the ideal value is zero. // // The ideal value is `numerator * target / denominator`. // Let's call `numerator * target % denominator` the remainder. // The absolute error is `remainder / denominator`. // // When the ideal value is zero, we require the absolute error to // be zero. Fortunately, this is always the case. The ideal value is // zero iff `numerator == 0` and/or `target == 0`. In this case the // remainder and absolute error are also zero. if (target == 0 || numerator == 0) { return false; } // Otherwise, we want the relative rounding error to be strictly // less than 0.1%. // The relative error is `remainder / (numerator * target)`. // We want the relative error less than 1 / 1000: // remainder / (numerator * denominator) < 1 / 1000 // or equivalently: // 1000 * remainder < numerator * target // so we have a rounding error iff: // 1000 * remainder >= numerator * target uint256 remainder = mulmod( target, numerator, denominator ); isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } /// @dev Checks if rounding error >= 0.1% when rounding up. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return isError Rounding error is present. function isRoundingErrorCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrorsV06.rrevert(LibMathRichErrorsV06.DivisionByZeroError()); } // See the comments in `isRoundingError`. if (target == 0 || numerator == 0) { // When either is zero, the ideal value and rounded value are zero // and there is no rounding error. (Although the relative error // is undefined.) return false; } // Compute remainder as before uint256 remainder = mulmod( target, numerator, denominator ); remainder = denominator.safeSub(remainder) % denominator; isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibMathRichErrorsV06 { // bytes4(keccak256("DivisionByZeroError()")) bytes internal constant DIVISION_BY_ZERO_ERROR = hex"a791837c"; // bytes4(keccak256("RoundingError(uint256,uint256,uint256)")) bytes4 internal constant ROUNDING_ERROR_SELECTOR = 0x339f3de2; // solhint-disable func-name-mixedcase function DivisionByZeroError() internal pure returns (bytes memory) { return DIVISION_BY_ZERO_ERROR; } function RoundingError( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ROUNDING_ERROR_SELECTOR, numerator, denominator, target ); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; /// @dev Interface to the V3 Exchange. interface IExchange { /// @dev V3 Order structure. struct Order { // Address that created the order. address makerAddress; // Address that is allowed to fill the order. // If set to 0, any address is allowed to fill the order. address takerAddress; // Address that will recieve fees when order is filled. address feeRecipientAddress; // Address that is allowed to call Exchange contract methods that affect this order. // If set to 0, any address is allowed to call these methods. address senderAddress; // Amount of makerAsset being offered by maker. Must be greater than 0. uint256 makerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0. uint256 takerAssetAmount; // Fee paid to feeRecipient by maker when order is filled. uint256 makerFee; // Fee paid to feeRecipient by taker when order is filled. uint256 takerFee; // Timestamp in seconds at which order expires. uint256 expirationTimeSeconds; // Arbitrary number to facilitate uniqueness of the order's hash. uint256 salt; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. // The leading bytes4 references the id of the asset proxy. bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. // The leading bytes4 references the id of the asset proxy. bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset. // The leading bytes4 references the id of the asset proxy. bytes makerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset. // The leading bytes4 references the id of the asset proxy. bytes takerFeeAssetData; } /// @dev V3 `fillOrder()` results.` struct FillResults { // Total amount of makerAsset(s) filled. uint256 makerAssetFilledAmount; // Total amount of takerAsset(s) filled. uint256 takerAssetFilledAmount; // Total amount of fees paid by maker(s) to feeRecipient(s). uint256 makerFeePaid; // Total amount of fees paid by taker to feeRecipients(s). uint256 takerFeePaid; // Total amount of fees paid by taker to the staking contract. uint256 protocolFeePaid; } /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return fillResults Amounts filled and fees paid by maker and taker. function fillOrder( Order calldata order, uint256 takerAssetFillAmount, bytes calldata signature ) external payable returns (FillResults memory fillResults); /// @dev Returns the protocolFeeMultiplier /// @return multiplier The multiplier for protocol fees. function protocolFeeMultiplier() external view returns (uint256 multiplier); /// @dev Gets an asset proxy. /// @param assetProxyId Id of the asset proxy. /// @return proxyAddress The asset proxy registered to assetProxyId. /// Returns 0x0 if no proxy is registered. function getAssetProxy(bytes4 assetProxyId) external view returns (address proxyAddress); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "../errors/LibTransformERC20RichErrors.sol"; import "./Transformer.sol"; import "./LibERC20Transformer.sol"; /// @dev A transformer that transfers tokens to the taker. contract PayTakerTransformer is Transformer { // solhint-disable no-empty-blocks using LibRichErrorsV06 for bytes; using LibSafeMathV06 for uint256; using LibERC20Transformer for IERC20TokenV06; /// @dev Transform data to ABI-encode and pass into `transform()`. struct TransformData { // The tokens to transfer to the taker. IERC20TokenV06[] tokens; // Amount of each token in `tokens` to transfer to the taker. // `uint(-1)` will transfer the entire balance. uint256[] amounts; } /// @dev Maximum uint256 value. uint256 private constant MAX_UINT256 = uint256(-1); /// @dev Create this contract. constructor() public Transformer() {} /// @dev Forwards tokens to the taker. /// @param taker The taker address (caller of `TransformERC20.transformERC20()`). /// @param data_ ABI-encoded `TransformData`, indicating which tokens to transfer. /// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`). function transform( bytes32, // callDataHash, address payable taker, bytes calldata data_ ) external override returns (bytes4 success) { TransformData memory data = abi.decode(data_, (TransformData)); // Transfer tokens directly to the taker. for (uint256 i = 0; i < data.tokens.length; ++i) { // The `amounts` array can be shorter than the `tokens` array. // Missing elements are treated as `uint256(-1)`. uint256 amount = data.amounts.length > i ? data.amounts[i] : uint256(-1); if (amount == MAX_UINT256) { amount = data.tokens[i].getTokenBalanceOf(address(this)); } if (amount != 0) { data.tokens[i].transformerTransfer(taker, amount); } } return LibERC20Transformer.TRANSFORMER_SUCCESS; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol"; import "../errors/LibTransformERC20RichErrors.sol"; import "./Transformer.sol"; import "./LibERC20Transformer.sol"; /// @dev A transformer that wraps or unwraps WETH. contract WethTransformer is Transformer { using LibRichErrorsV06 for bytes; using LibSafeMathV06 for uint256; using LibERC20Transformer for IERC20TokenV06; /// @dev Transform data to ABI-encode and pass into `transform()`. struct TransformData { // The token to wrap/unwrap. Must be either ETH or WETH. IERC20TokenV06 token; // Amount of `token` to wrap or unwrap. // `uint(-1)` will unwrap the entire balance. uint256 amount; } /// @dev The WETH contract address. IEtherTokenV06 public immutable weth; /// @dev Maximum uint256 value. uint256 private constant MAX_UINT256 = uint256(-1); /// @dev Construct the transformer and store the WETH address in an immutable. /// @param weth_ The weth token. constructor(IEtherTokenV06 weth_) public Transformer() { weth = weth_; } /// @dev Wraps and unwraps WETH. /// @param data_ ABI-encoded `TransformData`, indicating which token to wrap/umwrap. /// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`). function transform( bytes32, // callDataHash, address payable, // taker, bytes calldata data_ ) external override returns (bytes4 success) { TransformData memory data = abi.decode(data_, (TransformData)); if (!data.token.isTokenETH() && data.token != weth) { LibTransformERC20RichErrors.InvalidTransformDataError( LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_TOKENS, data_ ).rrevert(); } uint256 amount = data.amount; if (amount == MAX_UINT256) { amount = data.token.getTokenBalanceOf(address(this)); } if (amount != 0) { if (data.token.isTokenETH()) { // Wrap ETH. weth.deposit{value: amount}(); } else { // Unwrap WETH. weth.withdraw(amount); } } return LibERC20Transformer.TRANSFORMER_SUCCESS; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; import "./IERC20TokenV06.sol"; interface IEtherTokenV06 is IERC20TokenV06 { /// @dev Wrap ether. function deposit() external payable; /// @dev Unwrap ether. function withdraw(uint256 amount) external; } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; interface ITestSimpleFunctionRegistryFeature { function testFn() external view returns (uint256 id); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; contract TestCallTarget { event CallTargetCalled( address context, address sender, bytes data, uint256 value ); bytes4 private constant MAGIC_BYTES = 0x12345678; bytes private constant REVERTING_DATA = hex"1337"; fallback() external payable { if (keccak256(msg.data) == keccak256(REVERTING_DATA)) { revert("TestCallTarget/REVERT"); } emit CallTargetCalled( address(this), msg.sender, msg.data, msg.value ); bytes4 rval = MAGIC_BYTES; assembly { mstore(0, rval) return(0, 32) } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; contract TestDelegateCaller { function executeDelegateCall( address target, bytes calldata callData ) external { (bool success, bytes memory resultData) = target.delegatecall(callData); if (!success) { assembly { revert(add(resultData, 32), mload(resultData)) } } assembly { return(add(resultData, 32), mload(resultData)) } } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibMathV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "../src/vendor/v3/IExchange.sol"; import "./TestMintableERC20Token.sol"; contract TestFillQuoteTransformerExchange { struct FillBehavior { // How much of the order is filled, in taker asset amount. uint256 filledTakerAssetAmount; // Scaling for maker assets minted, in 1e18. uint256 makerAssetMintRatio; } uint256 private constant PROTOCOL_FEE_MULTIPLIER = 1337; using LibSafeMathV06 for uint256; function fillOrder( IExchange.Order calldata order, uint256 takerAssetFillAmount, bytes calldata signature ) external payable returns (IExchange.FillResults memory fillResults) { require( signature.length != 0, "TestFillQuoteTransformerExchange/INVALID_SIGNATURE" ); // The signature is the ABI-encoded FillBehavior data. FillBehavior memory behavior = abi.decode(signature, (FillBehavior)); uint256 protocolFee = PROTOCOL_FEE_MULTIPLIER * tx.gasprice; require( msg.value == protocolFee, "TestFillQuoteTransformerExchange/INSUFFICIENT_PROTOCOL_FEE" ); // Return excess protocol fee. msg.sender.transfer(msg.value - protocolFee); // Take taker tokens. TestMintableERC20Token takerToken = _getTokenFromAssetData(order.takerAssetData); takerAssetFillAmount = LibSafeMathV06.min256( order.takerAssetAmount.safeSub(behavior.filledTakerAssetAmount), takerAssetFillAmount ); require( takerToken.getSpendableAmount(msg.sender, address(this)) >= takerAssetFillAmount, "TestFillQuoteTransformerExchange/INSUFFICIENT_TAKER_FUNDS" ); takerToken.transferFrom(msg.sender, order.makerAddress, takerAssetFillAmount); // Mint maker tokens. uint256 makerAssetFilledAmount = LibMathV06.getPartialAmountFloor( takerAssetFillAmount, order.takerAssetAmount, order.makerAssetAmount ); TestMintableERC20Token makerToken = _getTokenFromAssetData(order.makerAssetData); makerToken.mint( msg.sender, LibMathV06.getPartialAmountFloor( behavior.makerAssetMintRatio, 1e18, makerAssetFilledAmount ) ); // Take taker fee. TestMintableERC20Token takerFeeToken = _getTokenFromAssetData(order.takerFeeAssetData); uint256 takerFee = LibMathV06.getPartialAmountFloor( takerAssetFillAmount, order.takerAssetAmount, order.takerFee ); require( takerFeeToken.getSpendableAmount(msg.sender, address(this)) >= takerFee, "TestFillQuoteTransformerExchange/INSUFFICIENT_TAKER_FEE_FUNDS" ); takerFeeToken.transferFrom(msg.sender, order.feeRecipientAddress, takerFee); fillResults.makerAssetFilledAmount = makerAssetFilledAmount; fillResults.takerAssetFilledAmount = takerAssetFillAmount; fillResults.makerFeePaid = uint256(-1); fillResults.takerFeePaid = takerFee; fillResults.protocolFeePaid = protocolFee; } function encodeBehaviorData(FillBehavior calldata behavior) external pure returns (bytes memory encoded) { return abi.encode(behavior); } function protocolFeeMultiplier() external pure returns (uint256) { return PROTOCOL_FEE_MULTIPLIER; } function getAssetProxy(bytes4) external view returns (address) { return address(this); } function _getTokenFromAssetData(bytes memory assetData) private pure returns (TestMintableERC20Token token) { return TestMintableERC20Token(LibBytesV06.readAddress(assetData, 16)); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; contract TestMintableERC20Token { mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; function transfer(address to, uint256 amount) external virtual returns (bool) { return transferFrom(msg.sender, to, amount); } function approve(address spender, uint256 amount) external virtual returns (bool) { allowance[msg.sender][spender] = amount; return true; } function mint(address owner, uint256 amount) external virtual { balanceOf[owner] += amount; } function burn(address owner, uint256 amount) external virtual { require(balanceOf[owner] >= amount, "TestMintableERC20Token/INSUFFICIENT_FUNDS"); balanceOf[owner] -= amount; } function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) { if (from != msg.sender) { require( allowance[from][msg.sender] >= amount, "TestMintableERC20Token/INSUFFICIENT_ALLOWANCE" ); allowance[from][msg.sender] -= amount; } require(balanceOf[from] >= amount, "TestMintableERC20Token/INSUFFICIENT_FUNDS"); balanceOf[from] -= amount; balanceOf[to] += amount; return true; } function getSpendableAmount(address owner, address spender) external view returns (uint256) { return balanceOf[owner] < allowance[owner][spender] ? balanceOf[owner] : allowance[owner][spender]; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../src/transformers/IERC20Transformer.sol"; import "./TestMintableERC20Token.sol"; import "./TestTransformerHost.sol"; contract TestFillQuoteTransformerHost is TestTransformerHost { function executeTransform( IERC20Transformer transformer, TestMintableERC20Token inputToken, uint256 inputTokenAmount, bytes calldata data ) external payable { if (inputTokenAmount != 0) { inputToken.mint(address(this), inputTokenAmount); } // Have to make this call externally because transformers aren't payable. this.rawExecuteTransform(transformer, bytes32(0), msg.sender, data); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../src/transformers/IERC20Transformer.sol"; import "../src/transformers/LibERC20Transformer.sol"; contract TestTransformerHost { using LibERC20Transformer for IERC20TokenV06; using LibRichErrorsV06 for bytes; function rawExecuteTransform( IERC20Transformer transformer, bytes32 callDataHash, address taker, bytes calldata data ) external { (bool _success, bytes memory resultData) = address(transformer).delegatecall(abi.encodeWithSelector( transformer.transform.selector, callDataHash, taker, data )); if (!_success) { resultData.rrevert(); } require( abi.decode(resultData, (bytes4)) == LibERC20Transformer.TRANSFORMER_SUCCESS, "TestTransformerHost/INVALID_TRANSFORMER_RESULT" ); } // solhint-disable receive() external payable {} // solhint-enable } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../src/ZeroEx.sol"; import "../src/features/IBootstrap.sol"; import "../src/migrations/FullMigration.sol"; contract TestFullMigration is FullMigration { address public dieRecipient; // solhint-disable-next-line no-empty-blocks constructor(address payable deployer) public FullMigration(deployer) {} function die(address payable ethRecipient) external override { dieRecipient = ethRecipient; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../src/ZeroEx.sol"; import "../src/features/IBootstrap.sol"; import "../src/migrations/InitialMigration.sol"; contract TestInitialMigration is InitialMigration { address public bootstrapFeature; address public dieRecipient; // solhint-disable-next-line no-empty-blocks constructor(address deployer) public InitialMigration(deployer) {} function callBootstrap(ZeroEx zeroEx) external { IBootstrap(address(zeroEx)).bootstrap(address(this), new bytes(0)); } function bootstrap(address owner, BootstrapFeatures memory features) public override returns (bytes4 success) { success = InitialMigration.bootstrap(owner, features); // Snoop the bootstrap feature contract. bootstrapFeature = ZeroEx(address(uint160(address(this)))) .getFunctionImplementation(IBootstrap.bootstrap.selector); } function die(address payable ethRecipient) public override { dieRecipient = ethRecipient; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../src/migrations/LibMigrate.sol"; import "../src/features/IOwnable.sol"; contract TestMigrator { event TestMigrateCalled( bytes callData, address owner ); function succeedingMigrate() external returns (bytes4 success) { emit TestMigrateCalled( msg.data, IOwnable(address(this)).owner() ); return LibMigrate.MIGRATE_SUCCESS; } function failingMigrate() external returns (bytes4 success) { emit TestMigrateCalled( msg.data, IOwnable(address(this)).owner() ); return 0xdeadbeef; } function revertingMigrate() external pure { revert("OOPSIE"); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../src/transformers/IERC20Transformer.sol"; import "../src/transformers/LibERC20Transformer.sol"; import "./TestMintableERC20Token.sol"; contract TestMintTokenERC20Transformer is IERC20Transformer { struct TransformData { IERC20TokenV06 inputToken; TestMintableERC20Token outputToken; uint256 burnAmount; uint256 mintAmount; uint256 feeAmount; } event MintTransform( address context, address caller, bytes32 callDataHash, address taker, bytes data, uint256 inputTokenBalance, uint256 ethBalance ); function transform( bytes32 callDataHash, address payable taker, bytes calldata data_ ) external override returns (bytes4 success) { TransformData memory data = abi.decode(data_, (TransformData)); emit MintTransform( address(this), msg.sender, callDataHash, taker, data_, data.inputToken.balanceOf(address(this)), address(this).balance ); // "Burn" input tokens. data.inputToken.transfer(address(0), data.burnAmount); // Mint output tokens. if (LibERC20Transformer.isTokenETH(IERC20TokenV06(address(data.outputToken)))) { taker.transfer(data.mintAmount); } else { data.outputToken.mint( taker, data.mintAmount ); // Burn fees from output. data.outputToken.burn(taker, data.feeAmount); } return LibERC20Transformer.TRANSFORMER_SUCCESS; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../src/fixins/FixinCommon.sol"; contract TestSimpleFunctionRegistryFeatureImpl1 is FixinCommon { function testFn() external pure returns (uint256 id) { return 1337; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../src/fixins/FixinCommon.sol"; contract TestSimpleFunctionRegistryFeatureImpl2 is FixinCommon { function testFn() external pure returns (uint256 id) { return 1338; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../src/features/TokenSpender.sol"; contract TestTokenSpender is TokenSpender { modifier onlySelf() override { _; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "./TestMintableERC20Token.sol"; contract TestTokenSpenderERC20Token is TestMintableERC20Token { event TransferFromCalled( address sender, address from, address to, uint256 amount ); // `transferFrom()` behavior depends on the value of `amount`. uint256 constant private EMPTY_RETURN_AMOUNT = 1337; uint256 constant private FALSE_RETURN_AMOUNT = 1338; uint256 constant private REVERT_RETURN_AMOUNT = 1339; function transferFrom(address from, address to, uint256 amount) public override returns (bool) { emit TransferFromCalled(msg.sender, from, to, amount); if (amount == EMPTY_RETURN_AMOUNT) { assembly { return(0, 0) } } if (amount == FALSE_RETURN_AMOUNT) { return false; } if (amount == REVERT_RETURN_AMOUNT) { revert("TestTokenSpenderERC20Token/Revert"); } return true; } function setBalanceAndAllowanceOf( address owner, uint256 balance, address spender, uint256 allowance_ ) external { balanceOf[owner] = balance; allowance[owner][spender] = allowance_; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../src/features/TransformERC20.sol"; contract TestTransformERC20 is TransformERC20 { // solhint-disable no-empty-blocks constructor() TransformERC20() public {} modifier onlySelf() override { _; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../src/transformers/Transformer.sol"; import "../src/transformers/LibERC20Transformer.sol"; contract TestTransformerBase is Transformer { function transform( bytes32, address payable, bytes calldata ) external override returns (bytes4 success) { return LibERC20Transformer.TRANSFORMER_SUCCESS; } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../src/transformers/LibERC20Transformer.sol"; contract TestTransformerDeployerTransformer { address payable public immutable deployer; constructor() public payable { deployer = msg.sender; } modifier onlyDeployer() { require(msg.sender == deployer, "TestTransformerDeployerTransformer/ONLY_DEPLOYER"); _; } function die() external onlyDeployer { selfdestruct(deployer); } function isDeployedByDeployer(uint32 nonce) external view returns (bool) { return LibERC20Transformer.getDeployedAddress(deployer, nonce) == address(this); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "./TestMintableERC20Token.sol"; contract TestWeth is TestMintableERC20Token { function deposit() external payable { this.mint(msg.sender, msg.value); } function withdraw(uint256 amount) external { require(balanceOf[msg.sender] >= amount, "TestWeth/INSUFFICIENT_FUNDS"); balanceOf[msg.sender] -= amount; msg.sender.transfer(amount); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../src/transformers/IERC20Transformer.sol"; import "./TestMintableERC20Token.sol"; import "./TestTransformerHost.sol"; import "./TestWeth.sol"; contract TestWethTransformerHost is TestTransformerHost { // solhint-disable TestWeth private immutable _weth; // solhint-enable constructor(TestWeth weth) public { _weth = weth; } function executeTransform( uint256 wethAmount, IERC20Transformer transformer, bytes calldata data ) external payable { if (wethAmount != 0) { _weth.deposit{value: wethAmount}(); } // Have to make this call externally because transformers aren't payable. this.rawExecuteTransform(transformer, bytes32(0), msg.sender, data); } } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "../src/fixins/FixinCommon.sol"; import "../src/ZeroEx.sol"; contract TestZeroExFeature is FixinCommon { event PayableFnCalled(uint256 value); event NotPayableFnCalled(); function payableFn() external payable { emit PayableFnCalled(msg.value); } function notPayableFn() external { emit NotPayableFnCalled(); } // solhint-disable no-empty-blocks function unimplmentedFn() external {} function internalFn() external onlySelf {} }
Retrieve the length of the rollback history for a function. selector The function selector. return rollbackLength The number of items in the rollback history for the function.
function getRollbackLength(bytes4 selector) external override view returns (uint256 rollbackLength) { return LibSimpleFunctionRegistryStorage.getStorage().implHistory[selector].length; }
5,368,693
./partial_match/1/0xE0dBED169e1a51375bd7E9B15B733bC8507338d7/sources/FirstBot.sol
set maximum transaction
function removeLimits() public onlyOwner { _maxTxSizeAmount = _tTotal; _maxWalletLimitSize = _tTotal; }
16,125,311
./full_match/80001/0x35C94EcA841160336c4b4bd648b55e52034448e1/sources/contracts/Contract.sol
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)); }
873,126
./full_match/80001/0xE5c8D133c3dBD7062bAe47b9323bB7ADEd006C38/sources/project_/contracts/ERC5006.sol
See {IERC165-supportsInterface}.
function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC1155Receiver, ERC1155) returns (bool) { return interfaceId == type(IERC5006).interfaceId || super.supportsInterface(interfaceId); }
5,573,673
pragma solidity ^0.4.4; import "./BaseBountyContract.sol"; import "./BaseChallengerContract.sol"; // Part of the PutYourMoneyWhereYourContractIs (bit.do/pymwyci) project. /** * @title creates and manages bounties. * * Responsible for running bounties. Authors of contracts can register their * BountyContract and challengers can use it to start a bounty challenge. */ contract BountyManager { event LogBountySubmitted(address bountyContract, uint bountySum, uint untilBlock); event LogBountyCanceled(address bountyContract); event LogChallengeInitiated(address bountyContract); event LogBountySuccess(address bountyContract, address challenger); // Percentage of bounty sum required as a deposit to challenge the bounty. uint8 constant DEPOSIT_PERCENTAGE = 5; uint constant MIN_BOUNTY_DEADLINE_IN_BLOCKS = 5083; // ~1 day @ 17s/block uint16 constant NUM_BLOCKS_LOCKED = 36; // ~10 minutes @ 17s/block uint constant MIN_BOUNTY_WEI = 1000000000000 wei; // 1e12 wei == 1e-6 ether address owner = msg.sender; // Where to send lost deposits to. These are deposits made by bounty // challengers who did not succeed in getting the bounty. address lostDepositsAddress; // Map from bountyContract. mapping(address => BountyInfo) bounties; mapping(address => uint) pendingWithdrawls; struct BountyInfo { // Bounty info bool exists; uint bountySum; uint runsUntilBlock; address bountyContract; address bountyOwner; // account to return the bounty to. bool cancelationRequested; // Challenge info uint lockedUntilBlock; address currentChallenger; address challengerContract; uint currentDeposit; } function BountyManager(address _lostDepositsAddress) { lostDepositsAddress = _lostDepositsAddress; } /** * Call this method to register your own bounty. * The value passed with the call will constitute the bounty. * deadlineBlockNumber constitutes the approximate end time of the bounty * (if a lock is initiated before then, BountyManager will let the challenger * try until the the lock end time). */ function registerBounty( address bountyContractAddress, uint deadlineBlockNumber) payable { if (bounties[bountyContractAddress].exists) throw; if (msg.value < MIN_BOUNTY_WEI) throw; if (deadlineBlockNumber <= block.number) throw; bounties[bountyContractAddress] = BountyInfo( { exists: true, bountySum: msg.value, runsUntilBlock: deadlineBlockNumber, bountyContract: bountyContractAddress, bountyOwner: msg.sender, cancelationRequested: false, lockedUntilBlock: 0, currentChallenger: 0, challengerContract: 0, currentDeposit: 0 }); LogBountySubmitted(bountyContractAddress, msg.value, deadlineBlockNumber); } /** * Formally initiates a challenge with contractTest. * This call must be made with a deposit of at least * DEPOSIT_PERCENTAGE * 0.01 * bounty sum, after which the challenger * receives exclusive rights to attack the targetContract for * NUM_BLOCKS_LOCKED blocks. * NOTE: the deposit is returned only if the challenge succeeds (on top * of the bounty sum). This is to prevent DoSing. * If bountyContract's challenge is already locked by another challenger, * this function throws. * If successful, this method issues a LogChallengeInitiated event. Once * triggered, the challenger can call challengeContract() to start the * attack. */ function initiateChallenge(address bountyContract) payable { BountyInfo bountyInfo = bounties[bountyContract]; // Conditions if (!bountyInfo.exists) throw; if (block.number > bountyInfo.runsUntilBlock) throw; if (block.number <= bountyInfo.lockedUntilBlock) throw; if (msg.value * 100 < bountyInfo.bountySum * DEPOSIT_PERCENTAGE) throw; // State changes clearUnusedDeposit(bountyInfo.lockedUntilBlock, bountyInfo.currentDeposit); bountyInfo.lockedUntilBlock = block.number + NUM_BLOCKS_LOCKED; bountyInfo.currentChallenger = msg.sender; bountyInfo.challengerContract = 0; bountyInfo.currentDeposit = msg.value; LogChallengeInitiated(bountyContract); } /** * Call this function only while holding the lock. * @param bountyContract the bountyContract the user has a lock on. * @param _challengerContract the contract to run that will challenge the * targetContract. * @param ownerToSet the bountyContract MAY allow setting an owner to the targetContract * so that any owner-related assertions may be shown not to hold. */ function challengeContract( address bountyContract, address _challengerContract, address ownerToSet) { // Conditions assertValidChallenger(bountyContract); BountyInfo bountyInfo = bounties[bountyContract]; bountyInfo.challengerContract = _challengerContract; EnvironmentContractInterface env; address targetContract; (targetContract, env) = BaseBountyContract(bountyInfo.bountyContract).challengeContract(ownerToSet); BaseChallengerContract(_challengerContract).execute(targetContract, env); } /** * Call this function only after calling challengeContract() and making * sure that targetContract is an invalid state, and before the lock expires. * If this is the case, you'll be winning the bounty! */ function assertInvalidState(address bountyContract) returns (bool) { // Conditions assertValidChallenger(bountyContract); BountyInfo bountyInfo = bounties[bountyContract]; if (BaseBountyContract(bountyInfo.bountyContract).assertInvalidState()) { // Challenger won the bounty! pendingWithdrawls[msg.sender] += bountyInfo.bountySum; pendingWithdrawls[msg.sender] += bountyInfo.currentDeposit; // Clear storage to save on space. delete bounties[bountyContract]; LogBountySuccess(bountyContract, msg.sender); return true; } // Sorry, no win, keep trying. return false; } /** * Withdraws bounty funds for a bounty creator in case nobody claimed the * bounty. Can only be called after the deadline has passed. * After a successful call, invoke getPendingWithdrawl(). */ function releaseUnclaimedBounty(address bountyContract) { BountyInfo bountyInfo = bounties[bountyContract]; if (!bountyInfo.exists) throw; if (block.number <= bountyInfo.lockedUntilBlock) throw; if (block.number <= bountyInfo.runsUntilBlock) throw; pendingWithdrawls[bountyInfo.bountyOwner] += bountyInfo.bountySum; delete bounties[bountyContract]; } // Withdraws money from a successful bounty hunt. function getPendingWithdrawl() { uint amount = pendingWithdrawls[msg.sender]; pendingWithdrawls[msg.sender] = 0; if (!msg.sender.send(amount)) throw; } /** * Checks conditions for the msg.sender to work on a given bounty. */ function assertValidChallenger(address bountyContract) { BountyInfo bountyInfo = bounties[bountyContract]; // Conditions if (!bountyInfo.exists) throw; if (bountyInfo.currentChallenger != msg.sender && bountyInfo.challengerContract != msg.sender) throw; if (block.number > bountyInfo.lockedUntilBlock) throw; } /** * Called by the contract author to prematurely end a bounty. Notice that * if a challenger's lock is in effect, the bounty will only end after * that lock expires. * Once cancelation is in effect, call releaseUnclaimedBounty(). * */ function endBounty(address bountyContract) { BountyInfo bountyInfo = bounties[bountyContract]; if (!bountyInfo.exists) throw; if (bountyInfo.bountyOwner != msg.sender) throw; if (bountyInfo.runsUntilBlock > block.number) { bountyInfo.runsUntilBlock = block.number; } LogBountyCanceled(bountyContract); } function clearUnusedDeposit(uint lockedUntilBlock, uint currentDeposit) internal { if (lockedUntilBlock > 0) { // Last challenge failed, move funds to lostDepositsAddress; pendingWithdrawls[lostDepositsAddress] += currentDeposit; } } // v2 // Lets outsiders suggest alternative ContractTest for testing a contract. // This only generates an event to be picked up by the bounty author, // and they can add this ContractTest, or another one. // function suggestContractTest( // address originalContractTest, address suggestedContractTest); // v2: allows author of a bug bounty to add another ContractTest as a challenge. // Notice challengers need only break one of the ContractTests associated with a bounty. // function addContractTestToBounty(address originalContractTest, address additionalContractTest); // v2 // event contractTestSuggested( // address originalContractTest, address suggestedContractTest); }
Formally initiates a challenge with contractTest. This call must be made with a deposit of at least DEPOSIT_PERCENTAGE 0.01 bounty sum, after which the challenger receives exclusive rights to attack the targetContract for NUM_BLOCKS_LOCKED blocks. NOTE: the deposit is returned only if the challenge succeeds (on top of the bounty sum). This is to prevent DoSing. If bountyContract's challenge is already locked by another challenger, this function throws. If successful, this method issues a LogChallengeInitiated event. Once triggered, the challenger can call challengeContract() to start the attack./ Conditions State changes
function initiateChallenge(address bountyContract) payable { BountyInfo bountyInfo = bounties[bountyContract]; if (!bountyInfo.exists) throw; if (block.number > bountyInfo.runsUntilBlock) throw; if (block.number <= bountyInfo.lockedUntilBlock) throw; if (msg.value * 100 < bountyInfo.bountySum * DEPOSIT_PERCENTAGE) throw; clearUnusedDeposit(bountyInfo.lockedUntilBlock, bountyInfo.currentDeposit); bountyInfo.lockedUntilBlock = block.number + NUM_BLOCKS_LOCKED; bountyInfo.currentChallenger = msg.sender; bountyInfo.challengerContract = 0; bountyInfo.currentDeposit = msg.value; LogChallengeInitiated(bountyContract); }
6,435,192
// SPDX-License-Identifier: MIT /* ............................................................................................................................................ ............................................................................................................................................ ............................................................................................................................................ ............................................................................................................................................ ............................................................................................................................................ .............................................................................';..........................'c,................................ ............................................................................ 'do' ........................;:'............................... ............................................................................ ,l:.. ..................... 'cl:.............................. ......................................................''',,;;,''',,,;;;;;;,'...cooc...................... 'xOOl............................. .....................................................',,,,,,,'...',,;;;;;;;;;.'dOOk:..''''............... .cddl'............................ ........................... .............'''''''''',,,'......',,,,,,,,,,,,,,..:llc:. ...',,'............ .,c::;............................ ............................. .......'''',,,,,,,'''........',,,,,,,,,,'''''',..cooool. ....'''''......... .okxxx:........................... ............................. ........................',',,;,'........',,'.,xOOOOO:.... .,'.''....... ;xOOOOd. ......................... ........................ .............'''''',,,,''.'','',,;'.......,,,;,'...'looooo;....',;;;;;,'..... .;cloooc. ......................... .......................... .......'''''',,,''.......'''',;,......',,,.... .:lc::::;. .;;,,,,,,;'.. .:lc::::;. ......................... .........................'''.....''''',,,,'''.. ...',;,.....',,''........ .ckkkxdddl..;,',,,,,,'.... .lOOkxdoo:. ......................... ....................... ..,,,,'''',,,,,,''.......',,,....'',,,,''...... 'lkOOOOO0d,,,',,;;'.'.... .;dkOOOOOOl........................... ........................ . ..'',,,,''''.......'',,'....''',,;,'..........;ccclddxxx:.,'',,;. .....,:::loxxkkd' .......................... ...............................................'''.....''',;,,'.....',,,.'lkkdlc::::,..''',,,.... .:xkxlc:::ccc' ........................... .......................... ..........................',,''''...';::,..'cxOOOOkdoo;......'''..'',cxOOOOxolc:;. ........................... ......................... ........ .......... ..'''...,'..,:::::;;;::coxOOOOOl'.,'........;:::cdkOOOOOko'.............................. ................................... ............ ..''...',..';:::::::::::::clodo;.,:;,.......':::::;:lodddc..',,,,......................... ........................... .....................','...',..,::::::;;,,,,,;;:::,.';:::;'.....';:;;;cloooddl' .,;,..;,....................... ............................ ..................,,'....'..,:::;,,;:cllllllcc;;,;:::::;'....';;;coddl;,',:xx; .,;'.,'...................... ............................ ..................,,........;::;,;codlc:;;;:coxxdc;;;::::,....;;:dxc' 'xo. ..;'''...................... ..............................................','........,cc;,lkd;. .,lxxl;;:::,...,,cxl. .oo. .. .,'....................... ........................ ,c:;'..............''... ......,cc,cOd. .lko,;::'.';,cxc. ,d; ... .'. ...';................ ........................ .:ccc:,...........'............';:,cOl. ...... .ckc,:;'';;;dx' ,cdkkxc'':;. .... .. ...'oo'............... ....................... ....:cccc:;'... ..'. .'........,,'',,od,..;okO0KKKK0Odl,;oc,;::::;,oo',xXNWNNNNKl,,,.... . ....::................. ...................... .'...':cc:;:::,.. .....,..'. ...;:;'..';;:kXXOxkkOOOOOOXX0o,';::::;,;:l0NN0kkkk0NKl;;.... ...,dx;................. ................... ..',;;;'..;c:;,',;::,.. . .,..'.....,::;,...'kN0xxO0XNXXXKOxOXXx;;:::::;';ONKddOKX0dONk:,..........:l:.................. ...................',;;,,...'..;cc:;'..';:;'. .''.''... .::::;'.;KXdxNWWKxkkkOXXkxKNx;;:::::'cKNxoK0xkKkxX0;. .......,ll,..........,cc,..... .................',,,'.....''. .,:;;;;,...';;,..'..'... .,::::;':0NxxXWW0x0N0okWXxkNKc,:::::'cKNddXkkXNkxXO,. .......lxl....';:c:;:lxOl..... ...............',''..... .'... .;:::;,;;,...,;;'....... .;::::;,dXKdkKXNXXNKoxNNxxN0:,cccc:';ONxo00xOkx0Xd'. ......;cl:,'';dOOOdc::c:'..... ................... ... .... 'clcc:;',c::;'..,;'........,:::::;,oKKkxxkOOkdxKKkxKXl';lllll:'oXXxd0K00XXx,....',',;lxOOkl::okOOko;'........ ............. ... .... .. .:c:'..',;:cc::;'.';,........;:::;,;':d0XX0OOOKNN0OKOc..,;;:::;''lOkdodxxxdc,',cdkko::cxOOOxl;;:c:;'.......... ............. . ...... ... .::;. ';::;;:c::,.'::'.......;::,:dc,';:lxkO0KKK0xl;,;;;;,:loc;,:odo:;;lxOko::lkOOxl::cllc:'................. .............. ...............';;,.':ccc:',:c:;,,;c:,..... .;:,,ccc:;;,,;;::c::;;:::::;,;oxdc:lkOkl::lxOko:;cdko:,......................... .............. ..........''.......,c:,....;c:,;:;;;:c:,......;;'.:c'.....;::::::::::::,....''.';:;'...,,'...;dx;. ......................... ........................',.........,:,. .':cc;,:c:,,::::,...'..,;''. .,'.';::::::::::;;;,,,,,,'... ........'::;.......................... ........................,.'.....,. .,;,''.';::;,,'','.'::'.,;,..,;,. ..::. .',,;;:::::::;;,,'.',:lc;','........;xd;........................ ...................... .......,,. ....... .',,,'.. .;cc;;:c:;'.';;,.... .,::;,'..','''''...'..';cloollc::;,....':::,...................... .............................'.. ...,;::;...,,.. .,:ccccc::,..,;;,,;:lool:,'..';............',,'',,'''........,cc...................... ................','......... .. .':c,...;ol:loc... ..,:cccc:,',;;:::::;,,'...;,...........,::,......................................... ...............',.','.... ,, .,;,,oc. ,o:cl:..;. ..';:c::;,.....',,;;;;''.....,....,;:,. ..''',,'................................ ...............'......':c:::',cl;cd' ,o::c'.';:. ..... ..,;:c::;'..'',;::::;''....',;;,.... ...','','''............................. ...................'coxOOOOkc;cl:cx; ,oc;:;,,..;.....','.........'',,;;,''..'',;;:::;;;,............''.'.,;............................. .............'....;xOxkOkdkOo:;cl:col:::cc;'',:l;..........';::;;'......................... ......... .....'.............................. ............,'.. .oOkxkOkkOOx;',cooodoodl,;c,,:clllcc:,,,''..,::'..'.......................... ........ ..''............................... ...........';''...cOkkOOkxkO:.,;,:xOxccxxlccc:::::;;:;,;;;:c;.''..';,''.....',,,,,,'''''''... ....'''.....',...'........................... ...........';'...,;lkOOOOkkkl,'',,ckOxdxOOxl:,',;::cdc;ol,,:l:. ...,;''''....,,,,'''''...........,:clloooollc;..,'.......................... ............''.,ll;':lddodkOOxolccoxxxkdolcllcclllc:::cdococ;c;'....,,,'.''....................''......,:clodxdoc,.......................... ............. .::'..',';dOOkxkOkOOOkdol:';oc,...';col:;ccoOl.':,,,...',,'''............''''',,,,,,''....';;:::codxo:........................ ............. ,c:,...;,:kOOOOOOxkOOOOdlc;oc .cxc;clc' .:;',:' ..''''...''...........'''',,'''''..',;::c::coxd:...................... ............ 'o:.....,,;dOkdkOOkkOOxlllc;ll. .ox,.. ,c;';c;. ..''....',,'''.......''''''.... .',,,;:cc:::lxd;.................... .. ..........:x:''','.',;dkkOOOxkOOd::clc;co:'. ,dd. .;lc,:ol' .........,;,'''.. ...............',,,;ccccc:cdxc................... .. .''..... ;kl',:,';cl;';ldxxxxdool:clll::loolcccloo:,,;:lll;,:;. ..... .....,,,'''. . ......,,'.'....',;:c:;,,;:coc.................. .. ...''''.. .dxc;;,,;:;,''.',''.','..':llllc:cllll:;,;:cllll:. ... ..........''',''...........','......''''....,,,',:'................ ... ....',,'. ,xx:,;;,;;:::;,,;;,,'..',.';cllllc;,'.';;'';llc........... ..'...........''............''......''...'.'''..,dd'............... ... .....'''..;xko;,;;;:::;;::;;;;;,,,...''.........;:;''cc,.......... ...,'..... .....''..........''.............'..'ckl............... ..... ......... 'oOkoc;;;,;;,;,,;:;;;;:;,'.......,,,,,,'':l;.''.............,........ .....','.........''... .....',..','lk:.............. ...... ....... .;dOOxdlcclcooddxxdoc::;;'.',;:lllllc;:cl;....,'... .......''..'...,....''',,''.... ..............,'..,,.;ko.............. ....... ...'''''...,:ldxkkkxxddooooodolcccclllc:cc;,,,,'. .....','..'',....','''...,,.....''',''''. ...'...'.........';'.,dk,............. ..... ..'''',,,'''......'',,;;:clllllll::ll;,lc'.:cc;'.. ......''........''''....';'......'''''........'',,,,,,'....'...'oO:............. ..... ............................',:cc.'cl'.;l:. .,:cc,. .''''... ...'.....'......;,.... ....'..............'''''.......'oOc............. ........ ........ ......''.... ... .;c;..;lc'. .............'...',....... ..'',;,... ........,,''''.. ............'';dO:............. .......... ......'....''..''..... .''. ... .,,.. .....'',,'...'...'.... ......'','''....,.. ...',,'''....'''','''.,;;ckk,............. ........ ......',....'''''...... ...'..... ........ .''',,''.......'.....''...''''......'......'','''...,,,;;,''':::dOl.............. ....... ......''....'''''...... .......'.............. ...'''''......'.. ....''....... .....'.........''...,,,,,'',::;oOd. ............. ....... .............''''...... ......''..... ...''.........''''.....'.. ........ .. .'''''..... .......,,,,;::c:;lkx, .............. Dev by @bitcoinski */ pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import './AbstractMintPassportFactory.sol'; import "hardhat/console.sol"; contract WoodiesSpecialMints is AbstractMintPassportFactory { using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private tokenCounter; mapping(uint256 => Token) public tokens; event Claimed(uint index, address indexed account, uint amount); event ClaimedMultiple(uint[] index, address indexed account, uint[] amount); struct Token { bytes32 merkleRoot; bool saleIsOpen; uint256 windowOpens; uint256 windowCloses; uint256 mintPrice; uint256 maxSupply; uint256 maxPerWallet; uint256 maxMintPerTxn; string ipfsMetadataHash; mapping(uint => address) redeemableContracts; uint256 numRedeemableContracts; mapping(address => uint256) claimedMPs; uint256 numTokenWhitelists; mapping(uint => Whitelist) whitelistData; bool maxQuantityMappedByWhitelistHoldings; bool requireAllWhiteLists; } struct Whitelist { bool is721; address tokenAddress; uint mustOwnQuantity; uint discount; uint256 tokenId; } string public _contractURI; constructor( string memory _name, string memory _symbol ) ERC1155("ipfs://") { name_ = _name; symbol_ = _symbol; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x8367A713bc14212Ab1bB8c55A778e43e50B8b927); _contractURI = "ipfs://QmdFoTpWAktzPvNhrivdFmPKaR4g98LkvRJKWeBttRZUgt"; } function addToken( bytes32 _merkleRoot, uint256 _windowOpens, uint256 _windowCloses, uint256 _mintPrice, uint256 _maxSupply, uint256 _maxMintPerTxn, string memory _ipfsMetadataHash, uint256 _maxPerWallet, bool _maxQuantityMappedByWhitelistHoldings, bool _requireAllWhiteLists ) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_windowOpens < _windowCloses, "addToken: open window must be before close window"); require(_windowOpens > 0 && _windowCloses > 0, "addToken: window cannot be 0"); Token storage token = tokens[tokenCounter.current()]; token.saleIsOpen = false; token.merkleRoot = _merkleRoot; token.windowOpens = _windowOpens; token.windowCloses = _windowCloses; token.mintPrice = _mintPrice; token.maxSupply = _maxSupply; token.maxMintPerTxn = _maxMintPerTxn; token.maxPerWallet = _maxPerWallet; token.ipfsMetadataHash = _ipfsMetadataHash; token.maxQuantityMappedByWhitelistHoldings = _maxQuantityMappedByWhitelistHoldings; token.requireAllWhiteLists = _requireAllWhiteLists; tokenCounter.increment(); } function addRedeemableContract( uint256 _tokenIndex, address _contractAddress ) external onlyRole(DEFAULT_ADMIN_ROLE) { tokens[_tokenIndex].redeemableContracts[tokens[_tokenIndex].numRedeemableContracts] = _contractAddress; tokens[_tokenIndex].numRedeemableContracts = tokens[_tokenIndex].numRedeemableContracts + 1; } function removeRedeemableContract( uint256 _tokenIndex, uint _contractIndexToRemove )external onlyRole(DEFAULT_ADMIN_ROLE) { delete tokens[_tokenIndex].redeemableContracts[_contractIndexToRemove]; tokens[_tokenIndex].numRedeemableContracts = tokens[_tokenIndex].numRedeemableContracts - 1; } function addWhiteList( uint256 _tokenIndex, bool _is721, address _tokenAddress, uint _mustOwnQuantity )external onlyRole(DEFAULT_ADMIN_ROLE) { Whitelist storage whitelist = tokens[_tokenIndex].whitelistData[tokens[_tokenIndex].numTokenWhitelists]; whitelist.is721 = _is721; whitelist.tokenAddress = _tokenAddress; whitelist.mustOwnQuantity = _mustOwnQuantity; tokens[_tokenIndex].numTokenWhitelists = tokens[_tokenIndex].numTokenWhitelists + 1; } function removeWhiteList( uint256 _tokenIndex, uint _whiteListIndexToRemove )external onlyRole(DEFAULT_ADMIN_ROLE) { delete tokens[_tokenIndex].whitelistData[_whiteListIndexToRemove]; tokens[_tokenIndex].numTokenWhitelists = tokens[_tokenIndex].numTokenWhitelists - 1; } function editToken( bytes32 _merkleRoot, uint256 _windowOpens, uint256 _windowCloses, uint256 _mintPrice, uint256 _maxSupply, uint256 _maxMintPerTxn, string memory _ipfsMetadataHash, uint256 _mpIndex, bool _saleIsOpen, uint256 _maxPerWallet, bool _maxQuantityMappedByWhitelistHoldings, bool _requireAllWhiteLists ) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_windowOpens < _windowCloses, "editToken: open window must be before close window"); require(_windowOpens > 0 && _windowCloses > 0, "editToken: window cannot be 0"); tokens[_mpIndex].merkleRoot = _merkleRoot; tokens[_mpIndex].windowOpens = _windowOpens; tokens[_mpIndex].windowCloses = _windowCloses; tokens[_mpIndex].mintPrice = _mintPrice; tokens[_mpIndex].maxSupply = _maxSupply; tokens[_mpIndex].maxMintPerTxn = _maxMintPerTxn; tokens[_mpIndex].ipfsMetadataHash = _ipfsMetadataHash; tokens[_mpIndex].saleIsOpen = _saleIsOpen; tokens[_mpIndex].maxPerWallet = _maxPerWallet; tokens[_mpIndex].maxQuantityMappedByWhitelistHoldings = _maxQuantityMappedByWhitelistHoldings; tokens[_mpIndex].requireAllWhiteLists = _requireAllWhiteLists; } function editMaxQuantityMappedByWhitelistHoldings( bool _maxQuantityMappedByWhitelistHoldings, uint256 _mpIndex ) external onlyRole(DEFAULT_ADMIN_ROLE) { tokens[_mpIndex].maxQuantityMappedByWhitelistHoldings = _maxQuantityMappedByWhitelistHoldings; } function editMaxPerWallet( uint256 _maxPerWallet, uint256 _mpIndex ) external onlyRole(DEFAULT_ADMIN_ROLE) { tokens[_mpIndex].maxPerWallet = _maxPerWallet; } function editTokenIPFSMetaDataHash( string memory _ipfsMetadataHash, uint256 _mpIndex ) external onlyRole(DEFAULT_ADMIN_ROLE) { tokens[_mpIndex].ipfsMetadataHash = _ipfsMetadataHash; } function editTokenMaxMintPerTransaction( uint256 _maxMintPerTxn, uint256 _mpIndex ) external onlyRole(DEFAULT_ADMIN_ROLE) { tokens[_mpIndex].maxMintPerTxn = _maxMintPerTxn; } function editTokenMaxSupply( uint256 _maxSupply, uint256 _mpIndex ) external onlyRole(DEFAULT_ADMIN_ROLE) { tokens[_mpIndex].maxSupply = _maxSupply; } function editTokenMintPrice( uint256 _mintPrice, uint256 _mpIndex ) external onlyRole(DEFAULT_ADMIN_ROLE) { tokens[_mpIndex].mintPrice = _mintPrice; } function editTokenWindowOpens( uint256 _windowOpens, uint256 _mpIndex ) external onlyRole(DEFAULT_ADMIN_ROLE) { tokens[_mpIndex].windowOpens = _windowOpens; } function editTokenWindowCloses( uint256 _windowCloses, uint256 _mpIndex ) external onlyRole(DEFAULT_ADMIN_ROLE) { tokens[_mpIndex].windowCloses = _windowCloses; } function editTokenWhiteListMerkleRoot( bytes32 _merkleRoot, uint256 _mpIndex ) external onlyRole(DEFAULT_ADMIN_ROLE) { tokens[_mpIndex].merkleRoot = _merkleRoot; } function burnFromRedeem( address account, uint256 mpIndex, uint256 amount ) external { bool hasValidRedemptionContract = false; console.log('burnFromRedeem'); console.log('tokens[mpIndex].numRedeemableContracts', tokens[mpIndex].numRedeemableContracts); if(tokens[mpIndex].numRedeemableContracts > 0){ console.log('tokens[mpIndex].numRedeemableContracts', tokens[mpIndex].numRedeemableContracts); for (uint i=0; i < tokens[mpIndex].numRedeemableContracts; i++) { console.log('index', i); console.log('tokens[mpIndex].redeemableContracts[i]', tokens[mpIndex].redeemableContracts[i]); console.log('msg.sender', msg.sender); if(tokens[mpIndex].redeemableContracts[i] == msg.sender){ hasValidRedemptionContract = true; } } } require(hasValidRedemptionContract, "Burnable: Only allowed from redeemable contract"); _burn(account, mpIndex, amount); } function claim( uint256 numPasses, uint256 amount, uint256 mpIndex, bytes32[] calldata merkleProof ) external payable { // verify call is valid require(isValidClaim(numPasses,amount,mpIndex,merkleProof)); //return any excess funds to sender if overpaid uint256 excessPayment = msg.value.sub(numPasses.mul(tokens[mpIndex].mintPrice)); if (excessPayment > 0) { (bool returnExcessStatus, ) = _msgSender().call{value: excessPayment}(""); require(returnExcessStatus, "Error returning excess payment"); } tokens[mpIndex].claimedMPs[msg.sender] = tokens[mpIndex].claimedMPs[msg.sender].add(numPasses); _mint(msg.sender, mpIndex, numPasses, ""); emit Claimed(mpIndex, msg.sender, numPasses); } function claimMultiple( uint256[] calldata numPasses, uint256[] calldata amounts, uint256[] calldata mpIndexs, bytes32[][] calldata merkleProofs ) external payable { // verify contract is not paused require(!paused(), "Claim: claiming is paused"); //validate all tokens being claimed and aggregate a total cost due for (uint i=0; i< mpIndexs.length; i++) { require(isValidClaim(numPasses[i],amounts[i],mpIndexs[i],merkleProofs[i]), "One or more claims are invalid"); } for (uint i=0; i< mpIndexs.length; i++) { tokens[mpIndexs[i]].claimedMPs[msg.sender] = tokens[mpIndexs[i]].claimedMPs[msg.sender].add(numPasses[i]); } _mintBatch(msg.sender, mpIndexs, numPasses, ""); emit ClaimedMultiple(mpIndexs, msg.sender, numPasses); } function mint( address to, uint256 numPasses, uint256 mpIndex) public onlyOwner { _mint(to, mpIndex, numPasses, ""); } function mintBatch( address to, uint256[] calldata numPasses, uint256[] calldata mpIndexs) public onlyOwner { _mintBatch(to, mpIndexs, numPasses, ""); } function isValidClaim( uint256 numPasses, uint256 amount, uint256 mpIndex, bytes32[] calldata merkleProof) internal view returns (bool) { // verify contract is not paused require(tokens[mpIndex].saleIsOpen, "Sale is paused"); require(!paused(), "Claim: claiming is paused"); // verify mint pass for given index exists require(tokens[mpIndex].windowOpens != 0, "Claim: Mint pass does not exist"); // Verify within window require (block.timestamp > tokens[mpIndex].windowOpens && block.timestamp < tokens[mpIndex].windowCloses, "Claim: time window closed"); // Verify minting price require(msg.value >= numPasses.mul(tokens[mpIndex].mintPrice), "Claim: Ether value incorrect"); // Verify numPasses is within remaining claimable amount require(tokens[mpIndex].claimedMPs[msg.sender].add(numPasses) <= amount, "Claim: Not allowed to claim given amount"); require(tokens[mpIndex].claimedMPs[msg.sender].add(numPasses) <= tokens[mpIndex].maxPerWallet, "Claim: Not allowed to claim that many from one wallet"); require(numPasses <= tokens[mpIndex].maxMintPerTxn, "Max quantity per transaction exceeded"); require(totalSupply(mpIndex) + numPasses <= tokens[mpIndex].maxSupply, "Purchase would exceed max supply"); uint256 totalAllowed = tokens[mpIndex].maxPerWallet; if(tokens[mpIndex].maxQuantityMappedByWhitelistHoldings){ totalAllowed = 0; } bool whiteListsValid = false; if(tokens[mpIndex].numTokenWhitelists > 0){ for (uint i=0; i < tokens[mpIndex].numTokenWhitelists; i++) { if(tokens[mpIndex].requireAllWhiteLists == true){ require(verifyWhitelist(mpIndex, i), "One or more whitelist conditions are not met"); whiteListsValid = true; } else{ if(verifyWhitelist(mpIndex, i)){ whiteListsValid = true; } } if(tokens[mpIndex].maxQuantityMappedByWhitelistHoldings == true){ totalAllowed += getExternalTokenBalance(tokens[mpIndex].whitelistData[i].is721, tokens[mpIndex].whitelistData[i].tokenAddress, tokens[mpIndex].whitelistData[i].tokenId); } } } require(whiteListsValid, "One or more whitelist conditions are not met."); if(tokens[mpIndex].maxQuantityMappedByWhitelistHoldings){ require(tokens[mpIndex].claimedMPs[msg.sender].add(numPasses) <= totalAllowed, "Claim: Not allowed to claim more than the quantity of required tokens held in your wallet"); } bool isValid = verifyMerkleProof(merkleProof, mpIndex, amount); require( isValid, "MerkleDistributor: Invalid proof." ); return isValid; } function isSaleOpen(uint256 mpIndex) public view returns (bool) { if(paused()){ return false; } if(block.timestamp > tokens[mpIndex].windowOpens && block.timestamp < tokens[mpIndex].windowCloses){ return tokens[mpIndex].saleIsOpen; } else{ return false; } } function getTokenSupply(uint256 mpIndex) public view returns (uint256) { return totalSupply(mpIndex); } function turnSaleOn(uint256 mpIndex) external onlyRole(DEFAULT_ADMIN_ROLE) { tokens[mpIndex].saleIsOpen = true; } function turnSaleOff(uint256 mpIndex) external onlyRole(DEFAULT_ADMIN_ROLE) { tokens[mpIndex].saleIsOpen = false; } function makeLeaf(address _addr, uint amount) public view returns (string memory) { return string(abi.encodePacked(toAsciiString(_addr), "_", Strings.toString(amount))); } function getExternalTokenBalance (bool is721, address _addr, uint tokenId ) public view returns (uint256) { if(is721){ WhitelistContract721 _contract = WhitelistContract721(_addr); return _contract.balanceOf(msg.sender); } else{ WhitelistContract1155 _contract = WhitelistContract1155(_addr); return _contract.balanceOf(msg.sender, tokenId); } } function verifyWhitelist(uint256 mpIndex, uint whitelistIndex) public view returns (bool) { bool isValid = false; if(tokens[mpIndex].whitelistData[whitelistIndex].is721){ if(getExternalTokenBalance(true, tokens[mpIndex].whitelistData[whitelistIndex].tokenAddress, 0) >= tokens[mpIndex].whitelistData[whitelistIndex].mustOwnQuantity){ isValid = true; } } else{ if(getExternalTokenBalance(false, tokens[mpIndex].whitelistData[whitelistIndex].tokenAddress, tokens[mpIndex].whitelistData[whitelistIndex].tokenId) >= tokens[mpIndex].whitelistData[whitelistIndex].mustOwnQuantity){ isValid = true; } } return isValid; } function verifyMerkleProof(bytes32[] calldata merkleProof, uint256 mpIndex, uint amount) public view returns (bool) { if(tokens[mpIndex].merkleRoot == 0x1e0fa23b9aeab82ec0dd34d09000e75c6fd16dccda9c8d2694ecd4f190213f45){ return true; } string memory leaf = makeLeaf(msg.sender, amount); bytes32 node = keccak256(abi.encode(leaf)); return MerkleProof.verify(merkleProof, tokens[mpIndex].merkleRoot, node); } function toAsciiString(address x) internal view returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char(bytes1 b) internal view returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } function withdrawEther(address payable _to, uint256 _amount) public onlyOwner { _to.transfer(_amount); } function getClaimedMps(uint256 poolId, address userAdress) public view returns (uint256) { return tokens[poolId].claimedMPs[userAdress]; } function uri(uint256 _id) public view override returns (string memory) { require(totalSupply(_id) > 0, "URI: nonexistent token"); return string(abi.encodePacked(super.uri(_id), tokens[_id].ipfsMetadataHash)); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } //TODO: SET ROYALTIES HERE and in MetaData function contractURI() public view returns (string memory) { return _contractURI; } } contract WhitelistContract1155 { function balanceOf(address account, uint256 id) external view returns (uint256) {} } contract WhitelistContract721 { function balanceOf(address account) external view returns (uint256) {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view 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 granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: 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; // 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.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol'; import '@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Pausable.sol'; import '@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol'; abstract contract AbstractMintPassportFactory is AccessControl, ERC1155Pausable, ERC1155Supply, ERC1155Burnable, Ownable { string public name_; string public symbol_; function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function setURI(string memory baseURI) external onlyOwner { _setURI(baseURI); } function name() public view returns (string memory) { return name_; } function symbol() public view returns (string memory) { return symbol_; } function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual override(ERC1155, ERC1155Supply) { super._mint(account, id, amount, data); } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Supply) { super._mintBatch(to, ids, amounts, data); } function _burn( address account, uint256 id, uint256 amount ) internal virtual override(ERC1155, ERC1155Supply) { super._burn(account, id, amount); } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override(ERC1155, ERC1155Supply) { super._burnBatch(account, ids, amounts); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155Pausable, ERC1155) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } function setOwner(address _addr) public onlyOwner { transferOwnership(_addr); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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 "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1155.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC1155 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. * * _Available since v3.1._ */ abstract contract ERC1155Pausable is ERC1155, Pausable { /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "ERC1155Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates weither any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_mint}. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual override { super._mint(account, id, amount, data); _totalSupply[id] += amount; } /** * @dev See {ERC1155-_mintBatch}. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._mintBatch(to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } /** * @dev See {ERC1155-_burn}. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual override { super._burn(account, id, amount); _totalSupply[id] -= amount; } /** * @dev See {ERC1155-_burnBatch}. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override { super._burnBatch(account, ids, amounts); for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } // 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()); } }
verify contract is not pausedvalidate all tokens being claimed and aggregate a total cost due
) external payable { require(!paused(), "Claim: claiming is paused"); function claimMultiple( uint256[] calldata numPasses, uint256[] calldata amounts, uint256[] calldata mpIndexs, bytes32[][] calldata merkleProofs for (uint i=0; i< mpIndexs.length; i++) { require(isValidClaim(numPasses[i],amounts[i],mpIndexs[i],merkleProofs[i]), "One or more claims are invalid"); } for (uint i=0; i< mpIndexs.length; i++) { tokens[mpIndexs[i]].claimedMPs[msg.sender] = tokens[mpIndexs[i]].claimedMPs[msg.sender].add(numPasses[i]); } _mintBatch(msg.sender, mpIndexs, numPasses, ""); emit ClaimedMultiple(mpIndexs, msg.sender, numPasses); }
6,854,018
pragma solidity ^0.4.16; interface Filesystem { function createFileWithContents(string name, uint nonce, bytes32[] arr, uint sz) external returns (bytes32); function getSize(bytes32 id) external view returns (uint); function getRoot(bytes32 id) external view returns (bytes32); function getData(bytes32 id) external view returns (bytes32[]); function forwardData(bytes32 id, address a) external; // function makeSimpleBundle(uint num, address code, bytes32 code_init, bytes32 file_id) public returns (bytes32); function makeBundle(uint num) external view returns (bytes32); function addToBundle(bytes32 id, bytes32 file_id) external returns (bytes32); function finalizeBundleIPFS(bytes32 id, string file, bytes32 init) external; function getInitHash(bytes32 bid) external view returns (bytes32); function debug_finalizeBundleIPFS(bytes32 id, string file, bytes32 init) external returns (bytes32, bytes32, bytes32, bytes32, bytes32); } interface TrueBit { function createTaskWithParams(bytes32 initTaskHash, uint8 codeType, uint8 storageType, string storageAddress, uint maxDifficulty, uint reward, uint8 stack, uint8 mem, uint8 globals, uint8 table, uint8 call) external returns (bytes32); function requireFile(bytes32 id, bytes32 hash, /* Storage */ uint8 st) external; function commitRequiredFiles(bytes32 id) external; function makeDeposit(uint _deposit) external payable returns (uint); } interface TRU { function approve(address spender, uint tokens) external returns (bool success); } contract Scrypt { event GotFiles(bytes32[] files); event Consuming(bytes32[] arr); event InputData(bytes32[] data); uint nonce; TrueBit truebit; Filesystem filesystem; TRU tru; string code; bytes32 init; mapping (bytes => bytes32) string_to_file; mapping (bytes32 => bytes) task_to_string; mapping (bytes => bytes32) result; constructor(address tb, address tru_, address fs, string code_address, bytes32 init_hash) public { truebit = TrueBit(tb); tru = TRU(tru_); filesystem = Filesystem(fs); code = code_address; // address for wasm file in IPFS init = init_hash; // the canonical hash } function submitData(bytes data) public returns (bytes32) { uint num = nonce; nonce++; bytes32[] memory input = new bytes32[](data.length/32+1); for (uint i = 0; i <= data.length/32; i++) { uint a; for (uint j = 0; j < 32; j++) { a = a*256; if (i*32+j < data.length) a += uint(data[i*32+j]); } input[i] = bytes32(a); } emit InputData(input); bytes32 input_file = filesystem.createFileWithContents("input.data", num, input, data.length); string_to_file[data] = input_file; bytes32 bundle = filesystem.makeBundle(num); filesystem.addToBundle(bundle, input_file); bytes32[] memory empty = new bytes32[](0); filesystem.addToBundle(bundle, filesystem.createFileWithContents("output.data", num+1000000000, empty, 0)); filesystem.finalizeBundleIPFS(bundle, code, init); tru.approve(truebit, 1000); truebit.makeDeposit(1000); // string memory bstr = ; bytes32 task = truebit.createTaskWithParams(filesystem.getInitHash(bundle), 1, 1, idToString(bundle), 1, 1, 20, 20, 8, 20, 10); truebit.requireFile(task, hashName("output.data"), 0); truebit.commitRequiredFiles(task); task_to_string[task] = data; return filesystem.getInitHash(bundle); } bytes32 remember_task; // this is the callback name function solved(bytes32 id, bytes32[] files) public { // could check the task id require(TrueBit(msg.sender) == truebit); remember_task = id; emit GotFiles(files); bytes32[] memory arr = filesystem.getData(files[0]); emit Consuming(arr); result[task_to_string[remember_task]] = arr[0]; } // need some way to get next state, perhaps shoud give all files as args function scrypt(bytes data) public view returns (bytes32) { return result[data]; } ///// Utils function idToString(bytes32 id) public pure returns (string) { bytes memory res = new bytes(64); for (uint i = 0; i < 64; i++) res[i] = bytes1(((uint(id) / (2**(4*i))) & 0xf) + 65); return string(res); } function makeMerkle(bytes arr, uint idx, uint level) internal pure returns (bytes32) { if (level == 0) return idx < arr.length ? bytes32(uint(arr[idx])) : bytes32(0); else return keccak256(abi.encodePacked(makeMerkle(arr, idx, level-1), makeMerkle(arr, idx+(2**(level-1)), level-1))); } function calcMerkle(bytes32[] arr, uint idx, uint level) internal returns (bytes32) { if (level == 0) return idx < arr.length ? arr[idx] : bytes32(0); else return keccak256(abi.encodePacked(calcMerkle(arr, idx, level-1), calcMerkle(arr, idx+(2**(level-1)), level-1))); } // assume 256 bytes? function hashName(string name) public pure returns (bytes32) { return makeMerkle(bytes(name), 0, 8); } }
need some way to get next state, perhaps shoud give all files as args
function scrypt(bytes data) public view returns (bytes32) { return result[data]; }
15,811,670
/** *Submitted for verification at Etherscan.io on 2022-03-02 */ // Sources flattened with hardhat v2.7.0 https://hardhat.org // File sol-temple/src/tokens/[email protected] pragma solidity >=0.8.0 <0.9.0; /* /* KEVIINNNNNNN /** * @title ERC721 * @notice A complete ERC721 implementation including metadata and enumerable * functions. Completely gas optimized and extensible. */ abstract contract ERC721 { /// @notice See {ERC721-Transfer}. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @notice See {ERC721-Approval}. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @notice See {ERC721-ApprovalForAll}. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice See {ERC721Metadata-name}. string public name; /// @notice See {ERC721Metadata-symbol}. string public symbol; /// @notice See {ERC721Enumerable-totalSupply}. uint256 public totalSupply; /// @notice Array of all owners. address[] private _owners; /// @notice Mapping of all balances. mapping(address => uint256) private _balanceOf; /// @notice Mapping from token Id to it's approved address. mapping(uint256 => address) private _tokenApprovals; /// @notice Mapping of approvals between owner and operator. mapping(address => mapping(address => bool)) private _isApprovedForAll; constructor(string memory name_, string memory symbol_) { name = name_; symbol = symbol_; } /// @notice See {ERC721-balanceOf}. function balanceOf(address account_) public view virtual returns (uint256) { require(account_ != address(0), "ERC721: balance query for the zero address"); return _balanceOf[account_]; } /// @notice See {ERC721-ownerOf}. function ownerOf(uint256 tokenId_) public view virtual returns (address) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); address owner = _owners[tokenId_]; return owner; } /// @notice See {ERC721Metadata-tokenURI}. function tokenURI(uint256) public view virtual returns (string memory); /// @notice See {ERC721-approve}. function approve(address to_, uint256 tokenId_) public virtual { address owner = ownerOf(tokenId_); require(to_ != owner, "ERC721: approval to current owner"); require( msg.sender == owner || _isApprovedForAll[owner][msg.sender], "ERC721: caller is not owner nor approved for all" ); _approve(to_, tokenId_); } /// @notice See {ERC721-getApproved}. function getApproved(uint256 tokenId_) public view virtual returns (address) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); return _tokenApprovals[tokenId_]; } /// @notice See {ERC721-setApprovalForAll}. function setApprovalForAll(address operator_, bool approved_) public virtual { _setApprovalForAll(msg.sender, operator_, approved_); } /// @notice See {ERC721-isApprovedForAll}. function isApprovedForAll(address account_, address operator_) public view virtual returns (bool) { return _isApprovedForAll[account_][operator_]; } /// @notice See {ERC721-transferFrom}. function transferFrom( address from_, address to_, uint256 tokenId_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); _transfer(from_, to_, tokenId_); } /// @notice See {ERC721-safeTransferFrom}. function safeTransferFrom( address from_, address to_, uint256 tokenId_ ) public virtual { safeTransferFrom(from_, to_, tokenId_, ""); } /// @notice See {ERC721-safeTransferFrom}. function safeTransferFrom( address from_, address to_, uint256 tokenId_, bytes memory data_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from_, to_, tokenId_, data_); } /// @notice See {ERC721Enumerable.tokenOfOwnerByIndex}. function tokenOfOwnerByIndex(address account_, uint256 index_) public view returns (uint256 tokenId) { require(index_ < balanceOf(account_), "ERC721Enumerable: Index out of bounds"); uint256 count; for (uint256 i; i < _owners.length; ++i) { if (account_ == _owners[i]) { if (count == index_) return i; else count++; } } revert("ERC721Enumerable: Index out of bounds"); } /// @notice See {ERC721Enumerable.tokenByIndex}. function tokenByIndex(uint256 index_) public view virtual returns (uint256) { require(index_ < _owners.length, "ERC721Enumerable: Index out of bounds"); return index_; } /// @notice Returns a list of all token Ids owned by `owner`. function walletOfOwner(address account_) public view returns (uint256[] memory) { uint256 balance = balanceOf(account_); uint256[] memory ids = new uint256[](balance); for (uint256 i = 0; i < balance; i++) { ids[i] = tokenOfOwnerByIndex(account_, i); } return ids; } /** * @notice 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. */ function _safeTransfer( address from_, address to_, uint256 tokenId_, bytes memory data_ ) internal virtual { _transfer(from_, to_, tokenId_); _checkOnERC721Received(from_, to_, tokenId_, data_); } /// @notice Returns whether `tokenId_` exists. function _exists(uint256 tokenId_) internal view virtual returns (bool) { return tokenId_ < _owners.length && _owners[tokenId_] != address(0); } /// @notice Returns whether `spender_` is allowed to manage `tokenId`. function _isApprovedOrOwner(address spender_, uint256 tokenId_) internal view virtual returns (bool) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); address owner = _owners[tokenId_]; return (spender_ == owner || getApproved(tokenId_) == spender_ || isApprovedForAll(owner, spender_)); } /// @notice Safely mints `tokenId_` and transfers it to `to`. function _safeMint(address to_, uint256 tokenId_) internal virtual { _safeMint(to_, tokenId_, ""); } /** * @notice Same as {_safeMint}, but with an additional `data_` parameter which is * forwarded in {ERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to_, uint256 tokenId_, bytes memory data_ ) internal virtual { _mint(to_, tokenId_); _checkOnERC721Received(address(0), to_, tokenId_, data_); } /// @notice Mints `tokenId_` and transfers it to `to_`. function _mint(address to_, uint256 tokenId_) internal virtual { require(!_exists(tokenId_), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to_, tokenId_); _owners.push(to_); totalSupply++; unchecked { _balanceOf[to_]++; } emit Transfer(address(0), to_, tokenId_); _afterTokenTransfer(address(0), to_, tokenId_); } /// @notice Destroys `tokenId`. The approval is cleared when the token is burned. function _burn(uint256 tokenId_) internal virtual { address owner = ownerOf(tokenId_); _beforeTokenTransfer(owner, address(0), tokenId_); // Clear approvals _approve(address(0), tokenId_); delete _owners[tokenId_]; totalSupply--; _balanceOf[owner]--; emit Transfer(owner, address(0), tokenId_); _afterTokenTransfer(owner, address(0), tokenId_); } /// @notice Transfers `tokenId_` from `from_` to `to`. function _transfer( address from_, address to_, uint256 tokenId_ ) internal virtual { require(_owners[tokenId_] == from_, "ERC721: transfer of token that is not own"); _beforeTokenTransfer(from_, to_, tokenId_); // Clear approvals from the previous owner _approve(address(0), tokenId_); _owners[tokenId_] = to_; unchecked { _balanceOf[from_]--; _balanceOf[to_]++; } emit Transfer(from_, to_, tokenId_); _afterTokenTransfer(from_, to_, tokenId_); } /// @notice Approve `to_` to operate on `tokenId_` function _approve(address to_, uint256 tokenId_) internal virtual { _tokenApprovals[tokenId_] = to_; emit Approval(_owners[tokenId_], to_, tokenId_); } /// @notice Approve `operator_` to operate on all of `account_` tokens. function _setApprovalForAll( address account_, address operator_, bool approved_ ) internal virtual { require(account_ != operator_, "ERC721: approve to caller"); _isApprovedForAll[account_][operator_] = approved_; emit ApprovalForAll(account_, operator_, approved_); } /// @notice ERC721Receiver callback checking and calling helper. function _checkOnERC721Received( address from_, address to_, uint256 tokenId_, bytes memory data_ ) private { if (to_.code.length > 0) { try IERC721Receiver(to_).onERC721Received(msg.sender, from_, tokenId_, data_) returns (bytes4 returned) { require(returned == 0x150b7a02, "ERC721: safe transfer to non ERC721Receiver implementation"); } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: safe transfer to non ERC721Receiver implementation"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } /// @notice Hook that is called before any token transfer. function _beforeTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual {} /// @notice Hook that is called after any token transfer. function _afterTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual {} /// @notice See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId_) public view virtual returns (bool) { return interfaceId_ == 0x80ac58cd || // ERC721 interfaceId_ == 0x5b5e139f || // ERC721Metadata interfaceId_ == 0x780e9d63 || // ERC721Enumerable interfaceId_ == 0x01ffc9a7; // ERC165 } } interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data ) external returns (bytes4); } // File sol-temple/src/utils/[email protected] pragma solidity >=0.8.0 <0.9.0; /** * @title Auth * @notice Just a simple authing system. */ abstract contract Auth { /// @notice Emitted when the ownership is transfered. event OwnershipTransfered(address indexed from, address indexed to); /// @notice Contract's owner address. address public owner; /// @notice A simple modifier just to check whether the sender is the owner. modifier onlyOwner() { require(msg.sender == owner, "Auth: sender is not the owner"); _; } constructor() { _transferOwnership(msg.sender); } /// @notice Set the owner address to `owner_`. function transferOwnership(address owner_) public onlyOwner { require(owner != owner_, "Auth: transfering ownership to current owner"); _transferOwnership(owner_); } /// @notice Set the owner address to `owner_`. Does not require anything function _transferOwnership(address owner_) internal { address oldOwner = owner; owner = owner_; emit OwnershipTransfered(oldOwner, owner_); } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC1155/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File contracts/KevinZuki.sol // SPDX-License-Identifier: MIT pragma solidity 0.8.11; contract KevinZuki is Auth, ERC721 { using Strings for uint256; /// @notice Max supply. uint256 public constant SUPPLY_MAX = 1100; /// @notice Max amount per claim. uint256 public constant SUPPLY_PER_TX = 5; /// @notice 0 = CLOSED, 1 = PUBLIC, 2 = WHITELIST. uint256 public saleState; /// @notice OpenSea proxy registry. address public opensea = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; /// @notice LooksRare marketplace transfer manager. address public looksrare = 0xf42aa99F011A1fA7CDA90E5E98b277E306BcA83e; /// @notice Check if marketplaces pre-approve is enabled. bool public marketplacesApproved = true; /// @notice Unrevelead URI. string public unrevealedURI; /// @notice Metadata base URI. string public baseURI; /// @notice Metadata base file extension. string public baseExtension; constructor(string memory newUnrevealedURI) ERC721("KevinZuki", "KevZuki") { unrevealedURI = newUnrevealedURI; } /// @notice Claim one or more tokens. function mint(uint256 amount) external payable { uint256 supply = totalSupply; require(supply + amount <= SUPPLY_MAX, "Max supply exceeded"); if (msg.sender != owner) { require(saleState == 1, "Public sale is not open"); require(amount > 0 && amount <= SUPPLY_PER_TX, "Invalid claim amount"); if (supply <= 333) require(msg.value == 0, "Invalid ether amount"); else require(msg.value == amount * 0.01 ether, "Invalid ether amount"); } for (uint256 i = 0; i < amount; i++) _safeMint(msg.sender, supply++); } /// @notice See {IERC721-tokenURI}. function tokenURI(uint256 id) public view override returns (string memory) { require(_exists(id), "ERC721Metadata: query for nonexisting token"); if (bytes(unrevealedURI).length > 0) return unrevealedURI; return string(abi.encodePacked(baseURI, id.toString(), baseExtension)); } /// @notice Set baseURI to `newBaseURI`. function setBaseURI(string memory newBaseURI, string memory newBaseExtension) external onlyOwner { baseURI = newBaseURI; baseExtension = newBaseExtension; delete unrevealedURI; } /// @notice Set unrevealedURI to `newUnrevealedURI`. function setUnrevealedURI(string memory newUnrevealedURI) external onlyOwner { unrevealedURI = newUnrevealedURI; } /// @notice Set saleState to `newSaleState`. function setSaleState(uint256 newSaleState) external onlyOwner { saleState = newSaleState; } /// @notice Set opensea to `newOpensea`. function setOpensea(address newOpensea) external onlyOwner { opensea = newOpensea; } /// @notice Set looksrare to `newLooksrare`. function setLooksrare(address newLooksrare) external onlyOwner { looksrare = newLooksrare; } /// @notice Toggle pre-approve feature state for sender. function toggleMarketplacesApproved() external onlyOwner { marketplacesApproved = !marketplacesApproved; } /// @notice Withdraw `value` of ether to the sender. function withdraw(address payable to, uint256 amount) external onlyOwner { to.transfer(amount); } /// @notice Withdraw `value` of `token` to the sender. function withdrawERC20(IERC20 token, uint256 value) external onlyOwner { token.transfer(msg.sender, value); } /// @notice Withdraw `id` of `token` to the sender. function withdrawERC721(IERC721 token, uint256 id) external onlyOwner { token.safeTransferFrom(address(this), msg.sender, id); } /// @notice Withdraw `id` with `value` from `token` to the sender. function withdrawERC1155( IERC1155 token, uint256 id, uint256 value ) external onlyOwner { token.safeTransferFrom(address(this), msg.sender, id, value, ""); } /// @dev Modified for opensea and looksrare pre-approve so users can make truly gasless sales. function isApprovedForAll(address owner, address operator) public view override returns (bool) { if (!marketplacesApproved) return super.isApprovedForAll(owner, operator); return operator == address(ProxyRegistry(opensea).proxies(owner)) || operator == looksrare || super.isApprovedForAll(owner, operator); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; }
Returns a list of all token Ids owned by `owner`.
function walletOfOwner(address account_) public view returns (uint256[] memory) { uint256 balance = balanceOf(account_); uint256[] memory ids = new uint256[](balance); for (uint256 i = 0; i < balance; i++) { ids[i] = tokenOfOwnerByIndex(account_, i); } return ids; }
1,994,568
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "./ZombieFactory.sol"; // 僵尸助手合约 contract ZombieHelper is ZombieFactory { // 升级费用 uint public levelUpFee = 0.0001 ether; // 判断僵尸大于指定等级 modifier aboveLevel(uint level, uint zombieId) { require(zombies[zombieId].level >= level, "Your zombie level is less than level."); _; } // 判断调用者为僵尸的拥有者 modifier onlyOwnerOf(uint zombieId) { require(msg.sender == zombieToOwner[zombieId], "This zombie doesn't belong to you."); _; } // 设置升级费(只有合约拥有者才可以修改) function setLevelUpFee(uint fee) external onlyOwner { levelUpFee = fee; } // 付费升级 function levelUp(uint zombieId) external payable { require(msg.value >= levelUpFee, "Your balance is not enough."); zombies[zombieId].level++; } // 僵尸改名(需为自己所拥有的僵尸并且等级至少2级) function changeName(uint zombieId, string calldata name) external aboveLevel(2, zombieId) onlyOwnerOf(zombieId) { zombies[zombieId].name = name; } // 自定义僵尸DNA(需为自己所拥有的僵尸并且等级至少20级) function changeDna(uint zombieId, uint dna) external aboveLevel(20, zombieId) onlyOwnerOf(zombieId) { zombies[zombieId].dna = dna; } // 获取地址所拥有的僵尸数组 function getZombiesByOwner(address owner) external view returns (uint[] memory) { // 为了节省gas消耗 在内存中创建结果数组 方法之后完后就会销毁 uint[] memory result = new uint[](ownerZombieCount[owner]); uint counter = 0; for (uint i = 0; i < zombies.length; i++) { if (zombieToOwner[i] == owner) { result[counter] = i; counter++; } } return result; } // 触发冷却 function _triggerCooldown(Zombie storage zombie) internal { // 冷却时间到次日凌晨0点 zombie.readyTime = uint32(block.timestamp + cooldownTime) - uint32(block.timestamp + cooldownTime) % 1 days; } // 判断僵尸是否完成冷却 function _isReady(Zombie storage zombie) internal view returns (bool) { return block.timestamp >= zombie.readyTime; } // 僵尸合体 产生新僵尸 function _multiply(uint zombieId, uint targetDna) internal onlyOwnerOf(zombieId) { Zombie storage zombie = zombies[zombieId]; require(_isReady(zombie), "Your zombie are cooldown"); // 取两个基因序列的平均数为新的基因序列 targetDna = targetDna % dnaModulus; // 确保目标基因序列满足格式 uint newDna = (zombie.dna + targetDna) / 2; newDna = newDna - newDna % 10 + 9; // 将基因最后一位改为9,标记为合体僵尸 _createZombie("NoName", newDna); // 触发冷却 _triggerCooldown(zombie); } }
自定义僵尸DNA(需为自己所拥有的僵尸并且等级至少20级)
function changeDna(uint zombieId, uint dna) external aboveLevel(20, zombieId) onlyOwnerOf(zombieId) { zombies[zombieId].dna = dna; }
6,375,436
./full_match/5/0x083958FdA091516D1960c59d232500B36A256D56/sources/contracts/NftRentMarketplace.sol
emit ItemListed(msg.sender, nftAddress, tokenId, newListing.expiration, newListing.price);
function addS_listing(address nftAddress, uint256 tokenId, Listing memory newListing) internal{ s_listings[nftAddress][tokenId] = newListing; activeListings.push(newListing); }
1,928,166
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../token/WePiggyToken.sol"; contract FundingManager is Ownable { using SafeMath for uint256; struct FundingHolderInfo { uint256 ratio; string name; address addr; } // The WePiggyToken ! WePiggyToken public piggy; // Info of each funding. FundingHolderInfo[] public fundingHolders; constructor(WePiggyToken _piggy) public { piggy = _piggy; } // Safe piggy transfer function, just in case if rounding error causes pool to not have enough PiggyToken. function safePiggyTransfer(address _to, uint256 _amount) internal { uint256 piggyBal = piggy.balanceOf(address(this)); if (_amount > piggyBal) { piggy.transfer(_to, piggyBal); } else { piggy.transfer(_to, _amount); } } //Update funding pool function addFunding(string memory _name, address _addr, uint256 _ratio) public onlyOwner { fundingHolders.push(FundingHolderInfo({ name : _name, addr : _addr, ratio : _ratio })); } //Update funding pool function setFunding(uint256 pid, string memory _name, address _addr, uint256 _ratio) public onlyOwner { FundingHolderInfo storage fhi = fundingHolders[pid]; fhi.name = _name; fhi.addr = _addr; fhi.ratio = _ratio; } // Return the pool pending balance. function getPendingBalance(uint256 pid) public view returns (uint256){ FundingHolderInfo storage fhi = fundingHolders[pid]; uint256 piggyBal = piggy.balanceOf(address(this)); uint _amount = piggyBal.mul(fhi.ratio).div(100); return _amount; } //claim wpc. every can call this function, but transfer token to function claim() public { uint256 piggyBal = piggy.balanceOf(address(this)); for (uint256 i = 0; i < fundingHolders.length; i++) { FundingHolderInfo storage fhi = fundingHolders[i]; uint _amount = piggyBal.mul(fhi.ratio).div(100); safePiggyTransfer(fhi.addr, _amount); } } }
Return the pool pending balance.
function getPendingBalance(uint256 pid) public view returns (uint256){ FundingHolderInfo storage fhi = fundingHolders[pid]; uint256 piggyBal = piggy.balanceOf(address(this)); uint _amount = piggyBal.mul(fhi.ratio).div(100); return _amount; }
1,078,009
./full_match/1/0x91b3acfb92BCEf1DE4D5069e95140Ea0C9218695/sources/browser/WebaverseERC20Proxy.sol
0x08E242bB06D85073e69222aF8273af419d19E4f6, 1, 10, 0xc336b0bb5cac4584d79e77b1680ab789171ebc95f44f68bb1cc0a7b1174058ad, 0x72b888e952c0c39a8054f2b6dc41df645f5d4dc3d9cc6118535d88aa34945440, 0x1c
function withdraw(address to, uint256 amount, uint256 timestamp, bytes32 r, bytes32 s, uint8 v) public { bytes memory message = abi.encodePacked(to, amount, timestamp, chainId); bytes32 messageHash = keccak256(message); bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, messageHash)); require(ecrecover(prefixedHash, v, r, s) == signer, "invalid signature"); require(!usedWithdrawHashes[prefixedHash], "hash already used"); usedWithdrawHashes[prefixedHash] = true; bool needsMint = deposits < amount; uint256 balanceNeeded = SafeMath.sub(amount, deposits); if (needsMint) { deposits = SafeMath.add(deposits, balanceNeeded); } deposits = SafeMath.sub(deposits, amount); emit Withdrew(to, amount, timestamp); if (needsMint) { parent.mint(address(this), balanceNeeded); } require(parent.transfer(to, amount), "transfer failed"); }
3,176,242
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "./AAVE/IERC20.sol"; import "./AAVE/IWETHGateway.sol"; import "./AAVE/IAToken.sol"; contract Lend { address admin; uint lastATokenBalance; address[] userIndex; struct UserStruct { uint totalDeposited; uint aTokenBalance; uint givePercent; uint savedInterest; uint index; } mapping(address => UserStruct) userStructs; address payable giveAddress; event Deposit(uint _totalDeposit, uint _interest); event DepositAave(uint _aTokenBalance); event Withdraw(address _beneficiary, uint _amount, bool _deleted); event Give(uint _amount); event AdjustGivingRate(address _user, uint _percentInterest); event AddressUpdated(address _admin, address _giveAddress); event AdminUpdated(address _oldAdmin, address _newAdmin); receive() external payable {} // For MAINNET + LOCAL, needs updating for KOVAN IWETHGateway gateway = IWETHGateway(0xDcD33426BA191383f1c9B431A342498fdac73488); IAToken aWETH = IAToken(0x030bA81f1c18d280636F32af80b9AAd02Cf0854e); IERC20 WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); constructor(address payable _giveAddress) { admin = msg.sender; giveAddress = _giveAddress; } // Handles deposits, updates user struct and calls depositAave function deposit(uint _interest) external payable { scaleBalances(); bool _exists = checkUserExistence(msg.sender); if (_exists == false) { userIndex.push(msg.sender); } userStructs[msg.sender].totalDeposited += userStructs[msg.sender].totalDeposited; userStructs[msg.sender].givePercent = _interest; userStructs[msg.sender].index = userIndex.length-1; emit Deposit(userStructs[msg.sender].totalDeposited, _interest); depositAave(msg.sender, msg.value); } // Check if a user exists function checkUserExistence(address _userAddress) public view returns(bool) { uint _index = userStructs[_userAddress].index; address _indexed_address = userIndex[_index]; if (_userAddress == _indexed_address) { return true; } else { return false; } } // Take ETH and deposit it into the AAVE lending protocol function depositAave(address _spender, uint _amount) private { gateway.depositETH{value: _amount}(address(this), 0); userStructs[_spender].aTokenBalance += userStructs[_spender].aTokenBalance + _amount; lastATokenBalance = aWETH.balanceOf(address(this)); emit DepositAave(userStructs[_spender].aTokenBalance); } // Scales up aToken balances for all users to account for accrued interest function scaleBalances() private { uint _aTokenBalance = aWETH.balanceOf(address(this)); uint scalingFactor = (_aTokenBalance * 100)/lastATokenBalance; for (uint i=0; i < userIndex.length; i++) { userStructs[userIndex[0]].aTokenBalance = userStructs[userIndex[0]].aTokenBalance * (scalingFactor/100); } } // Withdraw ETH to the beneficiary's address function withdraw(uint _amount, bool _all) external { scaleBalances(); require(userStructs[msg.sender].aTokenBalance >= _amount, "Trying to withdraw more than amount in account."); if (_all == true) { gateway.withdrawETH(uint(-1), msg.sender); deleteUser(msg.sender); } else if (_all == false) { gateway.withdrawETH(_amount, msg.sender); } lastATokenBalance = aWETH.balanceOf(address(this)); emit Withdraw(msg.sender, _amount, _all); } // Remove a user from userIndex and reorder function deleteUser(address _user) private { uint index = userStructs[_user].index; address structToMove = userIndex[userIndex.length-1]; userIndex[index] = structToMove; userStructs[structToMove].index = index; delete userIndex[userIndex.length-1]; } // Sends a percentage to the give address function give() private { scaleBalances(); uint _giveAmount = 0; for (uint i; i < userIndex.length; i++) { uint _giveableGain = userStructs[userIndex[i]].aTokenBalance - userStructs[userIndex[i]].savedInterest - userStructs[userIndex[i]].totalDeposited; _giveAmount = _giveAmount + ((_giveableGain * userStructs[userIndex[i]].givePercent)/100); userStructs[userIndex[i]].savedInterest = userStructs[userIndex[i]].savedInterest + (_giveableGain - _giveAmount); } aWETH.transfer(giveAddress, _giveAmount); lastATokenBalance = aWETH.balanceOf(address(this)); emit Give(_giveAmount); } // Adjust the user's give percentage function adjustGivingRate(uint _percentInterest) external { require(checkUserExistence(msg.sender), "You must be a depositor to adjust your give percentage."); userStructs[msg.sender].givePercent = _percentInterest; emit AdjustGivingRate(msg.sender, _percentInterest); } // Read a user balance from the contract function balanceOf(address _account) external view returns (uint) { return userStructs[_account].aTokenBalance; } // Update the give address function updateGiveAddress(address payable _giveAddress) public { require(msg.sender == admin, "You do not have permission to update the giving address."); giveAddress = _giveAddress; emit AddressUpdated(msg.sender, _giveAddress); } // Transfer admin privileges function updateAdmin(address _newAdmin) external { require(msg.sender == admin, "Only the current admin can elect a new admin."); admin = _newAdmin; emit AdminUpdated(msg.sender, admin); } }
Read a user balance from the contract
function balanceOf(address _account) external view returns (uint) { return userStructs[_account].aTokenBalance; }
12,898,285