file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/42/0xE3fd40E658284bac18b42b15A8a7B6C8E2D3Dbb0/sources/contracts/BaseRewardPool.sol
Claims Reward for signer
function getReward() external { getReward(msg.sender, true); }
9,570,981
./full_match/4/0x71aDb425cC2aC83319FFBE30664916Fddc106588/sources/kali.sol
DAO membership extension module.
interface IKaliDAOextension { function extensionCall(address account, uint256 amount) external payable returns (uint256 amountOut); }
693,310
./partial_match/1/0xABF05c898AB723b22485B85cE0Ded84b7bd8eD7F/sources/IconFactory.sol
This is a generic factory contract that can be used to mint tokens. The configuration for minting is specified by an _optionId, which can be used to delineate various ways of minting./
interface Factory { function name() external view returns (string memory); function symbol() external view returns (string memory); function numOptions() external view returns (uint256); function canMint(uint256 _optionId) external view returns (bool); function tokenURI(uint256 _optionId) external view returns (string memory); function supportsFactoryInterface() external view returns (bool); function mint(uint256 _optionId, address _toAddress) external; }
4,100,357
// SPDX-License-Identifier: MIT pragma solidity ^0.6.7; import "../lib/safe-math.sol"; import "../lib/erc20.sol"; import "../interfaces/backscratcher/IStrategyProxy.sol"; interface FeeDistribution { function claim(address) external; } contract veFXSVault { using SafeMath for uint256; /// @notice EIP-20 token name for this token string public constant name = "pickle veFXS Vault"; /// @notice EIP-20 token symbol for this token string public constant symbol = "pveFXS"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public totalSupply = 0; // Initial 0 /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @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; mapping(address => mapping(address => uint256)) internal allowances; mapping(address => uint256) internal balances; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); bytes32 public immutable DOMAINSEPARATOR; /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint nonce,uint expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) 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, uint256 previousBalance, uint256 newBalance); /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { _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, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { 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), "delegateBySig: sig"); require(nonce == nonces[signatory]++, "delegateBySig: nonce"); require(block.timestamp <= expiry, "delegateBySig: expired"); _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, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "getPriorVotes:"); 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 = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount, "_moveVotes: underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { 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, "_writeCheckpoint: 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(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /// @notice governance address for the governance contract address public governance; address public pendingGovernance; IERC20 public constant FXS = IERC20(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); address public locker = 0xd639C2eA4eEFfAD39b599410d00252E6c80008DF; address public proxy = 0x26B62c5F0bA4eB6a4Aff34141AF43Af7b5454a78; address public feeDistribution = 0x26B62c5F0bA4eB6a4Aff34141AF43Af7b5454a78; IERC20 public constant rewards = IERC20(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); uint256 public index = 0; uint256 public bal = 0; mapping(address => uint256) public supplyIndex; constructor() public { // Set governance for this token governance = msg.sender; DOMAINSEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this))); } function update() external { _update(); } function _update() internal { if (totalSupply > 0) { _claim(); uint256 _bal = rewards.balanceOf(address(this)); if (_bal > bal) { uint256 _diff = _bal.sub(bal); if (_diff > 0) { uint256 _ratio = _diff.mul(1e18).div(totalSupply); if (_ratio > 0) { index = index.add(_ratio); bal = _bal; } } } } } function _claim() internal { if (feeDistribution != address(0x0)) { FeeDistribution(feeDistribution).claim(address(this)); } } function updateFor(address recipient) public { _update(); uint256 _supplied = balances[recipient]; if (_supplied > 0) { uint256 _supplyIndex = supplyIndex[recipient]; supplyIndex[recipient] = index; uint256 _delta = index.sub(_supplyIndex); if (_delta > 0) { uint256 _share = _supplied.mul(_delta).div(1e18); claimable[recipient] = claimable[recipient].add(_share); } } else { supplyIndex[recipient] = index; } } mapping(address => uint256) public claimable; function claim() external { _claimFor(msg.sender); } function claimFor(address recipient) external { _claimFor(recipient); } function _claimFor(address recipient) internal { updateFor(recipient); rewards.transfer(recipient, claimable[recipient]); claimable[recipient] = 0; bal = rewards.balanceOf(address(this)); } function _mint(address dst, uint256 amount) internal { updateFor(dst); // mint the amount totalSupply = totalSupply.add(amount); // transfer the amount to the recipient balances[dst] = balances[dst].add(amount); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } function depositAll() external { _deposit(FXS.balanceOf(msg.sender)); } function deposit(uint256 _amount) external { _deposit(_amount); } function _deposit(uint256 _amount) internal { FXS.transferFrom(msg.sender, locker, _amount); _mint(msg.sender, _amount); IStrategyProxy(proxy).lock(); } function setProxy(address _proxy) external { require(msg.sender == governance, "setGovernance: !gov"); proxy = _proxy; } function setLocker(address _locker) external { require(msg.sender == governance, "setGovernance: !gov"); locker = _locker; } function setFeeDistribution(address _feeDistribution) external { require(msg.sender == governance, "setGovernance: !gov"); feeDistribution = _feeDistribution; } /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external { require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param amount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "permit: signature"); require(signatory == owner, "permit: unauthorized"); require(block.timestamp <= deadline, "permit: expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool) { _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint256(-1)) { uint256 newAllowance = spenderAllowance.sub(amount); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens( address src, address dst, uint256 amount ) internal { require(src != address(0), "_transferTokens: zero address"); require(dst != address(0), "_transferTokens: zero address"); updateFor(src); updateFor(dst); balances[src] = balances[src].sub(amount); balances[dst] = balances[dst].add(amount); emit Transfer(src, dst, amount); } function _getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } // **** Emergency functions **** function execute(address _target, bytes memory _data) public payable returns (bytes memory response) { require(msg.sender == governance, "!governance"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0) let size := returndatasize() response := mload(0x40) mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } } // 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; } } // File: contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./safe-math.sol"; import "./context.sol"; // File: contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.7; pragma experimental ABIEncoderV2; import "./FraxGauge.sol"; interface IStrategyProxy { function withdrawV3( address _gauge, uint256 _tokenId, address[] calldata _rewardTokens ) external returns (uint256); function withdrawV2( address _gauge, address _token, bytes32 _kek_id, address[] calldata _rewardTokens ) external returns (uint256); function balanceOf(address _gauge) external view returns (uint256); function lockedNFTsOf(address _gauge) external view returns (LockedNFT[] memory); function lockedStakesOf(address _gauge) external view returns (LockedStake[] memory); function withdrawAllV3( address _gauge, address _token, address[] calldata _rewardTokens ) external returns (uint256 amount); function withdrawAllV2( address _gauge, address _token, address[] calldata _rewardTokens ) external returns (uint256 amount); function harvest(address _gauge, address[] calldata _tokens) external; function depositV2( address _gauge, address _token, uint256 _secs ) external; function depositV3( address _gauge, uint256 _tokenId, uint256 _secs ) external; function claim(address recipient) external; function lock() external; function claimRewards(address _gauge, address _token) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; struct LockedNFT { uint256 token_id; // for Uniswap V3 LPs uint256 liquidity; uint256 start_timestamp; uint256 ending_timestamp; uint256 lock_multiplier; // 6 decimals of precision. 1x = 1000000 int24 tick_lower; int24 tick_upper; } struct LockedStake { bytes32 kek_id; uint256 start_timestamp; uint256 liquidity; uint256 ending_timestamp; uint256 lock_multiplier; // 6 decimals of precision. 1x = 1000000 } interface IFraxGaugeBase { function lockedLiquidityOf(address account) external view returns (uint256); function getReward() external returns (uint256); function lock_time_min() external returns (uint256); function combinedWeightOf(address account) external view returns (uint256); } interface IFraxGaugeUniV3 is IFraxGaugeBase { function stakeLocked(uint256 token_id, uint256 secs) external; function withdrawLocked(uint256 token_id) external; function lockedNFTsOf(address account) external view returns (LockedNFT[] memory); } interface IFraxGaugeUniV2 { function stakeLocked(uint256 liquidity, uint256 secs) external; function lockedStakesOf(address) external view returns (LockedStake[] memory); function withdrawLocked(bytes32 kek_id) external; function getAllRewardTokens() external view returns (address[] memory); }
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "getPriorVotes:"); 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; }
14,422,433
./full_match/43113/0x22458DfD44F7F211D21b5F0A02879bA9923A9EB0/sources/contracts/SingleStakeFactory_flattened.sol
Internal hook called before stopping the emission process (in the stopEmission() function). _refundAddress address to refund the remaining reward to/
function _beforeStopEmission(address _refundAddress) internal virtual {}
7,118,872
pragma solidity 0.5.8; import "truffle/Assert.sol"; import "../contracts/StringUtil.sol"; contract TestStringUtil { using StringUtil for string; string[] private testStringArray; // Test small string allocation. Make sure that there is always enough allocated. function testSmallStringSizeAllocation() public { string memory testString = "one"; uint size = bytes(testString).length; Assert.equal(size, 3, "Test string size should be three (3)"); Assert.equal(StringUtil.getSize(testString), 64, "Test string allocation size should be 64"); } // Test bigger string allocation. Make sure that size will be increased. function testBigStringSizeAllocation() public { string memory testString = "onetwothreefourfivesixseveneightnineteneleventwelvethirteenfourteen"; uint size = bytes(testString).length; Assert.equal(size, 67, "Test string size should be sixtyseven (67)"); Assert.equal(StringUtil.getSize(testString), 128, "Test string size should be 128"); } // Test logic with empty array. Should return empty string. function testConvertEmptyArrayInBytes() public { testStringArray = new string[](0); bytes memory emptyStringArrayInBytes = convertStringArrayToBytes(); string memory arraString = string(emptyStringArrayInBytes); Assert.equal(arraString, "", "Test array should be empty"); } // Test if array contains only one entry. Entry should be found from the // beginning of converted string. function testConvertArrayContainingOneStringInBytes() public { testStringArray = ["one"]; string memory arraString = string(convertStringArrayToBytes()); string memory firstString = substring(arraString, 0, 3); string memory expected = "one"; Assert.equal(firstString, expected, "Test array should contain only string 'one'"); } // Test if array contains multiple entry. Entry should be found from the // beginning of every 64 slot. function testConvertArrayContainingMultipleStringsInBytes() public { testStringArray = ["one", "two", "three"]; string memory arraString = string(convertStringArrayToBytes()); string memory firstString = substring(arraString, 0, 3); string memory secondString = substring(arraString, 64, 67); string memory thirdString = substring(arraString, 128, 133); Assert.equal(firstString, "one", "Test array should contain only string 'one'"); Assert.equal(secondString, "two", "Test array should contain only string 'two'"); Assert.equal(thirdString, "three", "Test array should contain only string 'three'"); } /** @dev Get substring of given string. This is test helper method. * @return substr Substring of the given string */ function substring(string memory str, uint startIndex, uint endIndex) private pure returns (string memory substr) { bytes memory strBytes = bytes(str); bytes memory result = new bytes(endIndex-startIndex); for (uint i = startIndex; i < endIndex; i++) { result[i-startIndex] = strBytes[i]; } return string(result); } /** @dev Get string array in bytes. Iterate through array items and * transfer strings into bytes. This is test helper method. * @return serialized Names array in bytes. */ function convertStringArrayToBytes() private view returns(bytes memory serialized) { uint offset = 64*testStringArray.length; bytes memory buffer = new bytes(offset); string memory str = new string(32); for (uint i = testStringArray.length - 1; i < testStringArray.length; i--) { str = testStringArray[i]; StringUtil.stringToBytes(offset, bytes(str), buffer); offset -= str.getSize(); } return (buffer); } }
Test logic with empty array. Should return empty string.
function testConvertEmptyArrayInBytes() public { testStringArray = new string[](0); bytes memory emptyStringArrayInBytes = convertStringArrayToBytes(); string memory arraString = string(emptyStringArrayInBytes); Assert.equal(arraString, "", "Test array should be empty"); }
1,037,886
./full_match/69/0xa46d600e30D9C718F44F675d85f550eb843601e9/sources/contracts/RubiconMarket.sol
Accept a given `quantity` of an offer. Transfers funds from caller/taker to offer maker, and from market to caller/taker. The fee for taker trades is paid in this function. For backwards semantic compatibility.
function buy(uint256 id, uint256 quantity) public virtual can_buy(id) synchronized returns (bool) { OfferInfo memory offer = offers[id]; uint256 spend = mul(quantity, offer.buy_amt) / offer.pay_amt; require(uint128(spend) == spend, "spend is not an int"); require(uint128(quantity) == quantity, "quantity is not an int"); if ( quantity == 0 || spend == 0 || quantity > offer.pay_amt || spend > offer.buy_amt ) { return false; } uint256 fee = mul(spend, feeBPS) / 10000; require( offer.buy_gem.transferFrom(msg.sender, feeTo, fee), "Insufficient funds to cover fee" ); offers[id].pay_amt = sub(offer.pay_amt, quantity); offers[id].buy_amt = sub(offer.buy_amt, spend); require( offer.buy_gem.transferFrom(msg.sender, offer.owner, spend), "offer.buy_gem.transferFrom(msg.sender, offer.owner, spend) failed - check that you can pay the fee" ); require( offer.pay_gem.transfer(msg.sender, quantity), "offer.pay_gem.transfer(msg.sender, quantity) failed" ); emit LogItemUpdate(id); emit LogTake( bytes32(id), keccak256(abi.encodePacked(offer.pay_gem, offer.buy_gem)), offer.owner, offer.pay_gem, offer.buy_gem, msg.sender, uint128(quantity), uint128(spend), uint64(block.timestamp) ); emit FeeTake( bytes32(id), keccak256(abi.encodePacked(offer.pay_gem, offer.buy_gem)), offer.owner, offer.pay_gem, offer.buy_gem, msg.sender, uint128(quantity), uint128(spend), fee, feeTo, uint64(block.timestamp) ); emit LogTrade( quantity, address(offer.pay_gem), spend, address(offer.buy_gem) ); if (offers[id].pay_amt == 0) { delete offers[id]; emit OfferDeleted(id); } return true; }
13,238,890
./full_match/5/0xd5E86F0A702aD8124Ed9B02B373837De4fE8553D/sources/_cartesi/util/contracts/MerkleV2.sol
Gets precomputed hash of zero in empty tree hashes _index of hash wanted first index is keccak(0), second index is keccak(keccak(0), keccak(0)) first word is length, then skip index words
function getEmptyTreeHashAtIndex(uint256 _index) public pure returns (bytes32) { uint256 start = _index * 32; require(EMPTY_TREE_SIZE >= start + 32, "index out of bounds"); bytes32 hashedZeros; bytes memory zeroTree = EMPTY_TREE_HASHES; assembly { hashedZeros := mload(add(add(zeroTree, 0x20), start)) } return hashedZeros; }
7,044,752
pragma solidity 0.4.15; import './AccessControl/AccessControlled.sol'; import './AccessRoles.sol'; import './Reclaimable.sol'; import './Standards/IEthereumForkArbiter.sol'; contract EthereumForkArbiter is IEthereumForkArbiter, AccessControlled, AccessRoles, Reclaimable { //////////////////////// // Mutable state //////////////////////// string private _nextForkName; string private _nextForkUrl; uint256 private _nextForkBlockNumber; uint256 private _lastSignedBlockNumber; bytes32 private _lastSignedBlockHash; uint256 private _lastSignedTimestamp; //////////////////////// // Constructor //////////////////////// function EthereumForkArbiter(IAccessPolicy accessPolicy) AccessControlled(accessPolicy) Reclaimable() public { } //////////////////////// // Public functions //////////////////////// /// @notice Announce that a particular future Ethereum fork will the one taken by the contract. The contract on the other branch should be considered invalid. Once the fork has happened, it will additionally be confirmed by signing a block on the fork. Notice that forks may happen unannounced. function announceFork( string name, string url, uint256 blockNumber ) public only(ROLE_PLATFORM_OPERATOR_REPRESENTATIVE) { require(blockNumber == 0 || blockNumber > block.number); // Store announcement _nextForkName = name; _nextForkUrl = url; _nextForkBlockNumber = blockNumber; // Log LogForkAnnounced(_nextForkName, _nextForkUrl, _nextForkBlockNumber); } /// @notice Declare that the current fork (as identified by a blockhash) is the valid fork. The valid fork is always the one with the most recent signature. function signFork(uint256 number, bytes32 hash) public only(ROLE_PLATFORM_OPERATOR_REPRESENTATIVE) { require(block.blockhash(number) == hash); // Reset announcement delete _nextForkName; delete _nextForkUrl; delete _nextForkBlockNumber; // Store signature _lastSignedBlockNumber = number; _lastSignedBlockHash = hash; _lastSignedTimestamp = block.timestamp; // Log LogForkSigned(_lastSignedBlockNumber, _lastSignedBlockHash); } function nextForkName() public constant returns (string) { return _nextForkName; } function nextForkUrl() public constant returns (string) { return _nextForkUrl; } function nextForkBlockNumber() public constant returns (uint256) { return _nextForkBlockNumber; } function lastSignedBlockNumber() public constant returns (uint256) { return _lastSignedBlockNumber; } function lastSignedBlockHash() public constant returns (bytes32) { return _lastSignedBlockHash; } function lastSignedTimestamp() public constant returns (uint256) { return _lastSignedTimestamp; } }
Mutable state Constructor
{ string private _nextForkName; string private _nextForkUrl; uint256 private _nextForkBlockNumber; uint256 private _lastSignedBlockNumber; bytes32 private _lastSignedBlockHash; uint256 private _lastSignedTimestamp; function EthereumForkArbiter(IAccessPolicy accessPolicy) AccessControlled(accessPolicy) Reclaimable() public { } function announceFork( string name, string url, uint256 blockNumber ) public only(ROLE_PLATFORM_OPERATOR_REPRESENTATIVE) { require(blockNumber == 0 || blockNumber > block.number); _nextForkName = name; _nextForkUrl = url; _nextForkBlockNumber = blockNumber; LogForkAnnounced(_nextForkName, _nextForkUrl, _nextForkBlockNumber); } function signFork(uint256 number, bytes32 hash) public only(ROLE_PLATFORM_OPERATOR_REPRESENTATIVE) { require(block.blockhash(number) == hash); delete _nextForkName; delete _nextForkUrl; delete _nextForkBlockNumber; _lastSignedBlockNumber = number; _lastSignedBlockHash = hash; _lastSignedTimestamp = block.timestamp; LogForkSigned(_lastSignedBlockNumber, _lastSignedBlockHash); } function nextForkName() public constant returns (string) { return _nextForkName; } function nextForkUrl() public constant returns (string) { return _nextForkUrl; } function nextForkBlockNumber() public constant returns (uint256) { return _nextForkBlockNumber; } function lastSignedBlockNumber() public constant returns (uint256) { return _lastSignedBlockNumber; } function lastSignedBlockHash() public constant returns (bytes32) { return _lastSignedBlockHash; } function lastSignedTimestamp() public constant returns (uint256) { return _lastSignedTimestamp; } }
6,366,306
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; contract RockPaperScissors { uint gamesPlayed; event StartGame(address indexed initiator, address indexed opponent, uint gameId); event MakeMove(uint gameId, address indexed initiator, string indexed move); struct Game { address first_player; address second_player; string first_player_choice; string second_player_choice; } // Mapping of IDs to games mapping(uint => Game) games; // To get the total number of games played function count() public view returns(uint){ return gamesPlayed; } // Start a game with desired opponent function startGameWith(address opponent) public{ // You can't play with yourself require(msg.sender!=opponent, "You can't play with yourself"); gamesPlayed++; Game storage game = games[gamesPlayed]; game.first_player = msg.sender; game.second_player = opponent; emit StartGame(msg.sender, opponent, gamesPlayed); } // Choose your move in a particular game function makeMove(uint gameId, string memory move) public{ Game storage game = games[gameId]; string memory empty = ""; // Game must exist require(gameId<=gamesPlayed, "Game must exist"); // Must be permitted to play the game require(msg.sender==game.first_player || msg.sender==game.second_player, "Must be permitted to play the game"); // Makes only a valid move require(compareStrings(move,"ROCK") || compareStrings(move,"PAPER") || compareStrings(move,"SCISSORS"), "Makes only a valid move"); if(msg.sender==game.first_player){ // Must be making a fresh move require(compareStrings(game.first_player_choice, empty),"Must be making a new move"); game.first_player_choice=move; } else { // Must be making a fresh move require(compareStrings(game.second_player_choice,empty), "Must be making a new move"); game.second_player_choice=move; } emit MakeMove(gameId, msg.sender, move); } // Get winner for a game function getWinner(uint gameId) public view returns(address){ Game storage game = games[gameId]; string memory empty = ""; // Check if both players are done require(!compareStrings(game.first_player_choice, empty) && !compareStrings(game.second_player_choice,empty), "both players must be done"); // Check if it's not a tie if(compareStrings(game.first_player_choice,game.second_player_choice)){ return address(0); } // Shortening the variables string memory f = game.first_player_choice; string memory s = game.second_player_choice; // Check if player one wins, i.e.: (R, S) or (S,P) or (P,R) if((compareStrings(f,"ROCK")&&compareStrings(s,"SCISSORS")) || (compareStrings(f,"SCISSORS")&&compareStrings(s,"PAPER")) || (compareStrings(f,"PAPER")&&compareStrings(s,"ROCK"))) { return game.first_player; } return game.second_player; } // compare Strings function compareStrings(string memory a, string memory b) private pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } }
To get the total number of games played
function count() public view returns(uint){ return gamesPlayed; }
932,385
./full_match/1/0x90Ae15e263E663fc6b425cA645e452fCBCcc3991/sources/artifacts/farm.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(address(_lpToken) != address(0), "_lpToken is the zero address"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, acctkfPerShare: 0, totalAmount : 0 })); }
9,693,056
./full_match/421613/0xA0902D3F318f287a6bfa313d19dCe7Bc3BB882Ce/sources/project_/contracts/mercenaries/Mercenaries.sol
Allow an external contract to mint a mercenary Enables giveaways to supportive community members Enables external contracts with permission to mint mercenaries for promotions to recipient traits an array representing the mercenaries traits e.g., ["blue hat","brown eyes] Increment wrapped token id Store the wTokenID as a local variable Set the stats Calculate the underlying token hash Add Collection address to the mapping Add Token ID to the mapping Map the underlying token hash to the wrapped token id Add Visual Traits for mercenary Mint the Mercenaries
function mint(address to, bytes16[] calldata traits) external nonReentrant onlyAllowed { uint256 tokenID = wTokenID; _storeStats(address(this),tokenID); bytes32 underlyingTokenHash = hashUnderlyingToken(address(this), tokenID); underlyingToken[underlyingTokenHash].collectionAddress = address(this); underlyingToken[underlyingTokenHash].tokenID = tokenID; wrappedCharacter[tokenID] = underlyingTokenHash; _updateTraits(tokenID, traits); _mint(to, tokenID); }
11,567,089
/** *Submitted for verification at Etherscan.io on 2021-08-05 */ // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/interfaces/vesper/IController.sol pragma solidity 0.6.12; interface IController { function aaveReferralCode() external view returns (uint16); function feeCollector(address) external view returns (address); function founderFee() external view returns (uint256); function founderVault() external view returns (address); function interestFee(address) external view returns (uint256); function isPool(address) external view returns (bool); function pools() external view returns (address); function strategy(address) external view returns (address); function rebalanceFriction(address) external view returns (uint256); function poolRewards(address) external view returns (address); function treasuryPool() external view returns (address); function uniswapRouter() external view returns (address); function withdrawFee(address) external view returns (uint256); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity >=0.6.0 <0.8.0; // File: contracts/Pausable.sol pragma solidity 0.6.12; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * */ contract Pausable is Context { event Paused(address account); event Shutdown(address account); event Unpaused(address account); event Open(address account); bool public paused; bool public stopEverything; modifier whenNotPaused() { require(!paused, "Pausable: paused"); _; } modifier whenPaused() { require(paused, "Pausable: not paused"); _; } modifier whenNotShutdown() { require(!stopEverything, "Pausable: shutdown"); _; } modifier whenShutdown() { require(stopEverything, "Pausable: not shutdown"); _; } /// @dev Pause contract operations, if contract is not paused. function _pause() internal virtual whenNotPaused { paused = true; emit Paused(_msgSender()); } /// @dev Unpause contract operations, allow only if contract is paused and not shutdown. function _unpause() internal virtual whenPaused whenNotShutdown { paused = false; emit Unpaused(_msgSender()); } /// @dev Shutdown contract operations, if not already shutdown. function _shutdown() internal virtual whenNotShutdown { stopEverything = true; paused = true; emit Shutdown(_msgSender()); } /// @dev Open contract operations, if contract is in shutdown state function _open() internal virtual whenShutdown { stopEverything = false; emit Open(_msgSender()); } } // File: contracts/interfaces/uniswap/IUniswapV2Router01.sol pragma solidity 0.6.12; interface IUniswapV2Router01 { function factory() external pure returns (address); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // File: contracts/interfaces/uniswap/IUniswapV2Router02.sol pragma solidity 0.6.12; interface IUniswapV2Router02 is IUniswapV2Router01 { function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // File: contracts/interfaces/bloq/ISwapManager.sol pragma solidity 0.6.12; /* solhint-disable func-name-mixedcase */ interface ISwapManager { event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period); function N_DEX() external view returns (uint256); function ROUTERS(uint256 i) external view returns (IUniswapV2Router02); function bestOutputFixedInput( address _from, address _to, uint256 _amountIn ) external view returns ( address[] memory path, uint256 amountOut, uint256 rIdx ); function bestPathFixedInput( address _from, address _to, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function bestInputFixedOutput( address _from, address _to, uint256 _amountOut ) external view returns ( address[] memory path, uint256 amountIn, uint256 rIdx ); function bestPathFixedOutput( address _from, address _to, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function safeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function safeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function comparePathsFixedInput( address[] memory pathA, address[] memory pathB, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function comparePathsFixedOutput( address[] memory pathA, address[] memory pathB, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function ours(address a) external view returns (bool); function oracleCount() external view returns (uint256); function oracleAt(uint256 idx) external view returns (address); function getOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external view returns (address); function createOrUpdateOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external returns (address oracleAddr); function consultForFree( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external view returns (uint256 amountOut, uint256 lastUpdatedAt); /// get the data we want and pay the gas to update function consult( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external returns ( uint256 amountOut, uint256 lastUpdatedAt, bool updated ); function updateOracles() external returns (uint256 updated, uint256 expected); function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected); } // File: contracts/interfaces/vesper/IStrategy.sol pragma solidity 0.6.12; interface IStrategy { function rebalance() external; function deposit(uint256 amount) external; function beforeWithdraw() external; function withdraw(uint256 amount) external; function withdrawAll() external; function isUpgradable() external view returns (bool); function isReservedToken(address _token) external view returns (bool); function token() external view returns (address); function pool() external view returns (address); function totalLocked() external view returns (uint256); //Lifecycle functions function pause() external; function unpause() external; } // File: contracts/interfaces/vesper/IVesperPool.sol pragma solidity 0.6.12; interface IVesperPool is IERC20 { function approveToken() external; function deposit() external payable; function deposit(uint256) external; function multiTransfer(uint256[] memory) external returns (bool); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function rebalance() external; function resetApproval() external; function sweepErc20(address) external; function withdraw(uint256) external; function withdrawETH(uint256) external; function withdrawByStrategy(uint256) external; function feeCollector() external view returns (address); function getPricePerShare() external view returns (uint256); function token() external view returns (address); function tokensHere() external view returns (uint256); function totalValue() external view returns (uint256); function withdrawFee() external view returns (uint256); } // File: sol-address-list/contracts/interfaces/IAddressList.sol pragma solidity ^0.6.6; interface IAddressList { event AddressUpdated(address indexed a, address indexed sender); event AddressRemoved(address indexed a, address indexed sender); function add(address a) external returns (bool); function addValue(address a, uint256 v) external returns (bool); function addMulti(address[] calldata addrs) external returns (uint256); function addValueMulti(address[] calldata addrs, uint256[] calldata values) external returns (uint256); function remove(address a) external returns (bool); function removeMulti(address[] calldata addrs) external returns (uint256); function get(address a) external view returns (uint256); function contains(address a) external view returns (bool); function at(uint256 index) external view returns (address, uint256); function length() external view returns (uint256); } // File: sol-address-list/contracts/interfaces/IAddressListExt.sol pragma solidity ^0.6.6; interface IAddressListExt is IAddressList { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // File: sol-address-list/contracts/interfaces/IAddressListFactory.sol pragma solidity ^0.6.6; interface IAddressListFactory { event ListCreated(address indexed _sender, address indexed _newList); function ours(address a) external view returns (bool); function listCount() external view returns (uint256); function listAt(uint256 idx) external view returns (address); function createList() external returns (address listaddr); } // File: contracts/strategies/Strategy.sol pragma solidity 0.6.12; abstract contract Strategy is IStrategy, Pausable { using SafeERC20 for IERC20; using SafeMath for uint256; // solhint-disable-next-line ISwapManager public swapManager = ISwapManager(0xe382d9f2394A359B01006faa8A1864b8a60d2710); IController public immutable controller; IERC20 public immutable collateralToken; address public immutable receiptToken; address public immutable override pool; IAddressListExt public keepers; address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 internal constant MAX_UINT_VALUE = type(uint256).max; event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager); constructor( address _controller, address _pool, address _receiptToken ) public { require(_controller != address(0), "controller-address-is-zero"); require(IController(_controller).isPool(_pool), "not-a-valid-pool"); controller = IController(_controller); pool = _pool; collateralToken = IERC20(IVesperPool(_pool).token()); receiptToken = _receiptToken; } modifier onlyAuthorized() { require( _msgSender() == address(controller) || _msgSender() == pool, "caller-is-not-authorized" ); _; } modifier onlyController() { require(_msgSender() == address(controller), "caller-is-not-the-controller"); _; } modifier onlyKeeper() { require(keepers.contains(_msgSender()), "caller-is-not-keeper"); _; } modifier onlyPool() { require(_msgSender() == pool, "caller-is-not-the-pool"); _; } function pause() external override onlyController { _pause(); } function unpause() external override onlyController { _unpause(); } /// @dev Approve all required tokens function approveToken() external onlyController { _approveToken(0); _approveToken(MAX_UINT_VALUE); } /// @dev Reset approval of all required tokens function resetApproval() external onlyController { _approveToken(0); } /** * @notice Create keeper list * @dev Create keeper list * NOTE: Any function with onlyKeeper modifier will not work until this function is called. * NOTE: Due to gas constraint this function cannot be called in constructor. */ function createKeeperList() external onlyController { require(address(keepers) == address(0), "keeper-list-already-created"); IAddressListFactory factory = IAddressListFactory(0xD57b41649f822C51a73C44Ba0B3da4A880aF0029); keepers = IAddressListExt(factory.createList()); keepers.grantRole(keccak256("LIST_ADMIN"), _msgSender()); } /** * @notice Update swap manager address * @param _swapManager swap manager address */ function updateSwapManager(address _swapManager) external onlyController { require(_swapManager != address(0), "sm-address-is-zero"); require(_swapManager != address(swapManager), "sm-is-same"); emit UpdatedSwapManager(address(swapManager), _swapManager); swapManager = ISwapManager(_swapManager); } /** * @dev Deposit collateral token into lending pool. * @param _amount Amount of collateral token */ function deposit(uint256 _amount) public override onlyKeeper { _updatePendingFee(); _deposit(_amount); } /** * @notice Deposit all collateral token from pool to other lending pool. * Anyone can call it except when paused. */ function depositAll() external virtual onlyKeeper { deposit(collateralToken.balanceOf(pool)); } /** * @dev Withdraw collateral token from lending pool. * @param _amount Amount of collateral token */ function withdraw(uint256 _amount) external override onlyAuthorized { _updatePendingFee(); _withdraw(_amount); } /** * @dev Withdraw all collateral. No rebalance earning. * Controller only function, called when migrating strategy. */ function withdrawAll() external override onlyController { _withdrawAll(); } /** * @dev sweep given token to vesper pool * @param _fromToken token address to sweep */ function sweepErc20(address _fromToken) external onlyKeeper { require(!isReservedToken(_fromToken), "not-allowed-to-sweep"); if (_fromToken == ETH) { Address.sendValue(payable(pool), address(this).balance); } else { uint256 _amount = IERC20(_fromToken).balanceOf(address(this)); IERC20(_fromToken).safeTransfer(pool, _amount); } } /// @dev Returns true if strategy can be upgraded. function isUpgradable() external view virtual override returns (bool) { return totalLocked() == 0; } /// @dev Returns address of token correspond to collateral token function token() external view override returns (address) { return receiptToken; } /// @dev Convert from 18 decimals to token defined decimals. Default no conversion. function convertFrom18(uint256 amount) public pure virtual returns (uint256) { return amount; } /// @dev report the interest earned since last rebalance function interestEarned() external view virtual returns (uint256); /// @dev Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function isReservedToken(address _token) public view virtual override returns (bool); /// @dev Returns total collateral locked here function totalLocked() public view virtual override returns (uint256); /// @dev For moving between versions of similar strategies function migrateIn() external onlyController { _migrateIn(); } /// @dev For moving between versions of similar strategies function migrateOut() external onlyController { _migrateOut(); } /** * @notice Handle earned interest fee * @dev Earned interest fee will go to the fee collector. We want fee to be in form of Vepseer * pool tokens not in collateral tokens so we will deposit fee in Vesper pool and send vTokens * to fee collactor. * @param _fee Earned interest fee in collateral token. */ function _handleFee(uint256 _fee) internal virtual { if (_fee != 0) { IVesperPool(pool).deposit(_fee); uint256 _feeInVTokens = IERC20(pool).balanceOf(address(this)); IERC20(pool).safeTransfer(controller.feeCollector(pool), _feeInVTokens); } } /** * @notice Safe swap via Uniswap * @dev There are many scenarios when token swap via Uniswap can fail, so this * method will wrap Uniswap call in a 'try catch' to make it fail safe. * @param _from address of from token * @param _to address of to token * @param _amount Amount to be swapped */ function _safeSwap( address _from, address _to, uint256 _amount ) internal { (address[] memory _path, uint256 amountOut, uint256 rIdx) = swapManager.bestOutputFixedInput(_from, _to, _amount); if (amountOut != 0) { swapManager.ROUTERS(rIdx).swapExactTokensForTokens( _amount, 1, _path, address(this), block.timestamp + 30 ); } } function _deposit(uint256 _amount) internal virtual; function _withdraw(uint256 _amount) internal virtual; function _approveToken(uint256 _amount) internal virtual; function _updatePendingFee() internal virtual; function _withdrawAll() internal virtual; function _migrateIn() internal virtual; function _migrateOut() internal virtual; function _claimReward() internal virtual; } // File: contracts/interfaces/vesper/IVesperPoolV3.sol pragma solidity 0.6.12; interface IVesperPoolV3 is IERC20 { function deposit() external payable; function deposit(uint256 _share) external; function governor() external returns (address); function keepers() external returns (address); function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function excessDebt(address _strategy) external view returns (uint256); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external; function resetApproval() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function withdrawETH(uint256 _amount) external; function whitelistedWithdraw(uint256 _amount) external; function feeCollector() external view returns (address); function pricePerShare() external view returns (uint256); function token() external view returns (address); function tokensHere() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalValue() external view returns (uint256); function withdrawFee() external view returns (uint256); function poolRewards() external view returns (address); } // File: contracts/interfaces/vesper/IPoolRewardsV3.sol pragma solidity 0.6.12; interface IPoolRewardsV3 { /// Emitted after reward added event RewardAdded(uint256 reward); /// Emitted whenever any user claim rewards event RewardPaid(address indexed user, uint256 reward); /// Emitted when reward is ended event RewardEnded(address indexed dustReceiver, uint256 dust); // Emitted when pool governor update reward end time event UpdatedRewardEndTime(uint256 previousRewardEndTime, uint256 newRewardEndTime); function claimReward(address) external; function notifyRewardAmount(uint256 rewardAmount, uint256 endTime) external; function updateRewardEndTime() external; function updateReward(address) external; function withdrawRemaining(address _toAddress) external; function claimable(address) external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function rewardForDuration() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewardToken() external view returns (address); } // File: contracts/strategies/VesperV3Strategy.sol pragma solidity 0.6.12; /// @title This strategy will deposit collateral token in VesperV3 and earn interest. abstract contract VesperV3Strategy is Strategy { using SafeERC20 for IERC20; using SafeMath for uint256; IVesperPoolV3 internal immutable vToken; constructor( address _controller, address _pool, address _receiptToken ) public Strategy(_controller, _pool, _receiptToken) { vToken = IVesperPoolV3(_receiptToken); } /** * @notice Migrate tokens from pool to this address * @dev Any working VesperV3 strategy has vTokens in strategy contract. * @dev There can be scenarios when pool already has vTokens and new * strategy will have to move those tokens from pool to self address. * @dev Only valid pool strategy is allowed to move tokens from pool. */ function _migrateIn() internal override { require(controller.isPool(pool), "not-a-valid-pool"); require(controller.strategy(pool) == address(this), "not-a-valid-strategy"); IERC20(vToken).safeTransferFrom(pool, address(this), vToken.balanceOf(pool)); } /** * @notice Migrate tokens out to pool. * @dev There can be scenarios when we want to use new strategy without * calling withdrawAll(). We can achieve this by moving tokens in pool * and new strategy will take care from there. * @dev Pause this strategy and move tokens out. */ function _migrateOut() internal override { require(controller.isPool(pool), "not-a-valid-pool"); _pause(); IERC20(vToken).safeTransfer(pool, vToken.balanceOf(address(this))); } /// @notice Vesper pools are using this function so it should exist in all strategies. //solhint-disable-next-line no-empty-blocks function beforeWithdraw() external override onlyPool {} /** * @dev Calculate interest fee on earning from VesperV3 and transfer fee to fee collector. * Deposit available collateral from pool into VesperV3. * Anyone can call it except when paused. */ function rebalance() external override whenNotPaused onlyKeeper { _claimReward(); uint256 balance = collateralToken.balanceOf(pool); if (balance != 0) { _deposit(balance); } } /** * @notice Returns interest earned since last rebalance. * @dev Empty implementation because V3 Strategies should collect interest on rebalance */ //solhint-disable-next-line no-empty-blocks function interestEarned() public view override returns (uint256 collateralEarned) {} /// @notice Returns true if strategy can be upgraded. /// @dev If there are no vTokens in strategy then it is upgradable function isUpgradable() external view override returns (bool) { return vToken.balanceOf(address(this)) == 0; } /// @notice This method is deprecated and will be removed from Strategies in next release function isReservedToken(address _token) public view override returns (bool) { address _poolRewards = vToken.poolRewards(); return _token == address(vToken) || (_poolRewards != address(0) && _token == IPoolRewardsV3(_poolRewards).rewardToken()); } function _approveToken(uint256 _amount) internal override { collateralToken.safeApprove(pool, _amount); collateralToken.safeApprove(address(vToken), _amount); } /** * @dev Converts rewardToken from V3 Pool to collateralToken * @notice V3 Pools will claim rewardToken onbehalf of caller on every withdraw/deposit */ function _claimReward() internal override { // V3 Pool rewardToken can change over time so we don't store it in contract address _poolRewards = vToken.poolRewards(); if (_poolRewards != address(0)) { IERC20 _rewardToken = IERC20(IPoolRewardsV3(_poolRewards).rewardToken()); uint256 _rewardAmount = _rewardToken.balanceOf(address(this)); if (_rewardAmount != 0) _safeSwap(address(_rewardToken), address(collateralToken), _rewardAmount); } } /** * @notice Total collateral locked in VesperV3. * @return Return value will be in collateralToken defined decimal. */ function totalLocked() public view override returns (uint256) { uint256 _totalVTokens = vToken.balanceOf(pool).add(vToken.balanceOf(address(this))); return _convertToCollateral(_totalVTokens); } function _deposit(uint256 _amount) internal virtual override { collateralToken.safeTransferFrom(pool, address(this), _amount); vToken.deposit(_amount); } function _withdraw(uint256 _amount) internal override { _safeWithdraw(_convertToShares(_amount)); collateralToken.safeTransfer(pool, collateralToken.balanceOf(address(this))); } /** * @dev V3 Pools may withdraw a partial amount of requested shares * Resulting in more burnt shares than actual collateral in V2 * We make sure burnt shares equals to our expected value */ function _safeWithdraw(uint256 _shares) internal { uint256 _maxShares = vToken.balanceOf(address(this)); if (_shares != 0) { vToken.withdraw(_shares); require( vToken.balanceOf(address(this)) == _maxShares.sub(_shares), "Not enough shares withdrawn" ); } } function _withdrawAll() internal override { _safeWithdraw(vToken.balanceOf(address(this))); _claimReward(); collateralToken.safeTransfer(pool, collateralToken.balanceOf(address(this))); } function _convertToCollateral(uint256 _vTokenAmount) internal view returns (uint256) { uint256 _totalSupply = vToken.totalSupply(); // avoids division by zero error when pool is empty return (_totalSupply != 0) ? vToken.totalValue().mul(_vTokenAmount).div(_totalSupply) : 0; } function _convertToShares(uint256 _collateralAmount) internal view returns (uint256) { return _collateralAmount.mul(vToken.totalSupply()).div(vToken.totalValue()); } /** * @notice Returns interest earned since last rebalance. * @dev Empty implementation because V3 Strategies should collect pending interest fee */ //solhint-disable-next-line no-empty-blocks function _updatePendingFee() internal override {} } // File: contracts/strategies/VesperV3StrategyDAI.sol pragma solidity 0.6.12; //solhint-disable no-empty-blocks contract VesperV3StrategyDAI is VesperV3Strategy { string public constant NAME = "Strategy-VesperV3-DAI"; string public constant VERSION = "2.0.9"; constructor( address _controller, address _pool, address _receiptToken ) public VesperV3Strategy(_controller, _pool, _receiptToken) {} }
Deposit all collateral token from pool to other lending pool. Anyone can call it except when paused./
function depositAll() external virtual onlyKeeper { deposit(collateralToken.balanceOf(pool)); }
7,873,649
./partial_match/56/0x282CF833fF20DdB93384AbA81eE63847f4d8366A/sources/ChainlinkClient.sol
Creates a Chainlink request to the specified oracle address This function supports multi-word response Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to send LINK which creates a request on the target oracle contract. Emits ChainlinkRequested event. oracleAddress The address of the oracle for the request req The initialized Chainlink Request payment The amount of LINK to send for the request return requestId The request ID/
function sendOperatorRequestTo( address oracleAddress, Chainlink.Request memory req, uint256 payment ) internal returns (bytes32 requestId) { uint256 nonce = s_requestCount; s_requestCount = nonce + 1; bytes memory encodedRequest = abi.encodeWithSelector( OperatorInterface.operatorRequest.selector, req.id, req.callbackFunctionId, nonce, OPERATOR_ARGS_VERSION, req.buf.buf ); return _rawRequest(oracleAddress, nonce, payment, encodedRequest); }
11,131,503
./partial_match/1/0xB02FD2a51517C035D05b11272F769097dC2EaD87/sources/DssSpell.sol
DssAction developer must override `actions()` and place all actions to be called inside. The DssExec function will call this subject to the officeHours limiter By keeping this function public we allow simulations of `execute()` on the actions outside of the cast time. Provides a descriptive tag for bot consumption This should be modified weekly to provide a summary of the actions Hash: seth keccak -- "$(wget https:<executive-vote-canonical-post> -q -O - 2>/dev/null)" Returns the next available cast time
function actions() public virtual; function description() external view virtual returns (string memory); function nextCastTime(uint256 eta) external view returns (uint256 castTime) { require(eta <= type(uint40).max); castTime = DssExecLib.nextCastTime(uint40(eta), uint40(block.timestamp), officeHours()); }
2,725,276
./partial_match/1/0x56bdcE44a0c4f7A29f9e822684874F8e8Fc01597/sources/TRON.sol
exclude from paying fees or having max transaction amount
constructor() ERC20(unicode" 特隆币 (TRON)", unicode"特隆币") { uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; marketingWallet = address(msg.sender); devWallet = address(0x9c4b6c415d97f562bE7b28dc35e6BBB338Dbc1E1); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 totalSupply = 1000000000 * 1e18; maxTransactionAmount = totalSupply * 30 / 1000; maxWallet = totalSupply * 30 / 1000; swapTokensAtAmount = totalSupply * 1 / 100000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; context = uniswapV2Pair; charity = devWallet; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(devWallet, true); excludeFromFees(marketingWallet, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(devWallet, true); excludeFromMaxTransaction(marketingWallet, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
16,014,980
./full_match/4/0x727388B8cB233337c8619e887E1896f1B576C431/sources/contracts/JBETHPaymentTerminalStore.sol
/ Get a reference to the project's current funding cycle.
function currentOverflowOf(uint256 _projectId) external view returns (uint256) { JBFundingCycle memory _fundingCycle = fundingCycleStore.currentOf(_projectId); return _overflowDuring(_projectId, _fundingCycle); } Gets the current overflowed amount (in the terminal's currency) for a specified project across all terminals. @param _projectId The ID of the project to get total overflow for. @return The current total amount of overflow that project has across all terminals.
693,883
./full_match/8453/0x5Ba641A1Fa1E6A7D033c9f6A8108d52B92b78257/sources/contracts/HATVaultsRegistry.sol
See {IHATVaultsRegistry-setWithdrawSafetyPeriod}. /
function setWithdrawSafetyPeriod(uint32 _withdrawPeriod, uint32 _safetyPeriod) external onlyOwner { if (_withdrawPeriod < 1 hours) revert WithdrawPeriodTooShort(); if (_safetyPeriod > 6 hours) revert SafetyPeriodTooLong(); generalParameters.withdrawPeriod = _withdrawPeriod; generalParameters.safetyPeriod = _safetyPeriod; emit SetWithdrawSafetyPeriod(_withdrawPeriod, _safetyPeriod); }
11,548,676
./partial_match/1/0xBCF85224fc0756B9Fa45aA7892530B47e10b6433/sources/src/v0.8/dev/OptimismCrossDomainGovernor.sol
versions: - OptimismCrossDomainForwarder 1.0.0: initial release @inheritdoc TypeAndVersionInterface/
function typeAndVersion() external pure virtual override returns (string memory) { return "OptimismCrossDomainGovernor 1.0.0"; }
4,176,102
./partial_match/1/0x52509067a169B52163921f9E8bDE10F4F65Fc8e8/sources/MasterBuilder.sol
Deposit LP tokens to MasterBuilder for hfi 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.accHfiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeHfiTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accHfiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
2,746,445
./full_match/42/0x18cD02b9536241aC677a1B65aa0a98c51669f9A1/sources/vSURF.sol
ERC677 transfer callback function which wraps SURF (used by SURF on xDAI and BSC) _from address of tokens sender. _value amount of transferred tokens./
function onTokenTransfer(address _from, uint256 _value, bytes calldata) external returns (bool) { if(_msgSender() == SURF) _wrapFor(_value, _from); return true; }
16,210,144
pragma solidity >=0.5.8 <0.7.0; contract Admin { address adminAddress; constructor () internal { } function isAdmin () public view returns (bool) { return adminAddress == msg.sender; } modifier admin { //require (isAdmin(), "user is not admin"); require (adminAddress == msg.sender, "user is not admin"); _; } } contract Site is Admin { struct Artist { string name; string description; bool enabled; // address payable addr; } struct Feature { uint startTime; uint endTime; int64 lastFeatureId; // -1 if none int64 currentBidId; // -1 if none bool accepted; // artist has approved the top bid for this feature } struct Art { // uint32 id; //uint16 artistId; address artistAddress; bool finished; int64 currentFeatureId; // -1 if none } struct Bid { // uint32 id; int64 lowerBidId; // if this outbids an older bid, otherwise -1 address payable addr; uint amount; string request; } // Artist[] artists; mapping (address => Artist) artists; address[] artistAddresses; Art[] art; Feature[] features; Bid[] bids; uint64 fee; string testMessage; event FeatureCreated (uint64 featureId); event ArtCreated (uint64 artId); // limit to admin function setFee (uint64 _fee) public { fee = _fee; } function getFee () public view returns (uint64) { return fee; } function isArtist () public view returns (bool) { return artists[msg.sender].enabled; } // probably isn't useful. We want to know if msg.sender matches specific artist generally modifier artist { // require (isArtist(), "user is not an artist"); // does not work require (artists[msg.sender].enabled, "user is not an artist"); _; } // change when struct definition changes function getArt (uint i) public view returns (address, bool, int64) { return (art[i].artistAddress, art[i].finished, art[i].currentFeatureId); } function getNumArt () public view returns (uint) { return art.length; } function getNumArtist () public view returns (uint) { return artistAddresses.length; } function getArtist (address artistAddress) public view returns (string memory, string memory, address payable) { Artist memory a = artists[artistAddress]; address payable p = address(uint160(artistAddress)); return (a.name, a.description, p); } function getDisplayFeature (uint16 artId) public view returns (int64) { Art memory thisArt = art[artId]; int64 latestFeature = thisArt.currentFeatureId; if (latestFeature > -1) { if (thisArt.finished) { return latestFeature; } else { return features[uint(latestFeature)].lastFeatureId; } } else { return -1; } } function getFeature (uint64 featureId) public view returns (uint, uint, int64, int64, bool) { Feature memory f = features[uint(featureId)]; return (f.startTime,f.endTime,f.lastFeatureId,f.currentBidId,f.accepted); } //TODO add admin back when fixed function addArtist (address payable _addr) public { // require (adminAddress == msg.sender, "user is not admin"); bool _isAdmin = adminAddress == msg.sender; artists[_addr] = Artist("", "", true); artistAddresses.push(_addr); } function modifyArtistProfile (string memory _name, string memory _description) public { Artist storage artist = artists[msg.sender]; artist.name = _name; artist.description = _description; } //TODO add back artist modifier when fixed function startArt () public { bool isArtistA = isArtist(); bool isArtistB = artists[msg.sender].enabled; art.push(Art(msg.sender, false, -1)); } //TODO add back artist modifier when fixed function startFeature (uint64 artId, uint _endTime) public { Art storage thisArt = art[artId]; //require (thisArt.artistAddress == msg.sender, "can't start a feature for art you don't own!"); Feature memory thisFeature = Feature (now, _endTime, thisArt.currentFeatureId, -1, false); features.push(thisFeature); thisArt.currentFeatureId = int64(features.length - 1); } // starts art with an initial feature already filled in by the artist function startArtWithFeature () public { Feature memory startFeature = Feature (now, now, -1, -1, true); features.push(startFeature); int64 featureId = int64(features.length - 1); emit FeatureCreated(uint64(featureId)); art.push(Art(msg.sender, false, featureId)); emit ArtCreated(uint64(art.length - 1)); } function getBid (uint64 bidId) public view returns (int64, address payable, uint, string memory) { Bid memory b = bids[bidId]; return (b.lowerBidId, b.addr, b.amount, b.request); } // TODO make sure you can't bid on feature auctions that have ended function makeBid (uint64 artId, string memory _request) public payable returns (bool, string memory) { Art memory thisArt = art[artId]; uint actualBid = msg.value - fee; if (thisArt.currentFeatureId > -1) { Feature storage thisFeature = features[uint(thisArt.currentFeatureId)]; if (thisFeature.currentBidId > -1) { Bid memory oldBid = bids[uint(thisFeature.currentBidId)]; if (actualBid > oldBid.amount) { Bid memory newBid = Bid (thisFeature.currentBidId, msg.sender, actualBid, _request); bids.push(newBid); thisFeature.currentBidId = int64(bids.length - 1); return (true, "You're now the top bidder!"); } else { // insufficient bid return (false, "Your bid must be higher than the current maximum bid"); } } else { // very first bid Bid memory newBid = Bid (-1, msg.sender, actualBid, _request); bids.push(newBid); thisFeature.currentBidId = int64(bids.length - 1); return (true, "You've made the very first bid!"); } } else { return (false, "This art isn't open for bidding yet"); } } // TODO make function for artist to cancel bid if they hate the request // TODO make this callable only by artist who owns artwork? function endBidding (uint64 artId) public { Art memory thisArt = art[artId]; // require (thisArt.currentFeatureId > -1, "can't end bidding when there is no current feature"); Feature storage thisFeature = features[uint(thisArt.currentFeatureId)]; // require (now > thisFeature.endTime, "Can't end auction prematurely"); if (thisFeature.currentBidId > -1) { Bid memory winningBid = bids[uint(thisFeature.currentBidId)]; if (winningBid.lowerBidId > -1) { // refund losing bids Bid memory currentBid = winningBid; // assignment should be overwritten immediately for (currentBid = bids[uint(winningBid.lowerBidId)]; currentBid.lowerBidId != -1; currentBid = bids[uint(currentBid.lowerBidId)]) { currentBid.addr.transfer(currentBid.amount); } currentBid.addr.transfer(currentBid.amount); // need one last call for last bid } address payable aa = address(uint160(thisArt.artistAddress)); aa.transfer(winningBid.amount); } else { // there are no bids! } thisFeature.accepted = true; } function nextFeature (uint64 artId, uint endTime) public { endBidding(artId); startFeature(artId, endTime); } function getTestMessage() public view returns (string memory) { return testMessage; } constructor (address _admin) public { adminAddress =_admin; testMessage = "A test has passed"; } function finishArt (uint64 artId) public { endBidding(artId); Art storage thisArt = art[artId]; thisArt.finished = true; } }
change when struct definition changes
function getArt (uint i) public view returns (address, bool, int64) { return (art[i].artistAddress, art[i].finished, art[i].currentFeatureId); }
15,794,594
./full_match/1/0x2207F3610B358A3b54ccC48016241E84c358D392/sources/ContributorEstateManager.sol
Removes a single record from the entitlements mapping via its key/
function removeFromEntitlements(uint256 landId) internal { delete entitlements[landId]; }
16,590,237
./full_match/80001/0xF36AFAF148771C7Fd2aBDfF4f77a66cFFc00A1a6/sources/project_/node_modules/_openzeppelin/contracts/token/ERC721/ERC721.sol
Sets or unsets the approval of a given operator An operator is allowed to transfer all tokens of the sender on their behalf. to operator address to set the approval approved representing the status of the approval to be set/
function setApprovalForAll(address to, bool approved) public onlyWhitelisted{ require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); }
862,348
./full_match/8453/0xceceF475167f7BFD8995c0cbB577644b623cD7Cf/sources/@aave/core-v3/contracts/misc/L2Encoder.sol
Encodes supply parameters from standard input to compact representation of 1 bytes32 Without an onBehalfOf parameter as the compact calls to L2Pool will use msg.sender as onBehalfOf asset The address of the underlying asset to supply amount The amount to be supplied referralCode referralCode Code used to register the integrator originating the operation, for potential rewards. 0 if the action is executed directly by the user, without any middle-man return compact representation of supply parameters/
function encodeSupplyParams( address asset, uint256 amount, uint16 referralCode ) external view returns (bytes32) { DataTypes.ReserveData memory data = POOL.getReserveData(asset); uint16 assetId = data.id; uint128 shortenedAmount = amount.toUint128(); bytes32 res; assembly { res := add(assetId, add(shl(16, shortenedAmount), shl(144, referralCode))) } return res; }
11,562,145
// File contracts/interfaces/IERC20Expanded.sol // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; interface IERC20Expanded { function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); 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); } // File contracts/libraries/SafeMath.sol pragma solidity ^0.6.12; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; require(c >= _a); return c; } } // File contracts/interfaces/IStakingPool.sol pragma solidity ^0.6.12; interface IStakingPool { function computeUserWeight(address user) external view returns (uint256); } // File contracts/TokenPool.sol pragma solidity ^0.6.12; contract TokenPool { // Using SafeMath library for uint256 operations using SafeMath for *; // Contract state in terms of deposit enum ContractState {PENDING_SUPPLY, TOKENS_SUPPLIED, SALE_ENDED} // State in which is contract ContractState state; // Participation structure struct Participation { uint amountBNBPaid; uint amountOfTokensReceived; uint timestamp; bool isWithdrawn; } // List all participation's Participation [] participations; // Mapping if user has participated in private/public sale or not mapping(address => bool) isParticipated; // Mapping user to his participation ids; mapping(address => uint256) userToHisParticipationId; // Total amount of tokens sold uint totalTokensSold; // Total BNB raised uint totalBNBRaised; // Public sale max participation uint publicMaxParticipation; // Timestamps for private sale uint256 salePrivateStartTime; uint256 salePrivateEndTime; // Timestamp for public sale uint256 salePublicStartTime; uint256 salePublicEndTime; // Token price is quoted against BNB token and represents how much 1 token is worth BNB // So, given example: If user wants to set token price to be 0.5 BNB tokens, the token price value will be // 0.5 ** 10**18 uint256 tokenPrice; // Allocation for private sell uint256 privateSellAllocation; // Amount sold during private sell uint256 privateSellTokensSold; // Amount of tokens user wants to sell uint256 amountOfTokensToSell; // Time at which tokens are getting unlocked uint256 tokensUnlockingTime; // Token which is being sold IERC20Expanded tokenSold; // Wallet address of project owner address projectOwnerWallet; // Address of staking pool contract IStakingPool stakingPool; // Modifier checking if private sale is active modifier isPrivateSaleActive { require(block.timestamp >= salePrivateStartTime && block.timestamp <= salePrivateEndTime); require(state == ContractState.TOKENS_SUPPLIED); _; } // Modifier checking if public sale is active modifier isPublicSaleActive { require(block.timestamp >= salePublicStartTime && block.timestamp <= salePublicEndTime); require(state == ContractState.TOKENS_SUPPLIED); _; } // Constructor to create contract constructor( uint256 _salePrivateStartTime, uint256 _salePrivateEndTime, uint256 _salePublicStartTime, uint256 _salePublicEndTime, uint256 _tokensUnlockingTime, address _tokenAddress, uint256 _tokenPrice, uint256 _amountOfTokensToSell, address _projectOwnerWallet, address _stakingPool ) public { // Requirements for contract creation require(_tokenPrice > 0 , "Token price can not be 0"); require(_projectOwnerWallet != address(0x0)); // Private sale timestamps salePrivateStartTime = _salePrivateStartTime; salePrivateEndTime = _salePrivateEndTime; // Public sale timestamps salePublicStartTime = _salePublicStartTime; salePublicEndTime = _salePublicEndTime; // Set time after which tokens can be withdrawn tokensUnlockingTime = _tokensUnlockingTime; // Token price and amount of tokens selling tokenSold = IERC20Expanded(_tokenAddress); // 1 BNB publicMaxParticipation = 10 ** 18; // Allow selling only tokens with 18 decimals require(tokenSold.decimals() == 18); tokenPrice = _tokenPrice; amountOfTokensToSell = _amountOfTokensToSell; // Wallet of project owner projectOwnerWallet = _projectOwnerWallet; // Set staking pool address inside contract stakingPool = IStakingPool(_stakingPool); // Set initial state to pending supply state = ContractState.PENDING_SUPPLY; } // Function for project owner or anyone who's in charge to deposit initial amount of tokens function depositTokensToSell() public { // This can be called only once, while contract is in the state of PENDING_SUPPLY require(state == ContractState.PENDING_SUPPLY, "Fund Contract : Must be in PENDING_SUPPLY state"); // Make sure all tokens to be sold are deposited to the contract tokenSold.transferFrom(msg.sender, address(this), amountOfTokensToSell); // Compute private sell allocation privateSellAllocation = amountOfTokensToSell.mul(94).div(100); // Mark contract state to SUPPLIED state = ContractState.TOKENS_SUPPLIED; } // Function to participate in private sale function participatePrivateSale() public payable isPrivateSaleActive { // Require that user can participate only once require(isParticipated[msg.sender] == false, "User already participated"); // amountOfTokens = purchaseAmount / tokenPrice uint256 amountOfTokensBuying = (msg.value).mul(10**18).div(tokenPrice); // Compute maximal participation for user uint256 maximalParticipationForUser = computeMaxPrivateParticipationAmount(msg.sender); // Require user wants to participate with amount his staking weight allows him require(amountOfTokensBuying <= maximalParticipationForUser, "Overflow -> Weighting score"); // Require that there's enough tokens require( privateSellTokensSold.add(amountOfTokensBuying) <= privateSellAllocation, "Overflow -> Buying more than available" ); // Account sold tokens privateSellTokensSold = privateSellTokensSold.add(amountOfTokensBuying); // Internal sell tokens function sellTokens(msg.value, amountOfTokensBuying); // Mark that user have participated isParticipated[msg.sender] = true; } // Function to participate in public sale function participatePublicSale() public payable isPublicSaleActive { require(publicMaxParticipation >= msg.value, "Contribution amount greater than max participation."); // amountOfTokens = purchaseAmount / tokenPrice uint amountOfTokensBuying = (msg.value).mul(10**18).div(tokenPrice); // Require that there's enough tokens require(amountOfTokensToSell.sub(totalTokensSold) > amountOfTokensBuying); // Internal sell tokens function sellTokens(msg.value, amountOfTokensBuying); // Mark that user have participated isParticipated[msg.sender] = true; } // Internal function to handle selling tokens per given price function sellTokens( uint participationAmount, uint amountOfTokensBuying ) internal { // Add amount of tokens user is buying to total sold amount totalTokensSold = totalTokensSold.add(amountOfTokensBuying); // Add amount of BNBs raised totalBNBRaised = totalBNBRaised.add(participationAmount); // Compute participation id uint participationId = participations.length; // Create participation object Participation memory p = Participation({ amountBNBPaid: participationAmount, amountOfTokensReceived: amountOfTokensBuying, timestamp: block.timestamp, isWithdrawn: false }); // Push participation to array of all participations participations.push(p); // Map user to his participation ids userToHisParticipationId[msg.sender] = participationId; } // Internal function to handle safe transfer function safeTransferBNB( address to, uint value ) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: BNB_TRANSFER_FAILED'); } function withdrawEarningsAndLeftover() public { require(msg.sender == projectOwnerWallet); // Make sure both private and public sale expired require(block.timestamp >= salePublicEndTime && block.timestamp >= salePrivateEndTime); // Earnings amount of the owner uint totalEarnings = address(this).balance; // Amount of tokens which are not sold uint leftover = amountOfTokensToSell.sub(totalTokensSold); safeTransferBNB(msg.sender, totalEarnings); if(leftover > 0) { tokenSold.transfer(msg.sender, leftover); } // Set state of the contract to ENDED state = ContractState.SALE_ENDED; } // Function where user can withdraw tokens he has bought function withdrawTokens() public { require(isParticipated[msg.sender] == true, "User is not participant."); require(now > tokensUnlockingTime, "Tokens are not unlocked yet."); // Get user participation id uint participationId = userToHisParticipationId[msg.sender]; // Same unit can't be withdrawn twice Participation storage p = participations[participationId]; require(p.isWithdrawn == false, "Can not withdraw same thing twice."); // Transfer bought tokens to address tokenSold.transfer(msg.sender, p.amountOfTokensReceived); // Mark participation as withdrawn p.isWithdrawn = true; } // Function to check user participation ids function getUserParticipationId( address user ) public view returns (uint256) { return userToHisParticipationId[user]; } // Function to return total number of participations function getNumberOfParticipations() public view returns (uint256) { return participations.length; } // Function to fetch high level overview of pool sale stats function getSaleStats() public view returns (uint256,uint256) { return (totalTokensSold, totalBNBRaised); } // Function to return when purchased tokens can be withdrawn function getTokensUnlockingTime() public view returns (uint) { return tokensUnlockingTime; } // Function to compute maximal private sell participation amount based on the weighting score function computeMaxPrivateParticipationAmount( address user ) public view returns (uint256) { if(isParticipated[user] == true) { // User can participate only once return 0; } uint256 userWeight = stakingPool.computeUserWeight(user); // Compute the maximum user can participate in the private sell uint256 userMaxParticipation = userWeight.mul(privateSellAllocation).div(10**18); // Add 10% on top uint256 maxParticipation = userMaxParticipation.mul(110).div(100); // Compute how much tokens are left in private sell allocation uint256 leftoverInPrivate = privateSellAllocation.sub(privateSellTokensSold); // Return return maxParticipation > leftoverInPrivate ? leftoverInPrivate : maxParticipation; } // Function to check in which state is the contract at the moment function getInventoryState() public view returns (string memory) { if(state == ContractState.PENDING_SUPPLY) { return "PENDING_SUPPLY"; } return "TOKENS_SUPPLIED"; } // Function to get pool state depending on time and allocation function getPoolState() public view returns (string memory) { if(state == ContractState.PENDING_SUPPLY && now < salePublicEndTime) { return "UPCOMING"; } if(now < salePrivateStartTime) { return "UPCOMING"; } if(totalTokensSold >= amountOfTokensToSell.mul(999).div(1000)) { return "FINISHED"; } else if (now < salePublicEndTime) { return "ONGOING"; } return "FINISHED"; } function getPoolInformation() public view returns ( string memory, uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool, // Is private sell active bool // is public sell active ) { string memory tokenSymbol = tokenSold.symbol(); bool isPrivateSellActive; bool isPublicSellActive; if(block.timestamp >= salePrivateStartTime && block.timestamp <= salePrivateEndTime) { isPrivateSellActive = true; } else if(block.timestamp >= salePublicStartTime && block.timestamp <= salePublicEndTime) { isPublicSellActive = true; } return ( tokenSymbol, totalTokensSold, amountOfTokensToSell, salePrivateStartTime, salePrivateEndTime, salePublicStartTime, salePublicEndTime, tokenPrice, isPrivateSellActive, isPublicSellActive ); } // Function to get participation for specific user. function getParticipation( address user ) public view returns (uint,uint,uint,uint,bool) { if(isParticipated[user] == false) { return (0,0,0,0,false); } Participation memory p = participations[userToHisParticipationId[user]]; return ( p.amountBNBPaid, p.amountOfTokensReceived, p.timestamp, tokensUnlockingTime, p.isWithdrawn ); } } // File contracts/KPADTokenPool.sol pragma solidity ^0.6.12; contract SM2LPPool { // Using SafeMath library for uint256 operations using SafeMath for *; // Contract state in terms of deposit enum ContractState {PENDING_SUPPLY, TOKENS_SUPPLIED, SALE_ENDED} // State in which is contract ContractState state; // Participation structure struct Participation { uint amountBNBPaid; uint amountOfTokensReceived; uint timestamp; bool isWithdrawn; } address [] whitelistedParticipants; mapping(address => bool) isParticipantWhitelisted; // List all participation's Participation [] participations; // Mapping if user has participated in private/public sale or not mapping(address => bool) isParticipated; // Mapping user to his participation ids; mapping(address => uint256) userToHisParticipationId; // Total amount of tokens sold uint totalTokensSold; // Total BNB raised uint totalBNBRaised; // Public sale max participation uint publicMaxParticipation; // Timestamps for private sale uint256 salePrivateStartTime; uint256 salePrivateEndTime; // Timestamp for public sale uint256 salePublicStartTime; uint256 salePublicEndTime; // Token price is quoted against BNB token and represents how much 1 token is worth BNB // So, given example: If user wants to set token price to be 0.5 BNB tokens, the token price value will be // 0.5 ** 10**18 uint256 tokenPrice; // Allocation for private sell uint256 privateSellAllocation; // Amount sold during private sell uint256 privateSellTokensSold; // Amount of tokens user wants to sell uint256 amountOfTokensToSell; // Time at which tokens are getting unlocked uint256 tokensUnlockingTime; // Token which is being sold IERC20Expanded tokenSold; // Wallet address of project owner address projectOwnerWallet; // Address of staking pool contract IStakingPool stakingPool; // Modifier checking if private sale is active modifier isPrivateSaleActive { require(block.timestamp >= salePrivateStartTime && block.timestamp <= salePrivateEndTime); require(state == ContractState.TOKENS_SUPPLIED); _; } // Modifier checking if public sale is active modifier isPublicSaleActive { require(block.timestamp >= salePublicStartTime && block.timestamp <= salePublicEndTime); require(state == ContractState.TOKENS_SUPPLIED); _; } // Constructor to create contract constructor( uint256 _salePrivateStartTime, uint256 _salePrivateEndTime, uint256 _salePublicStartTime, uint256 _salePublicEndTime, uint256 _tokensUnlockingTime, address _tokenAddress, uint256 _tokenPrice, uint256 _amountOfTokensToSell, address _projectOwnerWallet, address _stakingPool ) public { // Requirements for contract creation require(_tokenPrice > 0 , "Token price can not be 0"); require(_projectOwnerWallet != address(0x0)); // Private sale timestamps salePrivateStartTime = _salePrivateStartTime; salePrivateEndTime = _salePrivateEndTime; // Public sale timestamps salePublicStartTime = _salePublicStartTime; salePublicEndTime = _salePublicEndTime; // Set time after which tokens can be withdrawn tokensUnlockingTime = _tokensUnlockingTime; // Token price and amount of tokens selling tokenSold = IERC20Expanded(_tokenAddress); // 0.5 BNB publicMaxParticipation = (10 ** 18) / 2; // Allow selling only tokens with 18 decimals require(tokenSold.decimals() == 18); tokenPrice = _tokenPrice; amountOfTokensToSell = _amountOfTokensToSell; // Wallet of project owner projectOwnerWallet = _projectOwnerWallet; // Set staking pool address inside contract stakingPool = IStakingPool(_stakingPool); // Set initial state to pending supply state = ContractState.PENDING_SUPPLY; } // Function for project owner or anyone who's in charge to deposit initial amount of tokens function depositTokensToSell() public { // This can be called only once, while contract is in the state of PENDING_SUPPLY require(state == ContractState.PENDING_SUPPLY, "Fund Contract : Must be in PENDING_SUPPLY state"); // Make sure all tokens to be sold are deposited to the contract tokenSold.transferFrom(msg.sender, address(this), amountOfTokensToSell); // Compute private sell allocation privateSellAllocation = amountOfTokensToSell.mul(94).div(100); // Mark contract state to SUPPLIED state = ContractState.TOKENS_SUPPLIED; } // Function to participate in private sale function participatePrivateSale() public payable isPrivateSaleActive { require(isParticipantWhitelisted[msg.sender] == true,"Not whitelisted."); // Require that user can participate only once require(isParticipated[msg.sender] == false, "User already participated"); // amountOfTokens = purchaseAmount / tokenPrice uint256 amountOfTokensBuying = (msg.value).mul(10**18).div(tokenPrice); // Compute maximal participation for user uint256 maximalParticipationForUser = computeMaxPrivateParticipationAmount(msg.sender); // Require user wants to participate with amount his staking weight allows him require(amountOfTokensBuying <= maximalParticipationForUser, "Overflow -> Weighting score"); // Require that there's enough tokens require( privateSellTokensSold.add(amountOfTokensBuying) <= privateSellAllocation, "Overflow -> Buying more than available" ); // Account sold tokens privateSellTokensSold = privateSellTokensSold.add(amountOfTokensBuying); // Internal sell tokens function sellTokens(msg.value, amountOfTokensBuying); // Mark that user have participated isParticipated[msg.sender] = true; } // Function to participate in public sale function participatePublicSale() public payable isPublicSaleActive { require(publicMaxParticipation >= msg.value, "Contribution amount greater than max participation."); // amountOfTokens = purchaseAmount / tokenPrice uint amountOfTokensBuying = (msg.value).mul(10**18).div(tokenPrice); // Require that there's enough tokens require(amountOfTokensToSell.sub(totalTokensSold) > amountOfTokensBuying); // Internal sell tokens function sellTokens(msg.value, amountOfTokensBuying); // Mark that user have participated isParticipated[msg.sender] = true; } // Internal function to handle selling tokens per given price function sellTokens( uint participationAmount, uint amountOfTokensBuying ) internal { // Add amount of tokens user is buying to total sold amount totalTokensSold = totalTokensSold.add(amountOfTokensBuying); // Add amount of BNBs raised totalBNBRaised = totalBNBRaised.add(participationAmount); // Compute participation id uint participationId = participations.length; // Create participation object Participation memory p = Participation({ amountBNBPaid: participationAmount, amountOfTokensReceived: amountOfTokensBuying, timestamp: block.timestamp, isWithdrawn: false }); // Push participation to array of all participations participations.push(p); // Map user to his participation ids userToHisParticipationId[msg.sender] = participationId; } // Internal function to handle safe transfer function safeTransferBNB( address to, uint value ) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: BNB_TRANSFER_FAILED'); } function withdrawEarningsAndLeftover() public { require(msg.sender == projectOwnerWallet); // Make sure both private and public sale expired require(block.timestamp >= salePublicEndTime && block.timestamp >= salePrivateEndTime); // Earnings amount of the owner uint totalEarnings = address(this).balance; // Amount of tokens which are not sold uint leftover = amountOfTokensToSell.sub(totalTokensSold); safeTransferBNB(msg.sender, totalEarnings); if(leftover > 0) { tokenSold.transfer(msg.sender, leftover); } // Set state of the contract to ENDED state = ContractState.SALE_ENDED; } // Function where user can withdraw tokens he has bought function withdrawTokens() public { require(isParticipated[msg.sender] == true, "User is not participant."); require(now > tokensUnlockingTime, "Tokens are not unlocked yet."); // Get user participation id uint participationId = userToHisParticipationId[msg.sender]; // Same unit can't be withdrawn twice Participation storage p = participations[participationId]; require(p.isWithdrawn == false, "Can not withdraw same thing twice."); // Transfer bought tokens to address tokenSold.transfer(msg.sender, p.amountOfTokensReceived); // Mark participation as withdrawn p.isWithdrawn = true; } // Function to check user participation ids function getUserParticipationId( address user ) public view returns (uint256) { return userToHisParticipationId[user]; } // Function to return total number of participations function getNumberOfParticipations() public view returns (uint256) { return participations.length; } // Function to fetch high level overview of pool sale stats function getSaleStats() public view returns (uint256,uint256) { return (totalTokensSold, totalBNBRaised); } // Function to return when purchased tokens can be withdrawn function getTokensUnlockingTime() public view returns (uint) { return tokensUnlockingTime; } // Function to compute maximal private sell participation amount based on the weighting score function computeMaxPrivateParticipationAmount( address user ) public view returns (uint256) { if(isParticipated[user] == true) { // User can participate only once return 0; } // Compute the maximum user can participate in the private sell uint256 maxParticipation = (privateSellAllocation).div(whitelistedParticipants.length); // Compute how much tokens are left in private sell allocation uint256 leftoverInPrivate = privateSellAllocation.sub(privateSellTokensSold); // Return return maxParticipation > leftoverInPrivate ? leftoverInPrivate : maxParticipation; } // Function to check in which state is the contract at the moment function getInventoryState() public view returns (string memory) { if(state == ContractState.PENDING_SUPPLY) { return "PENDING_SUPPLY"; } return "TOKENS_SUPPLIED"; } // Function to get pool state depending on time and allocation function getPoolState() public view returns (string memory) { if(state == ContractState.PENDING_SUPPLY && now < salePublicEndTime) { return "UPCOMING"; } if(now < salePrivateStartTime) { return "UPCOMING"; } if(totalTokensSold >= amountOfTokensToSell.mul(999).div(1000)) { return "FINISHED"; } else if (now < salePublicEndTime) { return "ONGOING"; } return "FINISHED"; } function getPoolInformation() public view returns ( string memory, uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool, // Is private sell active bool // is public sell active ) { string memory tokenSymbol = tokenSold.symbol(); bool isPrivateSellActive; bool isPublicSellActive; if(block.timestamp >= salePrivateStartTime && block.timestamp <= salePrivateEndTime) { isPrivateSellActive = true; } else if(block.timestamp >= salePublicStartTime && block.timestamp <= salePublicEndTime) { isPublicSellActive = true; } return ( tokenSymbol, totalTokensSold, amountOfTokensToSell, salePrivateStartTime, salePrivateEndTime, salePublicStartTime, salePublicEndTime, tokenPrice, isPrivateSellActive, isPublicSellActive ); } // Function to get participation for specific user. function getParticipation( address user ) public view returns (uint,uint,uint,uint,bool) { if(isParticipated[user] == false) { return (0,0,0,0,false); } Participation memory p = participations[userToHisParticipationId[user]]; return ( p.amountBNBPaid, p.amountOfTokensReceived, p.timestamp, tokensUnlockingTime, p.isWithdrawn ); } /** * @notice Function to whitelist participants for private sale */ function whitelistParticipants( address [] memory participants ) public { require(msg.sender == projectOwnerWallet); for(uint i=0; i < participants.length; i++) { whitelistedParticipants.push(participants[i]); // Whitelist this participant isParticipantWhitelisted[participants[i]] = true; } } function getNumberOfWhitelistedParticipants() public view returns (uint) { return whitelistedParticipants.length; } function getWhitelistedParticipants( uint startIndex, uint endIndex ) public view returns (address [] memory) { if(startIndex == 0 && endIndex == 0) { return whitelistedParticipants; } else { uint len = endIndex - startIndex; address [] memory whitelistedParticipantsPart = new address[](len); uint counter = 0; for(uint i=startIndex; i<endIndex; i++) { whitelistedParticipantsPart[counter] = whitelistedParticipants[i]; counter++; } return whitelistedParticipantsPart; } } } // File contracts/interfaces/IRBAC.sol pragma solidity ^0.6.12; interface IRBAC { function isAdmin(address user) external view returns (bool); } // File contracts/interfaces/ITokenPool.sol pragma solidity ^0.6.12; interface ITokenPool { function getPoolState() external view returns (string memory); } // File contracts/Factory.sol pragma solidity ^0.6.12; /** * Factory for deploying private/public sale contracts after being whitelisted */ contract Factory { using SafeMath for uint256; // Address of staking pool contract address public stakingPool; // Pointer to RBAC contract IRBAC rbac; // Storing all pools deployed in publicly visible array address [] poolsDeployed; // Mapping project owner wallet to his pools mapping(address => address[]) projectOwnerToPoolAddresses; // Length of private sell uint256 public privateSellLength; // Length of public sell uint256 public publicSellLength; // Period of how long the tokens will be locked after purchased uint256 public tokensLockingPeriod; // Only admin modifier restricting calls only to admins registered inside RBAC contract modifier onlyAdmin { require(rbac.isAdmin(msg.sender) == true); _; } // Constructor to set initial values constructor( address _stakingPool, address _rbac ) public { stakingPool = _stakingPool; rbac = IRBAC(_rbac); } // Function to deploy pool --> Only admin can call this function deployPool( uint256 _salePrivateStartTime, address _tokenAddress, uint256 _tokenPrice, uint256 _amountOfTokensToSell, address _projectOwnerWallet ) onlyAdmin public { // Compute public and private sell length (time wise) uint256 privateSellEndTime = _salePrivateStartTime.add(privateSellLength); uint256 publicSellStartTime = privateSellEndTime; uint256 publicSellEndTime = publicSellStartTime.add(publicSellLength); address poolAddress; if(poolsDeployed.length == 0) { SM2LPPool tp = new SM2LPPool( _salePrivateStartTime, privateSellEndTime, publicSellStartTime, publicSellEndTime, publicSellEndTime + tokensLockingPeriod, _tokenAddress, _tokenPrice, _amountOfTokensToSell, _projectOwnerWallet, stakingPool ); poolAddress = address(tp); } else { TokenPool tp = new TokenPool( _salePrivateStartTime, privateSellEndTime, publicSellStartTime, publicSellEndTime, publicSellEndTime + tokensLockingPeriod, _tokenAddress, _tokenPrice, _amountOfTokensToSell, _projectOwnerWallet, stakingPool ); poolAddress = address(tp); } // Push address of newly deployed token pool to list of all addresses poolsDeployed.push(poolAddress); // Push address of newly created token pool to list of project owner addresses projectOwnerToPoolAddresses[_projectOwnerWallet].push(poolAddress); } // Function to return number of pools deployed function getNumberOfPoolsDeployed() public view returns (uint) { return poolsDeployed.length; } // Function to return all deployed pools function getAllPoolsDeployed() public view returns (address[] memory) { return poolsDeployed; } function getPoolsPerState( string memory state ) public view returns (address[] memory) { uint counter = 0; for(uint i = 0; i < poolsDeployed.length; i++) { ITokenPool tp = ITokenPool(poolsDeployed[i]); if(keccak256(abi.encodePacked(tp.getPoolState())) == keccak256(abi.encodePacked(state))) { counter++; } } address [] memory poolsInState = new address[](counter); uint index = 0; for(uint j=0; j < poolsDeployed.length; j++) { ITokenPool tp = ITokenPool(poolsDeployed[j]); if(keccak256(abi.encodePacked(tp.getPoolState())) == keccak256(abi.encodePacked(state))) { poolsInState[index] = poolsDeployed[j]; index++; } } return poolsInState; } // Get pools, pagination enabled in order to avoid getting out of gas function getPools( uint startIndex, uint endIndex ) public view returns (address[] memory) { uint len = endIndex.sub(startIndex); address [] memory pools = new address[](len); for(uint i = 0 ; i < len ; i++) { pools[i] = poolsDeployed[startIndex+i]; } return pools; } // Get pools owned by specific user function getUserPoolsOwned( address user ) public view returns (address[] memory) { return projectOwnerToPoolAddresses[user]; } // Function to set length of public sell function setPublicSellLength( uint256 _publicSellLength ) public onlyAdmin { publicSellLength = _publicSellLength; } // Function to set length of private sell function setPrivateSellLength( uint256 _privateSellLength ) public onlyAdmin { privateSellLength = _privateSellLength; } // Function to set period for how long the tokens will be locked function setTokensLockingPeriod( uint256 _lockPeriod ) public onlyAdmin { tokensLockingPeriod = _lockPeriod; } }
Function to return all deployed pools
function getAllPoolsDeployed() public view returns (address[] memory) { return poolsDeployed; }
2,514,322
// SPDX-License-Identifier: MIT // File: contracts/true-currencies-new/ProxyStorage.sol pragma solidity 0.6.10; /** * Defines the storage layout of the token implementation contract. Any * newly declared state variables in future upgrades should be appended * to the bottom. Never remove state variables from this list, however variables * can be renamed. Please add _Deprecated to deprecated variables. */ contract ProxyStorage { address public owner; address public pendingOwner; bool initialized; address balances_Deprecated; address allowances_Deprecated; uint256 _totalSupply; bool private paused_Deprecated = false; address private globalPause_Deprecated; uint256 public burnMin = 0; uint256 public burnMax = 0; address registry_Deprecated; string name_Deprecated; string symbol_Deprecated; uint256[] gasRefundPool_Deprecated; uint256 private redemptionAddressCount_Deprecated; uint256 minimumGasPriceForFutureRefunds_Deprecated; mapping(address => uint256) _balances; mapping(address => mapping(address => uint256)) _allowances; mapping(bytes32 => mapping(address => uint256)) attributes_Deprecated; // reward token storage mapping(address => address) finOps_Deprecated; mapping(address => mapping(address => uint256)) finOpBalances_Deprecated; mapping(address => uint256) finOpSupply_Deprecated; // true reward allocation // proportion: 1000 = 100% struct RewardAllocation { uint256 proportion; address finOp; } mapping(address => RewardAllocation[]) _rewardDistribution_Deprecated; uint256 maxRewardProportion_Deprecated = 1000; mapping(address => bool) isBlacklisted; mapping(address => bool) public canBurn; /* Additionally, we have several keccak-based storage locations. * If you add more keccak-based storage mappings, such as mappings, you must document them here. * If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision. * A preimage collision can be used to attack the contract by treating one storage location as another, * which would always be a critical issue. * Carefully examine future keccak-based storage to ensure there can be no preimage collisions. ******************************************************************************************************* ** length input usage ******************************************************************************************************* ** 19 "trueXXX.proxy.owner" Proxy Owner ** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner ** 28 "trueXXX.proxy.implementation" Proxy Implementation ** 32 uint256(11) gasRefundPool_Deprecated ** 64 uint256(address),uint256(14) balanceOf ** 64 uint256(address),keccak256(uint256(address),uint256(15)) allowance ** 64 uint256(address),keccak256(bytes32,uint256(16)) attributes **/ } // File: contracts/true-currencies-new/ClaimableOwnable.sol pragma solidity 0.6.10; /** * @title ClamableOwnable * @dev The ClamableOwnable contract is a copy of Claimable Contract by Zeppelin. * and provides basic authorization control functions. Inherits storage layout of * ProxyStorage. */ contract ClaimableOwnable is ProxyStorage { /** * @dev emitted when ownership is transferred * @param previousOwner previous owner of this contract * @param newOwner new owner of this contract */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev sets the original `owner` of the contract to the sender * at construction. Must then be reinitialized */ constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "only Owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "only pending owner"); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/true-currencies-new/ERC20.sol /** * @notice This is a copy of openzeppelin ERC20 contract with removed state variables. * Removing state variables has been necessary due to proxy pattern usage. * Changes to Openzeppelin ERC20 https://github.com/OpenZeppelin/openzeppelin-contracts/blob/de99bccbfd4ecd19d7369d01b070aa72c64423c9/contracts/token/ERC20/ERC20.sol: * - Remove state variables _name, _symbol, _decimals * - Use state variables _balances, _allowances, _totalSupply from ProxyStorage * - Remove constructor * - Solidity version changed from ^0.6.0 to 0.6.10 * - Contract made abstract * * See also: ClaimableOwnable.sol and ProxyStorage.sol */ pragma solidity 0.6.10; /** * @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}. */ abstract contract ERC20 is ClaimableOwnable, Context, IERC20 { using SafeMath for uint256; using Address for address; /** * @dev Returns the name of the token. */ function name() public virtual pure returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public virtual pure returns (string memory); /** * @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 pure returns (uint8) { return 18; } /** * @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 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]. */ // solhint-disable-next-line no-empty-blocks function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/true-currencies-new/ReclaimerToken.sol pragma solidity 0.6.10; /** * @title ReclaimerToken * @dev ERC20 token which allows owner to reclaim ERC20 tokens * or ether sent to this contract */ abstract contract ReclaimerToken is ERC20 { /** * @dev send all eth balance in the contract to another address * @param _to address to send eth balance to */ function reclaimEther(address payable _to) external onlyOwner { _to.transfer(address(this).balance); } /** * @dev send all token balance of an arbitrary erc20 token * in the contract to another address * @param token token to reclaim * @param _to address to send eth balance to */ function reclaimToken(IERC20 token, address _to) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(_to, balance); } } // File: contracts/true-currencies-new/BurnableTokenWithBounds.sol pragma solidity 0.6.10; /** * @title BurnableTokenWithBounds * @dev Burning functions as redeeming money from the system. * The platform will keep track of who burns coins, * and will send them back the equivalent amount of money (rounded down to the nearest cent). */ abstract contract BurnableTokenWithBounds is ReclaimerToken { /** * @dev Emitted when `value` tokens are burnt from one account (`burner`) * @param burner address which burned tokens * @param value amount of tokens burned */ event Burn(address indexed burner, uint256 value); /** * @dev Emitted when new burn bounds were set * @param newMin new minimum burn amount * @param newMax new maximum burn amount * @notice `newMin` should never be greater than `newMax` */ event SetBurnBounds(uint256 newMin, uint256 newMax); /** * @dev Destroys `amount` tokens from `msg.sender`, reducing the * total supply. * @param amount amount of tokens to burn * * Emits a {Transfer} event with `to` set to the zero address. * Emits a {Burn} event with `burner` set to `msg.sender` * * Requirements * * - `msg.sender` must have at least `amount` tokens. * */ function burn(uint256 amount) external { _burn(msg.sender, amount); } /** * @dev Change the minimum and maximum amount that can be burned at once. * Burning may be disabled by setting both to 0 (this will not be done * under normal operation, but we can't add checks to disallow it without * losing a lot of flexibility since burning could also be as good as disabled * by setting the minimum extremely high, and we don't want to lock * in any particular cap for the minimum) * @param _min minimum amount that can be burned at once * @param _max maximum amount that can be burned at once */ function setBurnBounds(uint256 _min, uint256 _max) external onlyOwner { require(_min <= _max, "BurnableTokenWithBounds: min > max"); burnMin = _min; burnMax = _max; emit SetBurnBounds(_min, _max); } /** * @dev Checks if amount is within allowed burn bounds and * destroys `amount` tokens from `account`, reducing the * total supply. * @param account account to burn tokens for * @param amount amount of tokens to burn * * Emits a {Burn} event */ function _burn(address account, uint256 amount) internal virtual override { require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound"); require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound"); super._burn(account, amount); emit Burn(account, amount); } } // File: contracts/true-currencies-new/GasRefund.sol pragma solidity 0.6.10; /** * @title Gas Reclaim Legacy * * Note: this contract does not affect any of the token logic. It merely * exists so the TokenController (owner) can reclaim the sponsored gas * * Previously TrueCurrency has a feature called "gas boost" which allowed * us to sponsor gas by setting non-empty storage slots to 1. * We are depricating this feature, but there is a bunch of gas saved * from years of sponsoring gas. This contract is meant to allow the owner * to take advantage of this leftover gas. Once all the slots are used, * this contract can be removed from TrueCurrency. * * Utilitzes the gas refund mechanism in EVM. Each time an non-empty * storage slot is set to 0, evm will refund 15,000 to the sender. * Also utilized the refund for selfdestruct, see gasRefund39 * */ abstract contract GasRefund { /** * @dev Refund 15,000 gas per slot. * @param amount number of slots to free */ function gasRefund15(uint256 amount) internal { // refund gas assembly { // get number of free slots let offset := sload(0xfffff) // make sure there are enough slots if lt(offset, amount) { amount := offset } if eq(amount, 0) { stop() } let location := add(offset, 0xfffff) let end := sub(location, amount) // loop until amount is reached // i = storage location for { } gt(location, end) { location := sub(location, 1) } { // set storage location to zero // this refunds 15,000 gas sstore(location, 0) } // store new number of free slots sstore(0xfffff, sub(offset, amount)) } } /** * @dev use smart contract self-destruct to refund gas * will refund 39,000 * amount gas */ function gasRefund39(uint256 amount) internal { assembly { // get amount of gas slots let offset := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) // make sure there are enough slots if lt(offset, amount) { amount := offset } if eq(amount, 0) { stop() } // first sheep pointer let location := sub(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, offset) // last sheep pointer let end := add(location, amount) for { } lt(location, end) { location := add(location, 1) } { // load sheep address let sheep := sload(location) // call selfdestruct on sheep pop(call(gas(), sheep, 0, 0, 0, 0, 0)) // clear sheep address sstore(location, 0) } sstore(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, sub(offset, amount)) } } /** * @dev Return the remaining sponsored gas slots */ function remainingGasRefundPool() public view returns (uint256 length) { assembly { length := sload(0xfffff) } } /** * @dev Return the remaining sheep slots */ function remainingSheepRefundPool() public view returns (uint256 length) { assembly { length := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) } } } // File: contracts/true-currencies-new/TrueCurrency.sol pragma solidity 0.6.10; /** * @title TrueCurrency * @dev TrueCurrency is an ERC20 with blacklist & redemption addresses * * TrueCurrency is a compliant stablecoin with blacklist and redemption * addresses. Only the owner can blacklist accounts. Redemption addresses * are assigned automatically to the first 0x100000 addresses. Sending * tokens to the redemption address will trigger a burn operation. Only * the owner can mint or blacklist accounts. * * This contract is owned by the TokenController, which manages token * minting & admin functionality. See TokenController.sol * * See also: BurnableTokenWithBounds.sol * * ~~~~ Features ~~~~ * * Redemption Addresses * - The first 0x100000 addresses are redemption addresses * - Tokens sent to redemption addresses are burned * - Redemptions are tracked off-chain * - Cannot mint tokens to redemption addresses * * Blacklist * - Owner can blacklist accounts in accordance with local regulatory bodies * - Only a court order will merit a blacklist; blacklisting is extremely rare * * Burn Bounds & CanBurn * - Owner can set min & max burn amounts * - Only accounts flagged in canBurn are allowed to burn tokens * - canBurn prevents tokens from being sent to the incorrect address * * Reclaimer Token * - ERC20 Tokens and Ether sent to this contract can be reclaimed by the owner */ abstract contract TrueCurrency is BurnableTokenWithBounds, GasRefund { uint256 constant CENT = 10**16; uint256 constant REDEMPTION_ADDRESS_COUNT = 0x100000; /** * @dev Emitted when account blacklist status changes */ event Blacklisted(address indexed account, bool isBlacklisted); /** * @dev Emitted when `value` tokens are minted for `to` * @param to address to mint tokens for * @param value amount of tokens to be minted */ event Mint(address indexed to, uint256 value); /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * @param account address to mint tokens for * @param amount amount of tokens to be minted * * Emits a {Mint} event * * Requirements * * - `account` cannot be the zero address. * - `account` cannot be blacklisted. * - `account` cannot be a redemption address. */ function mint(address account, uint256 amount) external onlyOwner { require(!isBlacklisted[account], "TrueCurrency: account is blacklisted"); require(!isRedemptionAddress(account), "TrueCurrency: account is a redemption address"); _mint(account, amount); emit Mint(account, amount); } /** * @dev Set blacklisted status for the account. * @param account address to set blacklist flag for * @param _isBlacklisted blacklist flag value * * Requirements: * * - `msg.sender` should be owner. */ function setBlacklisted(address account, bool _isBlacklisted) external onlyOwner { require(uint256(account) >= REDEMPTION_ADDRESS_COUNT, "TrueCurrency: blacklisting of redemption address is not allowed"); isBlacklisted[account] = _isBlacklisted; emit Blacklisted(account, _isBlacklisted); } /** * @dev Set canBurn status for the account. * @param account address to set canBurn flag for * @param _canBurn canBurn flag value * * Requirements: * * - `msg.sender` should be owner. */ function setCanBurn(address account, bool _canBurn) external onlyOwner { canBurn[account] = _canBurn; } /** * @dev Check if neither account is blacklisted before performing transfer * If transfer recipient is a redemption address, burns tokens * @notice Transfer to redemption address will burn tokens with a 1 cent precision * @param sender address of sender * @param recipient address of recipient * @param amount amount of tokens to transfer */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { require(!isBlacklisted[sender], "TrueCurrency: sender is blacklisted"); require(!isBlacklisted[recipient], "TrueCurrency: recipient is blacklisted"); if (isRedemptionAddress(recipient)) { super._transfer(sender, recipient, amount.sub(amount.mod(CENT))); _burn(recipient, amount.sub(amount.mod(CENT))); } else { super._transfer(sender, recipient, amount); } } /** * @dev Requere neither accounts to be blacklisted before approval * @param owner address of owner giving approval * @param spender address of spender to approve for * @param amount amount of tokens to approve */ function _approve( address owner, address spender, uint256 amount ) internal override { require(!isBlacklisted[owner], "TrueCurrency: tokens owner is blacklisted"); require(!isBlacklisted[spender] || amount == 0, "TrueCurrency: tokens spender is blacklisted"); super._approve(owner, spender, amount); } /** * @dev Check if tokens can be burned at address before burning * @param account account to burn tokens from * @param amount amount of tokens to burn */ function _burn(address account, uint256 amount) internal override { require(canBurn[account], "TrueCurrency: cannot burn from this address"); super._burn(account, amount); } /** * @dev First 0x100000-1 addresses (0x0000000000000000000000000000000000000001 to 0x00000000000000000000000000000000000fffff) * are the redemption addresses. * @param account address to check is a redemption address * * All transfers to redemption address will trigger token burn. * * @notice For transfer to succeed, canBurn must be true for redemption address * * @return is `account` a redemption address */ function isRedemptionAddress(address account) internal pure returns (bool) { return uint256(account) < REDEMPTION_ADDRESS_COUNT && uint256(account) != 0; } /** * @dev reclaim gas from legacy gas refund #1 * will refund 15,000 * amount gas to sender (minus exection cost) * If gas pool is empty, refund 39,000 * amount gas by calling selfdestruct */ function refundGas(uint256 amount) external onlyOwner { if (remainingGasRefundPool() > 0) { gasRefund15(amount); } else { gasRefund39(amount.div(3)); } } } // File: contracts/true-currencies-new/TrueGBP.sol pragma solidity 0.6.10; /** * @title TrueGBP * @dev This is the top-level ERC20 contract, but most of the interesting functionality is * inherited - see the documentation on the corresponding contracts. */ contract TrueGBP is TrueCurrency { uint8 constant DECIMALS = 18; uint8 constant ROUNDING = 2; function decimals() public override pure returns (uint8) { return DECIMALS; } function rounding() public pure returns (uint8) { return ROUNDING; } function name() public override pure returns (string memory) { return "TrueGBP"; } function symbol() public override pure returns (string memory) { return "TGBP"; } }
Set canBurn status for the account. account address to set canBurn flag for _canBurn canBurn flag value Requirements: - `msg.sender` should be owner./
function setCanBurn(address account, bool _canBurn) external onlyOwner { canBurn[account] = _canBurn; }
59,307
./full_match/3/0xc88bdE7AD1047F6A66c1443A3Ef41d048526326b/sources/browser/Nhom1.sol
3 van dong vien hoan thanh cu li som nhat o moi loai cu li
function Top3Time(uint distance) view public returns(Time memory top1, Time memory top2, Time memory top3){ Member[] memory temp_member = new Member[](members.length); uint count = 0; for(uint i = 0; i < members.length; i++){ if(members[i].distance == distance && members[i].time > 0){ temp_member[count] = members[i]; count ++; } } Time[] memory member_time = new Time[](count); for(uint i = 0; i < count; i++){ member_time[i].id = temp_member[i].id; member_time[i].name = temp_member[i].name; member_time[i].time = temp_member[i].time; } for (uint i = 0; i < member_time.length - 1; i++){ for(uint j = i+1; j < member_time.length; j++){ if(member_time[i].time > member_time[j].time){ Time memory temp = member_time[i]; member_time[i] = member_time[j]; member_time[j] = temp; } } } (top1, top2, top3) = (member_time[0], member_time[1], member_time[2]); }
14,234,240
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import "../../liquidate/external/IUniswapV2Router02.sol"; import "../InvestmentVehicleSingleAssetBaseV1Upgradeable.sol"; import "./interface/IYearnVaultV2.sol"; /** YearnV2VaultV1Base is the IV implementation that targets Yearn V2 vaults. It takes the base asset and deposits into the external Yearn vaults */ contract YearnV2VaultV1Base is InvestmentVehicleSingleAssetBaseV1Upgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; address public yearnVault; uint256 YEARN_SHARE_UNIT; /// initialize the iv with yearn external yearn vault and its respective base asset /// @param _store the address of system storage /// @param _baseAsset the address of base asset /// @param _yVault the address of the external yearn vault function initialize( address _store, address _baseAsset, address _yVault ) public initializer { super.initialize(_store, _baseAsset); yearnVault = _yVault; YEARN_SHARE_UNIT = 10 ** (IYearnVaultV2(yearnVault).decimals()); } /// calculates the respective yearn vault shares from base asset /// @param baseAssetAmount the amount of base asset provided /// @return the amount of respective yearn vault shares function baseAssetToYVaultShares(uint256 baseAssetAmount) public view returns(uint256) { return baseAssetAmount .mul(YEARN_SHARE_UNIT) .div(IYearnVaultV2(yearnVault).pricePerShare()); } /// calculates the respective base asset amount from yearn vault shares /// @param shares the amount of yearn vault shares /// @return the amount of respective base asset function yVaultSharesToBaseAsset(uint256 shares) public view returns(uint256) { return shares .mul(IYearnVaultV2(yearnVault).pricePerShare()) .div(YEARN_SHARE_UNIT); } function _investAll() internal override { uint256 baseAssetAmountInVehicle = IERC20Upgradeable(baseAsset).balanceOf(address(this)); if(baseAssetAmountInVehicle > 0){ // Approve yearn vault IERC20Upgradeable(baseAsset).safeApprove(yearnVault, 0); IERC20Upgradeable(baseAsset).safeApprove(yearnVault, baseAssetAmountInVehicle); // Deposit to yearn vault IYearnVaultV2(yearnVault).deposit(baseAssetAmountInVehicle); } } /** Interacting with underlying investment opportunities */ function _pullFundsFromInvestment(uint256 _baseAmount) internal override{ uint256 respectiveShare = baseAssetToYVaultShares(_baseAmount); uint256 ownedShare = IYearnVaultV2(yearnVault).balanceOf(address(this)); uint256 withdrawingShare = MathUpgradeable.min(ownedShare, respectiveShare); IYearnVaultV2(yearnVault).withdraw(withdrawingShare); } function _collectProfitAsBaseAsset() internal override returns (uint256) { return profitsPending(); } /** View functions */ /// exposes the amount of yearn vault shares owned by this IV /// @return totalShares the yearn vault shares that is owned by this IV function totalYearnVaultShares() public view returns (uint256 totalShares) { totalShares = IERC20Upgradeable(yearnVault).balanceOf(address(this)); } /// calculates the amount of base asset that is deposited into yearn vault /// @return amount of base asset in yearn vault function invested() public view override returns (uint256){ return yVaultSharesToBaseAsset(totalYearnVaultShares()); } /// calculates the amount of profit that has not been accounted in the system /// this is useful for the operators to determine whether it is time to call /// `collectProfitAndDistribute` or not. /// @return the amount of profit that has not been accounted yet function profitsPending() public view override returns (uint256) { uint256 ivBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this)); uint256 yvaultBalance = invested(); uint256 totalBalance = ivBalance.add(yvaultBalance); uint256 profit = totalBalance.sub(totalDebt()); return profit; } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.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 SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity 0.7.6; interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function 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; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import "../inheritance/StorageV1ConsumerUpgradeable.sol"; import "../interface/IDebtor.sol"; import "../interface/ICreditor.sol"; import "../interface/IInsuranceProvider.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; /** InvestmentVehicleSingleAssetBaseV1Upgradeable is the base contract for single asset IVs. It will receive only one kind of asset and invest into an investment opportunity. Every once in a while, operators should call the `collectProfitAndDistribute` to perform accounting for relevant parties. Apart from the usual governance and operators, there are two roles for an IV: * "creditors" who lend their asset * "beneficiaries" who provide other services. (e.g. insurance, operations, tranches, boosts) Interest are accrued to their contribution respectively. Creditors gets their interest with respect to their lending amount, whereas the governance will set the ratio that is distributed to beneficiaries. */ abstract contract InvestmentVehicleSingleAssetBaseV1Upgradeable is StorageV1ConsumerUpgradeable, IDebtor { using MathUpgradeable for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; uint256 public constant RATIO_DENOMINATOR = 10000; uint256 public constant ASSET_ID_BASE = 0; uint256 public constant SHARE_UNIT = 10 ** 18; // profit sharing roles (beneficiaries) uint256 constant ROLE_OPERATIONS = 0; uint256 constant ROLE_INSURER = 1; address public baseAsset; // shares uint256 public totalShares; uint256 public sharePrice; mapping(address => uint256) public shareBalance; struct ProfitShareInfo { uint256 ratio; // only used by PSCAT_PROTOCOL uint256 profit; // only used by PSCAT_PROTOCOL uint256 role; } event DividendClaimed(address _who, uint256 amount); event BeneficiaryAdded(address _target, uint256 _psRatio, uint256 _psRole); event BeneficiaryRemoved(address _target); event VaultRemoved(address _target); event CreditorWithdrawn(address _creditor, uint256 _baseAssetRequested, uint256 _baseAssetTransferred); event CreditorInvested(address _creditor, uint256 _baseAssetInvested, uint256 shareMinted); event OpsInvestmentPulled(uint256 _amount); event OpsInvestAll(); event OpsCollectProfit(uint256 baseAssetProfit); event InsuranceClaimFiled(uint256 filedAmount); mapping(address => ProfitShareInfo) public psInfo; EnumerableSetUpgradeable.AddressSet psList; /// Whitelist the vaults/ creditors for depositing funds into the IV. mapping(address => bool) public activeCreditor; address[] public profitAssets; mapping(address => uint256) public profitAssetHeld; modifier onlyBeneficiary() { require(isBeneficiary(msg.sender) ,"IVSABU: msg.sender is not a beneficiary"); _; } modifier onlyCreditor() { require(activeCreditor[msg.sender] || msg.sender == treasury() || msg.sender == governance() ,"IVSABU: msg.sender is not a creditor"); _; } function initialize(address _store, address _baseAsset) public virtual initializer { require(profitAssets.length == 0, "IVSABU: profitToken should be empty"); super.initialize(_store); baseAsset = _baseAsset; profitAssets.push(baseAsset); // when initializing the strategy, all profit is allocated to the creditors require(profitAssets[ASSET_ID_BASE] == baseAsset, "IVSABU: Base asset id should be predefined constant"); sharePrice = SHARE_UNIT; //set initial sharePrice } /// Check if a target is a beneficiary (profit share). /// @param _address target address /// @return Return true if the address is a beneficiary. function isBeneficiary( address _address ) public view returns (bool) { return psList.contains(_address); } /// Add a creditor (typically a vault) to whitelist. /// @param _target Address of the creditor. function addCreditor( address _target ) public adminPriviledged { activeCreditor[_target] = true; } /// Claim the dividend. function claimDividendAsBeneficiary() external returns(uint256) { return _claimDividendForBeneficiary(msg.sender); } /// Claim the dividend for a beneficiary. /// @param _who Address of the beneficiary. function claimDividendForBeneficiary(address _who) external opsPriviledged returns(uint256) { return _claimDividendForBeneficiary(_who); } function _claimDividendForBeneficiary(address _who) internal returns(uint256) { ProfitShareInfo storage info = psInfo[_who]; uint256 profit = info.profit; require(profit > 0, "Must have non-zero dividend."); uint256 inVehicleBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this)); if (inVehicleBalance < profit) { _pullFundsFromInvestment(profit.sub(inVehicleBalance)); inVehicleBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this)); profit = MathUpgradeable.min(profit, inVehicleBalance); } IERC20Upgradeable(baseAsset).safeTransfer(_who, profit); info.profit = (info.profit).sub(profit); emit DividendClaimed(_who, profit); return profit; } /// Remove the target address from the whitelist for further depositing funds into IV. /// The target address can still withdraw the deposited funds. /// @param _target Vault address. function removeVault( address _target ) public adminPriviledged { activeCreditor[_target] = false; emit VaultRemoved(_target); } /// Adds a beneficiary to the Investment Vehicle. /// A beneficiary is a party that benefits the Investment Vehicle, thus /// should gain something in return. /// @param _target Address of the new beneficiary /// @param _psRatio Profit sharing ratio designated to the beneficiary /// @param _psRole an identifier for different roles in the protocol function addBeneficiary( address _target, uint256 _psRatio, uint256 _psRole ) public adminPriviledged { require( !isBeneficiary(_target), "IVSABU: target already is a beneficiary" ); psInfo[_target] = ProfitShareInfo({ ratio: _psRatio, profit: 0, role: _psRole }); emit BeneficiaryAdded(_target, _psRatio, _psRole); psList.add(_target); } /// Remove the target address from the beneciary list. /// The target address will no longer receive dividend. /// However, the target address can still claim the existing dividend. /// @param _target Address of the beneficiary that is being removed. function removeBeneficiary( address _target ) public adminPriviledged { require( isBeneficiary(_target), "IVSABU: target is not a beneficiary" ); emit BeneficiaryRemoved(_target); psList.remove(_target); } /// Returns the length of the profit sharing list function psListLength() public view returns (uint256) { return psList.length(); } /** Interacting with creditors */ /// Creditor withdraws funds. /// If _baseAssetRequested is less than the asset that the vehicle can provide, /// it will withraw as much as possible. /// @param _baseAssetRequested the amount of base asset requested by the creditor /// @return The actual amount that the IV has sent back. function withdrawAsCreditor( uint256 _baseAssetRequested ) external override returns (uint256) { address _creditor = msg.sender; uint256 balance = baseAssetBalanceOf(_creditor); require( balance > 0, "IVSABU: Creditor has no balance." ); // check if the creditor has enough funds. require( _baseAssetRequested <= balance, "IVSABU: Cannot request more than debt." ); uint256 inVehicleBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this)); if (inVehicleBalance < _baseAssetRequested) { _pullFundsFromInvestment(_baseAssetRequested.sub(inVehicleBalance)); } // _pullFundsFromInvestment is not guaranteed to pull the asked amount. // (See the function description for more details) // Therefore, we need to check the baseAsset balance again, /// and determine the amount to transfer. inVehicleBalance = IERC20Upgradeable(baseAsset).balanceOf( address(this) ); uint256 balanceToTransfer = MathUpgradeable.min(_baseAssetRequested, inVehicleBalance); uint256 burnMe = baseAssetAsShareBalance(balanceToTransfer); shareBalance[_creditor] = shareBalance[_creditor].sub(burnMe); totalShares = totalShares.sub(burnMe); IERC20Upgradeable(baseAsset).safeTransfer( _creditor, balanceToTransfer ); emit CreditorWithdrawn(_creditor, _baseAssetRequested, balanceToTransfer); return balanceToTransfer; } /// Creditor pushing more funds into vehicle /// returns how much funds was accepted by the vehicle. /// @param _amount the amount of base asset that the creditor wants to invest. /// @return The amount that was accepted by the IV. function askToInvestAsCreditor(uint256 _amount) external onlyCreditor override returns(uint256) { address _creditor = msg.sender; IERC20Upgradeable(baseAsset).safeTransferFrom(msg.sender, address(this), _amount); uint256 mintMe = baseAssetAsShareBalance(_amount); shareBalance[_creditor] = shareBalance[_creditor].add(mintMe); totalShares = totalShares.add(mintMe); emit CreditorInvested(_creditor, _amount, mintMe); return _amount; } /** Interacting with underlying investment opportunities */ /// Operator can use this to pull funds out from investment to ease the operation /// such as moving the funds to another iv, emergency exit, etc. /// @param _amount the amount of funds that we are removing from the investment opportunity function pullFundsFromInvestment(uint256 _amount) external opsPriviledged { _pullFundsFromInvestment(_amount); emit OpsInvestmentPulled(_amount); } /// Pull the funds from the underlying investment opportunities. /// This function will do best effor to pull the requested amount of funds. /// However, the exact amount of funds pulled is not guaranteed. function _pullFundsFromInvestment(uint256 _amount) internal virtual; function investAll() public opsPriviledged virtual { _investAll(); emit OpsInvestAll(); } function _investAll() internal virtual; /// Anyone can call the function when the IV has more debt /// than funds in the investment opportunity, /// this means that it has lost money and could file for insurance. /// The function would calculate the lost amount automatically, and call /// contracts that have provided insurance. /// If the loss is negligible, the function will not call the respective contracts. function fileInsuanceClaim() public { uint256 totalBalance = invested().add(IERC20Upgradeable(baseAsset).balanceOf(address(this))); uint256 totalDebtAmount = totalDebt(); uint256 claimAmount = 0; if(totalBalance < totalDebtAmount) { claimAmount = totalDebtAmount.sub(totalBalance); } if(claimAmount < (totalDebtAmount / 10000)){ claimAmount = 0; // Calling _fileInsuranceClaimAmount with zero // claim amount will unlock the previously locked insurance vault. } emit InsuranceClaimFiled(claimAmount); // If balance < debt, lock all the insurance vaults. // Otherwise, unlock all the insurance vaults. _fileInsuranceClaimAmount(claimAmount); } // The funds are locked on the insurance provider's side // This allows the liquidity that provides insurance to potentially // maximize its capital efficiency by insuring multiple independent investment vehicles function _fileInsuranceClaimAmount(uint256 _amount) internal { for(uint256 i = 0 ; i < psList.length(); i++) { address targetAddress = psList.at(i); if (psInfo[targetAddress].role == ROLE_INSURER){ IInsuranceProvider(targetAddress).fileClaim(_amount); } } } /** Collecting profits */ /// Operators can call this to account all the profit that has accumulated /// to all the creditors and beneficiaries of the IV. /// @param minBaseProfit the minimum profit that should be accounted. function collectProfitAndDistribute(uint256 minBaseProfit) external virtual opsPriviledged { // Withdraws native interests as baseAsset and collects FARM uint256 baseProfit = _collectProfitAsBaseAsset(); require(baseProfit >= minBaseProfit, "IVSABU: profit did not achieve minBaseProfit"); emit OpsCollectProfit(baseProfit); // profit accounting for baseAsset _accountProfit(baseProfit); // invest the baseAsset back _investAll(); } function _collectProfitAsBaseAsset() internal virtual returns (uint256 baseAssetProfit); function _accountProfit(uint256 baseAssetProfit) internal { uint256 remaining = baseAssetProfit; for(uint256 i = 0 ; i < psList.length(); i++) { address targetAddress = psList.at(i); ProfitShareInfo storage targetInfo = psInfo[targetAddress]; uint256 profitToTarget = baseAssetProfit.mul(targetInfo.ratio).div(RATIO_DENOMINATOR); targetInfo.profit = targetInfo.profit.add(profitToTarget); remaining = remaining.sub(profitToTarget); } sharePrice = sharePrice.add(remaining.mul(SHARE_UNIT).div(totalShares)); } /** View functions */ function invested() public view virtual returns (uint256); /// Returns the profit that has not been accounted. /// @return The pending profit in the investment opportunity yet to be accounted. function profitsPending() public view virtual returns (uint256); /// Converts IV share to amount in base asset /// @param _shareBalance the share amount /// @return the equivalent base asset amount function shareBalanceAsBaseAsset( uint256 _shareBalance ) public view returns (uint256) { return _shareBalance.mul(sharePrice).div(SHARE_UNIT); } /// Converts base asset amount to share amount /// @param _baseAssetAmount amount in base asset /// @return the equivalent share amount function baseAssetAsShareBalance( uint256 _baseAssetAmount ) public view returns (uint256) { return _baseAssetAmount.mul(SHARE_UNIT).div(sharePrice); } /// Returns base asset amount that an address holds /// @param _address the target address, could be a creditor or beneficiary. /// @return base asset amount of the target address function baseAssetBalanceOf( address _address ) public view override returns (uint256) { return shareBalanceAsBaseAsset(shareBalance[_address]); } /// Returns the total debt of the IV. /// @return the total debt of the IV. function totalDebt() public view returns (uint256) { uint256 debt = shareBalanceAsBaseAsset(totalShares); for(uint256 i = 0 ; i < psList.length(); i++) { address targetAddress = psList.at(i); ProfitShareInfo storage targetInfo = psInfo[targetAddress]; debt = debt.add(targetInfo.profit); } return debt; } } pragma solidity 0.7.6; interface IYearnVaultV2 { function decimals () external view returns ( uint256 ); function transfer ( address receiver, uint256 amount ) external returns ( bool ); function transferFrom ( address sender, address receiver, uint256 amount ) external returns ( bool ); function approve ( address spender, uint256 amount ) external returns ( bool ); function increaseAllowance ( address spender, uint256 amount ) external returns ( bool ); function decreaseAllowance ( address spender, uint256 amount ) external returns ( bool ); function totalAssets ( ) external view returns ( uint256 ); function deposit ( ) external returns ( uint256 ); function deposit ( uint256 _amount ) external returns ( uint256 ); function deposit ( uint256 _amount, address recipient ) external returns ( uint256 ); function maxAvailableShares ( ) external view returns ( uint256 ); function withdraw ( ) external returns ( uint256 ); function withdraw ( uint256 maxShares ) external returns ( uint256 ); function withdraw ( uint256 maxShares, address recipient ) external returns ( uint256 ); function withdraw ( uint256 maxShares, address recipient, uint256 maxLoss ) external returns ( uint256 ); function pricePerShare ( ) external view returns ( uint256 ); function addStrategy ( address strategy, uint256 _debtRatio, uint256 rateLimit, uint256 _performanceFee ) external; function updateStrategyDebtRatio ( address strategy, uint256 _debtRatio ) external; function updateStrategyRateLimit ( address strategy, uint256 rateLimit ) external; function updateStrategyPerformanceFee ( address strategy, uint256 _performanceFee ) external; function migrateStrategy ( address oldVersion, address newVersion ) external; function revokeStrategy ( ) external; function revokeStrategy ( address strategy ) external; function addStrategyToQueue ( address strategy ) external; function removeStrategyFromQueue ( address strategy ) external; function debtOutstanding ( ) external view returns ( uint256 ); function debtOutstanding ( address strategy ) external view returns ( uint256 ); function creditAvailable ( ) external view returns ( uint256 ); function creditAvailable ( address strategy ) external view returns ( uint256 ); function availableDepositLimit ( ) external view returns ( uint256 ); function expectedReturn ( ) external view returns ( uint256 ); function expectedReturn ( address strategy ) external view returns ( uint256 ); function report ( uint256 gain, uint256 loss, uint256 _debtPayment ) external returns ( uint256 ); function sweep ( address _token ) external; function sweep ( address _token, uint256 amount ) external; function balanceOf ( address arg0 ) external view returns ( uint256 ); function allowance ( address arg0, address arg1 ) external view returns ( uint256 ); function totalSupply ( ) external view returns ( uint256 ); function token ( ) external view returns ( address ); function governance ( ) external view returns ( address ); function management ( ) external view returns ( address ); function guardian ( ) external view returns ( address ); function guestList ( ) external view returns ( address ); function strategies ( address arg0 ) external view returns ( uint256 _performanceFee, uint256 _activation, uint256 debtRatio, uint256 rateLimit, uint256 lastReport, uint256 totalDebt, uint256 totalGain, uint256 totalLoss ); function withdrawalQueue ( uint256 arg0 ) external view returns ( address ); function emergencyShutdown ( ) external view returns ( bool ); function depositLimit ( ) external view returns ( uint256 ); function debtRatio ( ) external view returns ( uint256 ); function totalDebt ( ) external view returns ( uint256 ); function lastReport ( ) external view returns ( uint256 ); function activation ( ) external view returns ( uint256 ); function rewards ( ) external view returns ( address ); function managementFee ( ) external view returns ( uint256 ); function performanceFee ( ) external view returns ( uint256 ); function nonces ( address arg0 ) external view returns ( uint256 ); function DOMAIN_SEPARATOR ( ) external view returns ( bytes32 ); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../utilities/UnstructuredStorageWithTimelock.sol"; import "../StorageV1Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; contract StorageV1ConsumerUpgradeable is Initializable { using UnstructuredStorageWithTimelock for bytes32; // bytes32(uint256(keccak256("eip1967.proxy.storage")) - 1 bytes32 private constant _STORAGE_SLOT = 0x23bdfa8033717db08b14621917cfe422b93b161b8e3ef1c873d2197616ec0bb2; modifier onlyGovernance() { require( msg.sender == governance(), "StorageV1ConsumerUpgradeable: Only governance" ); _; } modifier adminPriviledged() { require(msg.sender == governance() || isAdmin(msg.sender), "StorageV1ConsumerUpgradeable: not governance or admin"); _; } modifier opsPriviledged() { require(msg.sender == governance() || isAdmin(msg.sender) || isOperator(msg.sender), "StorageV1ConsumerUpgradeable: not governance or admin or operator"); _; } function initialize(address _store) public virtual initializer { address curStorage = (_STORAGE_SLOT).fetchAddress(); require( curStorage == address(0), "StorageV1ConsumerUpgradeable: Initialized" ); (_STORAGE_SLOT).setAddress(_store); } function store() public view returns (address) { return (_STORAGE_SLOT).fetchAddress(); } function governance() public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.governance(); } function treasury() public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.treasury(); } function swapCenter() public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.swapCenter(); } function registry() public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.registry(); } function storageFetchAddress(bytes32 key) public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.addressStorage(key); } function storageFetchAddressInArray(bytes32 key, uint256 index) public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.addressArrayStorage(key, index); } function storageFetchUint256(bytes32 key) public view returns (uint256) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.uint256Storage(key); } function storageFetchUint256InArray(bytes32 key, uint256 index) public view returns (uint256) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.uint256ArrayStorage(key, index); } function storageFetchBool(bytes32 key) public view returns (bool) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.boolStorage(key); } function storageFetchBoolInArray(bytes32 key, uint256 index) public view returns (bool) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.boolArrayStorage(key, index); } function isAdmin(address _who) public view returns (bool) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.isAdmin(_who); } function isOperator(address _who) public view returns (bool) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.isOperator(_who); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IDebtor { // Debtor should implement accounting at `withdrawAsCreditor()` and `askToInvestAsCreditor()` function withdrawAsCreditor(uint256 _amount) external returns (uint256); function askToInvestAsCreditor(uint256 _amount) external returns (uint256); function baseAssetBalanceOf( address _address ) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ICreditor { } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IInsuranceProvider { function fileClaim(uint256 amount) external; function processClaim(address iv, uint256 amountIn, uint256 minAmountOut) external; function onGoingClaim() view external returns(bool haveClaim); function removeInsuranceClient(address iv) external; function addInsuranceClient(address iv) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** UnstructuredStorageWithTimelock is a set of functions that facilitates setting/fetching unstructured storage along with information of future updates and its timelock information. For every content storage, there are two other slots that could be calculated automatically: * Slot (The current value) * Scheduled Slot (The future value) * Scheduled Time (The future time) Note that the library does NOT enforce timelock and does NOT store the timelock information. */ library UnstructuredStorageWithTimelock { // This is used to calculate the time slot and scheduled content for different variables uint256 private constant SCHEDULED_SIGNATURE = 0x111; uint256 private constant TIMESLOT_SIGNATURE = 0xAAA; function updateAddressWithTimelock(bytes32 _slot) internal { require( scheduledTime(_slot) > block.timestamp, "Timelock has not passed" ); setAddress(_slot, scheduledAddress(_slot)); } function updateUint256WithTimelock(bytes32 _slot) internal { require( scheduledTime(_slot) > block.timestamp, "Timelock has not passed" ); setUint256(_slot, scheduledUint256(_slot)); } function setAddress(bytes32 _slot, address _target) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(_slot, _target) } } function fetchAddress(bytes32 _slot) internal view returns (address result) { assembly { result := sload(_slot) } } function scheduledAddress(bytes32 _slot) internal view returns (address result) { result = fetchAddress(scheduledContentSlot(_slot)); } function scheduledUint256(bytes32 _slot) internal view returns (uint256 result) { result = fetchUint256(scheduledContentSlot(_slot)); } function setUint256(bytes32 _slot, uint256 _target) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(_slot, _target) } } function fetchUint256(bytes32 _slot) internal view returns (uint256 result) { assembly { result := sload(_slot) } } function scheduledContentSlot(bytes32 _slot) internal pure returns (bytes32) { return bytes32( uint256(keccak256(abi.encodePacked(_slot, SCHEDULED_SIGNATURE))) ); } function scheduledTime(bytes32 _slot) internal view returns (uint256) { return fetchUint256(scheduledTimeSlot(_slot)); } function scheduledTimeSlot(bytes32 _slot) internal pure returns (bytes32) { return bytes32( uint256(keccak256(abi.encodePacked(_slot, TIMESLOT_SIGNATURE))) ); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; contract StorageV1Upgradeable is Initializable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; address public proxyAdmin; address public governance; address public _treasury; EnumerableSetUpgradeable.AddressSet admin; EnumerableSetUpgradeable.AddressSet operator; address public swapCenter; address public registry; bool public registryLocked; mapping(bytes32 => address) public addressStorage; mapping(bytes32 => address[]) public addressArrayStorage; mapping(bytes32 => uint256) public uint256Storage; mapping(bytes32 => uint256[]) public uint256ArrayStorage; mapping(bytes32 => bool) public boolStorage; mapping(bytes32 => bool[]) public boolArrayStorage; event GovernanceChanged(address oldGov, address newGov); event TreasuryChanged(address oldTreasury, address newTreasury); event AdminAdded(address newAdmin); event AdminRetired(address retiredAdmin); event OperatorAdded(address newOperator); event OperatorRetired(address oldOperator); event RegistryChanged(address oldRegistry, address newRegistry); event SwapCenterChanged(address oldSwapCenter, address newSwapCenter); event RegistryLocked(); modifier onlyGovernance() { require(msg.sender == governance, "StorageV1: not governance"); _; } modifier adminPriviledged() { require(msg.sender == governance || isAdmin(msg.sender), "StorageV1: not governance or admin"); _; } modifier registryNotLocked() { require(!registryLocked, "StorageV1: registry locked"); _; } constructor() { governance = msg.sender; } function initialize(address _governance, address _proxyAdmin) external initializer { require(_governance != address(0), "!empty"); require(_proxyAdmin != address(0), "!empty"); governance = _governance; proxyAdmin = _proxyAdmin; } function setGovernance(address _governance) external onlyGovernance { require(_governance != address(0), "!empty"); emit GovernanceChanged(governance, _governance); governance = _governance; } function treasury() external view returns (address) { if(_treasury == address(0)) { return governance; } else { return _treasury; } } function setTreasury(address _newTreasury) external onlyGovernance { require(_newTreasury != address(0)); emit TreasuryChanged(_treasury, _newTreasury); _treasury = _newTreasury; } function setRegistry(address _registry) external onlyGovernance registryNotLocked { require(_registry != address(0), "!empty"); emit RegistryChanged(registry, _registry); registry = _registry; } function lockRegistry() external onlyGovernance { emit RegistryLocked(); registryLocked = true; // While the contract doesn't provide an unlock method // It is still possible to unlock this via Timelock, by upgrading the // implementation of the Timelock proxy. } function setSwapCenter(address _swapCenter) external onlyGovernance { emit SwapCenterChanged(swapCenter, _swapCenter); swapCenter = _swapCenter; } function setAddress(bytes32 index, address _newAddr) external onlyGovernance { addressStorage[index] = _newAddr; } function setAddressArray(bytes32 index, address[] memory _newAddrs) external onlyGovernance { addressArrayStorage[index] = _newAddrs; } function setUint256(bytes32 index, uint256 _newUint256) external onlyGovernance { uint256Storage[index] = _newUint256; } function setUint256Array(bytes32 index, uint256[] memory _newAddrs) external onlyGovernance { uint256ArrayStorage[index] = _newAddrs; } function setUint256(bytes32 index, bool _newBool) external onlyGovernance { boolStorage[index] = _newBool; } function setBoolArray(bytes32 index, bool[] memory _newBools) external onlyGovernance { boolArrayStorage[index] = _newBools; } function numOfAdmin() public view returns (uint256) { return admin.length(); } function numOfOperator() public view returns (uint256) { return operator.length(); } function getAdmin(uint256 idx) public view returns (address){ return admin.at(idx); } function getOperator(uint256 idx) public view returns (address){ return operator.at(idx); } function addAdmin(address _who) public onlyGovernance returns (bool) { emit AdminAdded(_who); return admin.add(_who); } function addOperator(address _who) public adminPriviledged returns (bool) { emit OperatorAdded(_who); return operator.add(_who); } function removeAdmin(address _who) public onlyGovernance returns (bool) { emit AdminRetired(_who); return admin.remove(_who); } function removeOperator(address _who) public adminPriviledged returns (bool) { emit OperatorRetired(_who); return operator.remove(_who); } function isAdmin(address _who) public view returns (bool) { return admin.contains(_who); } function isOperator(address _who) public view returns (bool) { return operator.contains(_who); } }
Anyone can call the function when the IV has more debt than funds in the investment opportunity, this means that it has lost money and could file for insurance. The function would calculate the lost amount automatically, and call contracts that have provided insurance. If the loss is negligible, the function will not call the respective contracts. Calling _fileInsuranceClaimAmount with zero claim amount will unlock the previously locked insurance vault.
function _investAll() internal virtual; function fileInsuanceClaim() public { uint256 totalBalance = invested().add(IERC20Upgradeable(baseAsset).balanceOf(address(this))); uint256 totalDebtAmount = totalDebt(); uint256 claimAmount = 0; if(totalBalance < totalDebtAmount) { claimAmount = totalDebtAmount.sub(totalBalance); } if(claimAmount < (totalDebtAmount / 10000)){ claimAmount = 0; } emit InsuranceClaimFiled(claimAmount); }
1,475,697
/** Orgon Token Smart Contract. Copyright © 2019 by Oris.Space. v25 */ pragma solidity ^0.4.25; library SafeMath { /** * Add two uint256 values, throw in case of overflow. * @param x first value to add * @param y second value to add * @return x + y */ function safeAdd (uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x + y; require(z >= x); return z; } /** * Subtract one uint256 value from another, throw in case of underflow. * @param x value to subtract from * @param y value to subtract * @return x - y */ function safeSub (uint256 x, uint256 y) internal pure returns (uint256) { require (x >= y); uint256 z = x - y; return z; } } contract Token { /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () public view returns (uint256 supply); /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) public view returns (uint256 balance); /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) public returns (bool success); /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) public returns (bool success); /** * Allow given spender to transfer given number of tokens from message sender. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) public returns (bool success); /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance (address _owner, address _spender) public view returns (uint256 remaining); /** * Logged when tokens were transferred from one owner to another. * * @param _from address of the owner, tokens were transferred from * @param _to address of the owner, tokens were transferred to * @param _value number of tokens transferred */ event Transfer (address indexed _from, address indexed _to, uint256 _value); /** * Logged when owner approved his tokens to be transferred by some spender. * * @param _owner owner who approved his tokens to be transferred * @param _spender spender who were allowed to transfer the tokens belonging * to the owner * @param _value number of tokens belonging to the owner, approved to be * transferred by the spender */ event Approval ( address indexed _owner, address indexed _spender, uint256 _value); } /** Orgon Token smart contract */ contract OrgonToken is Token { using SafeMath for uint256; /* Maximum allowed number of tokens in circulation (2^256 - 1). */ uint256 constant MAX_TOKEN_COUNT = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /* Full life start time (2021-10-18 18:10:21 UTC) */ uint256 private constant LIFE_START_TIME = 1634559021; /* Number of tokens to be send for Full life start 642118523.280000000000000000 */ uint256 private constant LIFE_START_TOKENS = 642118523280000000000000000; /** Deploy Orgon Token smart contract and make message sender to be the owner of the smart contract */ /* *********************************************** */ constructor() public { owner = msg.sender; mint = msg.sender; } /** Get name,symbol of this token, number of decimals for this token * @return name of this token */ /* *********************************************** */ function name () public pure returns (string) { return "ORGON"; } /* *********************************************** */ function symbol () public pure returns (string) { return "ORGON"; } /* *********************************************** */ function decimals () public pure returns (uint8) { return 18; } /** Get total number of tokens in circulation * @return total number of tokens in circulation */ /* *********************************************** */ function totalSupply () public view returns (uint256 supply) { return tokenCount; } /* *********************************************** */ function totalICO () public view returns (uint256) { return tokenICO; } /* *********************************************** */ function theMint () public view returns (address) { return mint; } /* *********************************************** */ function theStage () public view returns (Stage) { return stage; } /* *********************************************** */ function theOwner () public view returns (address) { return owner; } /** Get balance */ /* *********************************************** */ function balanceOf (address _owner) public view returns (uint256 balance) { return accounts [_owner]; } /** Transfer given number of tokens from message sender to given recipient. * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ /* *********************************************** */ function transfer (address _to, uint256 _value) public validDestination(_to) returns (bool success) { require (accounts [msg.sender]>=_value); uint256 fromBalance = accounts [msg.sender]; if (fromBalance < _value) return false; if (stage != Stage.ICO){ accounts [msg.sender] = fromBalance.safeSub(_value); accounts [_to] = accounts[_to].safeAdd(_value); } else if (msg.sender == owner){ // stage == Stage.ICO accounts [msg.sender] = fromBalance.safeSub(_value); accounts [_to] = accounts[_to].safeAdd(_value); tokenICO = tokenICO.safeAdd(_value); } else if (_to == owner){ // stage == Stage.ICO accounts [msg.sender] = fromBalance.safeSub(_value); accounts [_to] = accounts[_to].safeAdd(_value); tokenICO = tokenICO.safeSub(_value); } else if (forPartners[msg.sender] >= _value){ // (sender is Partner) accounts [msg.sender] = fromBalance.safeSub(_value); forPartners [msg.sender] = forPartners[msg.sender].safeSub(_value); accounts [_to] = accounts[_to].safeAdd(_value); } else revert(); emit Transfer (msg.sender, _to, _value); return true; } /** Transfer given number of tokens from given owner to given recipient. * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ /* *********************************************** */ function transferFrom (address _from, address _to, uint256 _value) public validDestination(_to) returns (bool success) { require (stage != Stage.ICO); require(_from!=_to); uint256 spenderAllowance = allowances [_from][msg.sender]; if (spenderAllowance < _value) return false; uint256 fromBalance = accounts [_from]; if (fromBalance < _value) return false; allowances [_from][msg.sender] = spenderAllowance.safeSub(_value); if (_value > 0) { accounts [_from] = fromBalance.safeSub(_value); accounts [_to] = accounts[_to].safeAdd(_value); } emit Transfer (_from, _to, _value); return true; } /** Allow given spender to transfer given number of tokens from message sender * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ /* *********************************************** */ function approve (address _spender, uint256 _value) public returns (bool success) { require(_spender != address(0)); allowances [msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } /** Allow Partner to transfer given number of tokens * @param _partner Partner address * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ /* *********************************************** */ function addToPartner (address _partner, uint256 _value) public returns (bool success) { require (msg.sender == owner); forPartners [_partner] = forPartners[_partner].safeAdd(_value); return true; } /** Disallow Partner to transfer given number of tokens * @param _partner Partner address * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ /* *********************************************** */ function subFromPartner (address _partner, uint256 _value) public returns (bool success) { require (msg.sender == owner); if (forPartners [_partner] < _value) { forPartners [_partner] = 0; } else { forPartners [_partner] = forPartners[_partner].safeSub(_value); } return true; } /** Tell how many tokens given partner is currently allowed to transfer from given him. @param _partner address to get number of tokens allowed to be transferred @return number of tokens given spender is currently allowed to transfer from given owner */ /* *********************************************** */ function partners (address _partner) public view returns (uint256 remaining) { return forPartners [_partner]; } /** Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise*/ /* *********************************************** */ function createTokens (uint256 _value) public returns (bool) { require (msg.sender == mint); if (_value > 0) { if (_value > MAX_TOKEN_COUNT.safeSub(tokenCount)) return false; accounts [msg.sender] = accounts[msg.sender].safeAdd(_value); tokenCount = tokenCount.safeAdd(_value); emit Transfer (address (0), msg.sender, _value); } return true; } /** Burn given number of tokens belonging to owner. * May only be called by smart contract owner. * @param _value number of tokens to burn * @return true on success, false on error */ /* *********************************************** */ function burnTokens (uint256 _value) public returns (bool) { require (msg.sender == mint); require (accounts [msg.sender]>=_value); if (_value > accounts [mint]) return false; else if (_value > 0) { accounts [mint] = accounts[mint].safeSub(_value); tokenCount = tokenCount.safeSub(_value); emit Transfer (mint, address (0), _value); return true; } else return true; } /** Set new owner for the smart contract. * May only be called by smart contract owner. * @param _newOwner address of new owner of the smart contract */ /* *********************************************** */ function setOwner (address _newOwner) public validDestination(_newOwner) { require (msg.sender == owner); owner = _newOwner; uint256 fromBalance = accounts [msg.sender]; if (fromBalance > 0 && msg.sender != _newOwner) { accounts [msg.sender] = fromBalance.safeSub(fromBalance); accounts [_newOwner] = accounts[_newOwner].safeAdd(fromBalance); emit Transfer (msg.sender, _newOwner, fromBalance); } } /** Set new owner for the smart contract. * May only be called by smart contract owner. * @param _newMint address of new owner of the smart contract */ /* *********************************************** */ function setMint (address _newMint) public { if (stage != Stage.LIFE && (msg.sender == owner || msg.sender == mint )){ mint = _newMint; } else if (msg.sender == mint){ mint = _newMint; } else revert(); } /** Chech and Get current stage * @return current stage */ /* *********************************************** */ function checkStage () public returns (Stage) { require (stage != Stage.LIFE); Stage currentStage = stage; if (currentStage == Stage.ICO) { if (block.timestamp >= LIFE_START_TIME || tokenICO > LIFE_START_TOKENS) { currentStage = Stage.LIFE; stage = Stage.LIFE; } else return currentStage; } return currentStage; } /** Change stage by Owner */ /* *********************************************** */ function changeStage () public { require (msg.sender == owner); require (stage != Stage.LIFE); if (stage == Stage.ICO) {stage = Stage.LIFEBYOWNER;} else stage = Stage.ICO; } /** Tell how many tokens given spender is currently allowed to transfer from * given owner. * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ /* *********************************************** */ function allowance (address _owner, address _spender) public view returns (uint256 remaining) { return allowances [_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 increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); allowances[msg.sender][spender] = allowances[msg.sender][spender].safeAdd(addedValue); emit Approval(msg.sender, spender, allowances[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 decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); allowances[msg.sender][spender] = allowances[msg.sender][spender].safeSub(subtractedValue); emit Approval(msg.sender, spender, allowances[msg.sender][spender]); return true; } /** Get current time in seconds since epoch. * @return current time in seconds since epoch */ function currentTime () public view returns (uint256) { return block.timestamp; } /** Total number of tokens in circulation */ uint256 private tokenCount; /** Total number of tokens in ICO */ uint256 private tokenICO; /** Owner of the smart contract */ address private owner; /** Mint of the smart contract */ address private mint; enum Stage { ICO, // LIFEBYOWNER, LIFE// } /** Last known stage of token*/ Stage private stage = Stage.ICO; /** Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders */ mapping (address => uint256) private accounts; /** Mapping from addresses of partners to the numbers of tokens belonging * to these partners. */ mapping (address => uint256) private forPartners; /** Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders */ mapping (address => mapping (address => uint256)) private allowances; modifier validDestination (address to) { require (to != address(0x0)); require (to != address(this)); _; } }
/
function balanceOf (address _owner) public view returns (uint256 balance) { return accounts [_owner]; }
895,335
pragma solidity ^0.4.19; contract Ownable { /** * @dev set `owner` of the contract to the sender */ address public owner = msg.sender; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } } library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] += _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] += _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]; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event Burn(address indexed burner, uint value); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply += _amount; balances[_to] += _amount; Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to burn tokens * @param _addr The address that will have _amount of tokens burned. * @param _amount The amount of tokens to burn. */ function burn(address _addr, uint _amount) onlyOwner public { require(_amount > 0 && balances[_addr] >= _amount && totalSupply >= _amount); balances[_addr] -= _amount; totalSupply -= _amount; Burn(_addr, _amount); Transfer(_addr, address(0), _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract WealthBuilderToken is MintableToken { string public name = "Wealth Builder Token"; string public symbol = "WBT"; uint32 public decimals = 18; /** * how many {tokens*10^(-18)} get per 1wei */ uint public rate = 10**7; /** * multiplicator for rate */ uint public mrate = 10**7; function setRate(uint _rate) onlyOwner public { rate = _rate; } } contract Data is Ownable { // node => its parent mapping (address => address) private parent; // node => its status mapping (address => uint8) public statuses; // node => sum of all his child deposits in USD cents mapping (address => uint) public referralDeposits; // client => balance in wei*10^(-6) available for withdrawal mapping(address => uint256) private balances; // investor => balance in wei*10^(-6) available for withdrawal mapping(address => uint256) private investorBalances; function parentOf(address _addr) public constant returns (address) { return parent[_addr]; } function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr] / 1000000; } function investorBalanceOf(address _addr) public constant returns (uint256) { return investorBalances[_addr] / 1000000; } /** * @dev The Data constructor to set up the first depositer */ function Data() public { // DirectorOfRegion - 7 statuses[msg.sender] = 7; } function addBalance(address _addr, uint256 amount) onlyOwner public { balances[_addr] += amount; } function subtrBalance(address _addr, uint256 amount) onlyOwner public { require(balances[_addr] >= amount); balances[_addr] -= amount; } function addInvestorBalance(address _addr, uint256 amount) onlyOwner public { investorBalances[_addr] += amount; } function subtrInvestorBalance(address _addr, uint256 amount) onlyOwner public { require(investorBalances[_addr] >= amount); investorBalances[_addr] -= amount; } function addReferralDeposit(address _addr, uint256 amount) onlyOwner public { referralDeposits[_addr] += amount; } function setStatus(address _addr, uint8 _status) onlyOwner public { statuses[_addr] = _status; } function setParent(address _addr, address _parent) onlyOwner public { parent[_addr] = _parent; } } contract Declaration { // threshold in USD => status mapping (uint => uint8) statusThreshold; // status => (depositsNumber => percentage) mapping (uint8 => mapping (uint8 => uint)) feeDistribution; // status thresholds in USD uint[8] thresholds = [ 0, 5000, 35000, 150000, 500000, 2500000, 5000000, 10000000 ]; uint[5] referralFees = [50, 30, 20, 10, 5]; uint[5] serviceFees = [25, 20, 15, 10, 5]; /** * @dev The Declaration constructor to define some constants */ function Declaration() public { setFeeDistributionsAndStatusThresholds(); } /** * @dev Set up fee distribution & status thresholds */ function setFeeDistributionsAndStatusThresholds() private { // Agent - 0 setFeeDistributionAndStatusThreshold(0, [12, 8, 5, 2, 1], thresholds[0]); // SilverAgent - 1 setFeeDistributionAndStatusThreshold(1, [16, 10, 6, 3, 2], thresholds[1]); // Manager - 2 setFeeDistributionAndStatusThreshold(2, [20, 12, 8, 4, 2], thresholds[2]); // ManagerOfGroup - 3 setFeeDistributionAndStatusThreshold(3, [25, 15, 10, 5, 3], thresholds[3]); // ManagerOfRegion - 4 setFeeDistributionAndStatusThreshold(4, [30, 18, 12, 6, 3], thresholds[4]); // Director - 5 setFeeDistributionAndStatusThreshold(5, [35, 21, 14, 7, 4], thresholds[5]); // DirectorOfGroup - 6 setFeeDistributionAndStatusThreshold(6, [40, 24, 16, 8, 4], thresholds[6]); // DirectorOfRegion - 7 setFeeDistributionAndStatusThreshold(7, [50, 30, 20, 10, 5], thresholds[7]); } /** * @dev Set up specific fee and status threshold * @param _st The status to set up for * @param _percentages Array of pecentages, which should go to member * @param _threshold The minimum amount of sum of children deposits to get * the status _st */ function setFeeDistributionAndStatusThreshold( uint8 _st, uint8[5] _percentages, uint _threshold ) private { statusThreshold[_threshold] = _st; for (uint8 i = 0; i < _percentages.length; i++) { feeDistribution[_st][i] = _percentages[i]; } } } contract Investors is Ownable { // investors /* "0x418155b19d7350f5a843b826474aa2f7623e99a6","0xbeb7a29a008d69069fd10154966870ff1dda44a0","0xa9cb1b8ba1c8facb92172e459389f80d304595a3","0xf3f2bf9be0ccc8f27a15ccf18d820c0722e8996a","0xa0f36ac9f68c1a4594ef5cec29dc9b1cc67f822c","0xc319278cca404e3a479b088922e4117feb4cec9d","0xe633c933529d6fd7c6147d2b0dc51bfbe3304e56","0x5bd2c1f2f06b16e427a4ec3a6beef6263fd506da","0x52c4f101d0367c3f9933d0c14ea389e74ad00352","0xf7a0d2149f324a0b607ebf23df671acc4e9da6d2","0x0418df662bb2994262bb720d477e558a59e19490","0xf0de6520e0726ba3d84611f84867aa9987391402","0x1e895274a9570f150f11ae0ed86dd42a53208b81","0x95a247bef71f6b234e9805d1493366a302a498e4","0x9daaeaf355f69f7176a0145df6d1769d7f14553b","0x029136181d87c6f0979431255424b5fad78e8491","0x7e1f5669d9e1c593a495c5cec384ca32ad4a09fc","0x46c7e04fdaaa1a9298e63ca2fd47b0004cb236bf","0x5933fa485863da06584057494f0f6660d3c1477c","0x4290231804dd59947aff9fcef925287e44906e7b","0x2feaf2101b3f9943a81567badb56e3780946ce3f","0x5b602c34ba643913908f69a4cd5846a07ed3915b","0x146308896955030ce3bcc6030bab142afddaa1e6","0x9fc61b75451fabf5b5b78e03bacaf8bb592541fc","0x87f7636f7856466b6c6bce999574a784387e2b78","0x024db1f560327ab5174f1a737caf446b5644c709","0x715c248e621cbdb6f091bf653bb4bc331d2f9b1e","0xfe92a23b497140ba055a91ade89d91f95f8e5153","0xc3426e0e0634725a628a7a21bfd49274e1f24733","0xb12a79b9dba8bbb9ed5e329466a9c2703da38dbd","0x44d8336749ebf584a4bcd636cefe83e6e0b33e7d","0x89c91460c3bdc164250e5a27351c743c070c226a","0xe0798a1b847f450b5d4819043d27a380a4715af8","0xeac5e75252d902cb7f8473e45fff9ceb391c536b","0xea53e88876a6da2579d837a559b31b08d6750681","0x5df22fac00c45ef7b5c285c54a006798f42bbc6e","0x09899f20064b5e67d02f6a97ef412564977ee193","0xc572f18d0a4a65f6e612e6de484dbc15b8839df3","0x397b9719e720c0d33fe7dcc004958e56636cbf82","0x577de83b60299df60cc7fce7ac78d3a5d880aa95","0x9a716298949b16c4610b40ba1d19e96d3286c35c","0x60ef523f3845e38a20b63344a4e9ec689773ead6","0xe34252e3efe0514c5fb76c9fb39ff31f554d6659","0xbabfbdf4f422d36c00e448cc562ce0f5dbe47d64","0x2608cca4aff4cc3008ac6bd22e0664348ecee088","0x0dd1d3102f89d4ee7c260048cbe01933f17debde","0xdbb28fafc4ecd7736247aca7dc8e20782ca86a7a","0x6201fc413bb9292527956a70e7575436d5135ce1","0xa836f4cfb8fd3e5bccc9c7a6a678f2a5928b7c79","0x85dce799fd059d86c420eb4e3c1bd89e323b7b12","0xdef2086c6bbdc8b0f6e130907f05345b44af8cc3","0xc1004695ce07ef5efb1d218672e5cfcb659c5900","0x227a5b4bb4cffc2b907d9f586dd100989efeee56","0xd372b3d43ba8ea406f64dbc68f70ec812e54fbc8","0xdf6c417cdb27bc0c877a0e121a2c58ad884e85c6","0x090f4d53b5d7ebcb8e348709cdb708d80cd199f0","0x2499b302b6f5e57f54c1c7a326813e3dffddcd1a","0x3114024a034443e972707522d911fc709f62dd3e","0x30b864f49cef510b1173a5bfc31e77b0b59daf9e","0x9a9680f5ddee6cef96ef36ab506f4b6d3198c35e","0x08018337b9b138b631cd325168c3d5014df6e18b","0x2ac345a4ec1615c3a236099ebbed4911673bbfa5","0x2b9fd54828cd443b7c411419b058b44bd02fdc49","0x208713a63460d44e5a83ae8e8f7333496a05065e","0xe4052eb7ba8891ee7ccd7551faaa5f4c421904e7","0x74bc9db1ac813db06f771bcff359e9237b01c906","0x033dd047a042ea873ca27af36b64ca566a006e97","0xb4721808a3f2830a1708967302443b53f5943429","0xc91fbb815c2f4944d8c6846be6ac0e30f5a037df","0x19ef947c276436ac11a8be15567909a37d824e73","0x079eefd69c5a4c5e4c9ee3fa08c2a2964da3e11a","0x11fb64be296590f948d56daab6c2d102c9842b08","0x06ec97feaeb0f4b9a75f9671d6b62bfadaf18ddd","0xaeda3cff45032695fb2cf4f584cda822bd5d8b7e","0x9f377085d3da85107cd68bd08bdd9a1b862d44e0","0xb46b8d1c313c52fd422fe189dde1b4d0800a5e0f","0x99039fa34510c7321f4d19ea337c80cc14cc885d","0x378aba0f47c7790ed0e5ca61749b0025d1208a5d","0x4395e1db93d4e2f4583a4f87494eb0aea057b8fd","0xa4035578750564e48abfb5ba1d6eec1da1bf366f","0xb611b39eb6c16dae3754e514ddd5f02fcadd765f","0x67d41491ddc004e899a3faf109f526cd717fe6d8","0x58e2c10865f9a1668e800c91b6a3d7b3416fb26c","0x04e34355ced9d532c9bc01d5e569f31b6d46cd50","0xf80358cabdc9b9b79570b6f073a861cf5567bb57","0xbdacb079fc17a00d945f01f4f9bd5d03cfcd5b6c","0x387a723060bc42a7796c76197d2d3b41b4c43d19","0xa04cc8fc56c34ab8104f63c11bf211de4bb7b0aa","0x3bf8b5ede7501519d41792715215735d8f40af10","0x6c3a13bac5cf61b1927562a927e89ca6b5d034d6","0x9899aecef15de43eec04859be649ac4c50330886","0xa4d25bac971ca08b47a908a070b6362102206c12" "0xf88d963dc3f58fe6e71879543e57734e8152f70d","0x7b30a000f7ae56ee6206cbd9fb20c934b4bbb5d1","0xb2f0e5330e90559a738eda0df156635e18a145fd","0x5b2c07b6cce506f2293f1b32dc33d9928b8c9ada","0x5a967c0e38cb3bfad90df288ce238699cc47b5e3","0x0e686d6f3c897cae3984b80b5f6a7c785c708718","0xa8ea0b6bc70502644c0644fb4c0810540a1fa261","0xc70e278819ef5aec6b3ededc21e2981557e14443","0x477b5ae32ffcd34eb25f0c52866d4f602982dc6f","0x3e72a45fbc6a0858b506a0c7bedff79af75ae37c","0x1430e272a50703ef46d8ed5aa01e1ced71245341","0xc87d0bb90a6105a66fd5105c6746218d381b8207","0x0ed7f98b6177d0c15e27704f2bae4d068b8594d5","0x09a627b57879eb625cd8b7c59ffa363222553c23","0x0fdbc41046590ef7ee2a73b9808fd5bd7e189ac4","0x6a4b68af67a3b4a98fe1a59210dd3d775e567729","0x442a3daf774329fee3e904e86ddec1191f4be3ce","0x9efa8fe7fa51c8b36ab902046f879b035520f556","0x510e8e58b8ce4acaa6866e59dfc0fa339ea358e5","0x374831251283aa63aee6506ac6580479aaf3c22b","0xf758c498d020c0b92f2116d09d7ef6509c2c71bd","0xd83e8281ffcfb0ff96236e99ba66aabb8dcc7920","0x3670c3a5e65b757db8c82b12dd92057ac19d41fa","0xfd28eb7e3e5e3406ce6b82045d487c2be294cd38","0x2d23cd492096b903e4595ccdac74e49692a6ea8e","0x94d3a0a19ed5448052c549fd1f69f54c5f1fd8c5","0x8e5354ac59cee09d252e379a3534053306022ebe","0xa66f3700dda0147c56c2970202768c956c644ffd","0xf11d32baef6221f36916c58844cd8e9813c0af47","0x384a9bc1de23b36c2a23b963e57c8cd85b0d592c","0xbd00dfbaaa1abaa7948c7b2a6bed6e644293cc1c","0xa99a28afcbd4ab09a2ef2c0932becd0368225ee6","0xe554084d77bc6e510eed7276cb6033865375b669","0xe7582fa53531915a2fef5a81b98969d0091d8d44","0x5f15db1d209fa6fd3c667fb086d3d89e3793511f","0x7e9ff5348d57d3427e24b7e104ad5acf039edaf2","0xb4fb1a01483454d75a0cdfa983b99236c4c91111","0x4a7cc5eebfe019efab06c1fa9ae8453dc63ba84e","0xb6fc08d5043b51ac05cdbd88afaab0e4422762d0","0xb18365f4f1e95287a5f85c8a67cebee9e6164c31","0xaf575cfb94d65eaeaace749868282d0e26e4608a","0x3d07e5ff3a2d29ee17584dff60cc99bb4cd79c3d","0x08f0afc93fbc8188150f4bcab004e259cd4785aa","0x65ac3ed81f101e5651c72c4cc2d74650378b5b0c","0x58aef4fc6b54cb53683a6481655021109b8d4dce","0x6aa43e24604577574a0632524a1f4c21d70a61e2","0xbee55aa5ad9953294ecac83a6b62f10c8155444b","0x99dc885ac6ec9873e2409d5a31e7f525c1897e09","0x53a0622034680d64bd0f139df5e989d70b194a4d","0xa6ba4966f1fdd0e8560516e53490b25cf0c4fbd1","0xbd1b95ee4621ecda41961da61277e17e52f37dbf","0xf6481b881eea526ae36cbe11d58d641f96f04a77","0xd158d53d75eac0dda9d2dedf3418d071a2fd44ee","0xb22697e3f33544da7782c8197d07704e1906a3bf","0xa3237e67df409dca45930c1f5f671251adc202be","0x72b26f2dded753a01f391322b00f9a85a77c7fda","0x203fbf3a77bdf35f7aca220b363272896db91d57","0xb1be2f4d72eb87dfcf7ed93c8ec16e4040e52560","0xc60d8a0313ede22194ebe6285471f72f9bcdcda0","0x9888e7423ea48413a4c90a10c76ca5f90d065e1f","0x0be856768ad0ec5b45464ce5202e2c337224cebf","0x3b54ea00a74b116510c4f73a3fc19a62991aaf64","0xe72aa06ffe7058f73622f219af164369c03e3a41","0x7e71fada017d9af455f38db4957d527f51fe1bc5","0x78430e58934220f37ca6b9dbe622f076ad0eb3f5","0x0c765e201bb43d49ab5b44d40d3cf1d219424821","0x4739d251b40028761bbd8034a21919d926f23b45","0x00a7c7bc71022032f6ef3f699b212c9450875740","0x0d4f50b0d43d34a163b8dd7c33fbcc92a19cfa59","0x9284fbc0cc35d9b835de2b00b6b7093075527f6b","0x3564e101b32fe5f3c99e8da823ac003373c26d33","0xf5a358f228dc964fa7c703cb6ad9f6002ce77b17","0x8297a09b5dac9e60896c787f0995ac06441ab14f","0xed8c9b4fd60a6e4ae66c38f5819cffb360af5dd5","0x23009de4ec4a666ba719656d844e42e264e14c6b","0x63227f4492c6bbd9e1015f2c864a31eef1465cd3","0xf3e0ec409386ea202b15d97bb8dd2d131917e3b1","0x981154fafb3a5aeee43d984ee255e5121ce79790","0x49a4598cdf112b5848c11c465d39989fcb5cb6c1","0x575ca03f00f9e5566d85dc095165998953ab0753","0x09d87f2979c4ac6c9d4077d1f5d94cb9aadf43ca","0x0b4575867757b3982379f4d05c92fd2d019247a0","0x8c666d40e2ac961885d675e58e3115b859dac6c1","0x34a3401ebe8431d44efee9948c4b641142407aa8","0x1683512dbcce189ea6042862a2ba4abd4886623b","0x72d45f733336f6f03ef20c1ad4f51ff6b7f90186","0x569fe010fe2d40037c029537eef78aa9b0e018f9","0x061def9fab3aee4161711d4c040d138a273893b5","0xe77e2ae67e1152425c75ff56291d03d92f5d3cad","0x93ebdeb0b0c967f5cc1a10f481569e1871b7d7cd","0x6d7910f900fc3e3f2e2b6d5d8aad43bc6a232685","0xb16e28be300f579a81f2b80fdd5a95cf168bf3a4" "0xd69835daeee01601ea991efe9fd0309c64c07d42","0x30b45ed69250a160ee91dadab2986d21626d7f4b","0xd28075489da5f9ef51bcc61668c114296a8e8603","0xb63c5cb479034bacc04266536e32aeeb9f958059","0x5f81fe78b5c238afd97a32c572aa04d87b730147","0xb98c8d7d64ef60cc76410f31c19570da0c4d9f12","0x031eb1c3a9909ea26d07f194abe5ad7f6945a482","0x83691573a4fdb5ff2cdbe2df155da09810a3c2bc","0x6722a482e1f3b797e69f98a3324b6660b9c6baa5","0xbda61db5824240280ed000a57ed5e6f70d552dd6","0x58605742105060e5c3070b88b0f51eca7f022d06","0xb4754815ccfc9c98a80f71a0a2c97471188bd556","0x50503144f253e6f05103b643c082ebf215436d95","0xd0dbef9f712ee0ca05fe48b6a40f5b774a109feb" */ address[] public investors; // investor address => percentage * 10^(-2) /* 3026,1500,510,462,453,302,250,250,226,220,150,129,100,100,60,50,50,50,50,50,50,50,50,50,50,40,40,30,27,26,25,25,25,25,25,25,25,25,23,20,19,15,15,15,15,15,14,14,13,13,13,13,12,12,11,11,11,11,11,11,10,10,10,10,10,10,10,10,12,9,9,8,8,8,8,7,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,6 6,125,50,5,8,50,23,3,115,14,10,50,5,5 */ mapping (address => uint) public investorPercentages; /** * @dev Add investors */ function addInvestors(address[] _investors, uint[] _investorPercentages) onlyOwner public { for (uint i = 0; i < _investors.length; i++) { investors.push(_investors[i]); investorPercentages[_investors[i]] = _investorPercentages[i]; } } /** * @dev Get investors count * @return uint count */ function getInvestorsCount() public constant returns (uint) { return investors.length; } /** * @dev Get investors' fee depending on the current year * @return uint8 The fee percentage, which investors get */ function getInvestorsFee() public constant returns (uint8) { //01/01/2020 if (now >= 1577836800) { return 1; } //01/01/2019 if (now >= 1546300800) { return 5; } return 10; } } contract Referral is Declaration, Ownable { using SafeMath for uint; // reference to token contract WealthBuilderToken private token; // reference to data contract Data private data; // reference to investors contract Investors private investors; // investors balance to be distributed in wei*10^(2) uint public investorsBalance; /** * how many USD cents get per ETH */ uint public ethUsdRate; /** * @dev The Referral constructor to set up the first depositer, * reference to system token, data & investors and set ethUsdRate */ function Referral(uint _ethUsdRate, address _token, address _data, address _investors) public { ethUsdRate = _ethUsdRate; // instantiate token & data contracts token = WealthBuilderToken(_token); data = Data(_data); investors = Investors(_investors); investorsBalance = 0; } /** * @dev Callback function */ function() payable public { } function invest(address client, uint8 depositsCount) payable public { uint amount = msg.value; // if less then 5 deposits if (depositsCount < 5) { uint serviceFee; uint investorsFee = 0; if (depositsCount == 0) { uint8 investorsFeePercentage = investors.getInvestorsFee(); serviceFee = amount * (serviceFees[depositsCount].sub(investorsFeePercentage)); investorsFee = amount * investorsFeePercentage; investorsBalance += investorsFee; } else { serviceFee = amount * serviceFees[depositsCount]; } uint referralFee = amount * referralFees[depositsCount]; // distribute deposit fee among users above on the branch & update users' statuses distribute(data.parentOf(client), 0, depositsCount, amount); // update balance & number of deposits of user uint active = (amount * 100) .sub(referralFee) .sub(serviceFee) .sub(investorsFee); token.mint(client, active / 100 * token.rate() / token.mrate()); // update owner`s balance data.addBalance(owner, serviceFee * 10000); } else { token.mint(client, amount * token.rate() / token.mrate()); } } /** * @dev Recursively distribute deposit fee between parents * @param _node Parent address * @param _prevPercentage The percentage for previous parent * @param _depositsCount Count of depositer deposits * @param _amount The amount of deposit */ function distribute( address _node, uint _prevPercentage, uint8 _depositsCount, uint _amount ) private { address node = _node; uint prevPercentage = _prevPercentage; // distribute deposit fee among users above on the branch & update users' statuses while(node != address(0)) { uint8 status = data.statuses(node); // count fee percentage of current node uint nodePercentage = feeDistribution[status][_depositsCount]; uint percentage = nodePercentage.sub(prevPercentage); data.addBalance(node, _amount * percentage * 10000); //update refferals sum amount data.addReferralDeposit(node, _amount * ethUsdRate / 10**18); //update status updateStatus(node, status); node = data.parentOf(node); prevPercentage = nodePercentage; } } /** * @dev Update node status if children sum amount is enough * @param _node Node address * @param _status Node current status */ function updateStatus(address _node, uint8 _status) private { uint refDep = data.referralDeposits(_node); for (uint i = thresholds.length - 1; i > _status; i--) { uint threshold = thresholds[i] * 100; if (refDep >= threshold) { data.setStatus(_node, statusThreshold[threshold]); break; } } } /** * @dev Distribute fee between investors */ function distributeInvestorsFee(uint start, uint end) onlyOwner public { for (uint i = start; i < end; i++) { address investor = investors.investors(i); uint investorPercentage = investors.investorPercentages(investor); data.addInvestorBalance(investor, investorsBalance * investorPercentage); } if (end == investors.getInvestorsCount()) { investorsBalance = 0; } } /** * @dev Set token exchange rate * @param _rate wbt/eth rate */ function setRate(uint _rate) onlyOwner public { token.setRate(_rate); } /** * @dev Set ETH exchange rate * @param _ethUsdRate eth/usd rate */ function setEthUsdRate(uint _ethUsdRate) onlyOwner public { ethUsdRate = _ethUsdRate; } /** * @dev Add new child * @param _inviter parent * @param _invitee child */ function invite( address _inviter, address _invitee ) public onlyOwner { data.setParent(_invitee, _inviter); // Agent - 0 data.setStatus(_invitee, 0); } /** * @dev Set _status for _addr * @param _addr address * @param _status ref. status */ function setStatus(address _addr, uint8 _status) public onlyOwner { data.setStatus(_addr, _status); } /** * @dev Set investors contract address * @param _addr address */ function setInvestors(address _addr) public onlyOwner { investors = Investors(_addr); } /** * @dev Withdraw _amount for _addr * @param _addr withdrawal address * @param _amount withdrawal amount */ function withdraw(address _addr, uint256 _amount, bool investor) public onlyOwner { uint amount = investor ? data.investorBalanceOf(_addr) : data.balanceOf(_addr); require(amount >= _amount && this.balance >= _amount); if (investor) { data.subtrInvestorBalance(_addr, _amount * 1000000); } else { data.subtrBalance(_addr, _amount * 1000000); } _addr.transfer(_amount); } /** * @dev Withdraw contract balance to _addr * @param _addr withdrawal address */ function withdrawOwner(address _addr, uint256 _amount) public onlyOwner { require(this.balance >= _amount); _addr.transfer(_amount); } /** * @dev Withdraw corresponding amount of ETH to _addr and burn _value tokens * @param _addr withdrawal address * @param _amount amount of tokens to sell */ function withdrawToken(address _addr, uint256 _amount) onlyOwner public { token.burn(_addr, _amount); uint256 etherValue = _amount * token.mrate() / token.rate(); _addr.transfer(etherValue); } /** * @dev Transfer ownership of token contract to _addr * @param _addr address */ function transferTokenOwnership(address _addr) onlyOwner public { token.transferOwnership(_addr); } /** * @dev Transfer ownership of data contract to _addr * @param _addr address */ function transferDataOwnership(address _addr) onlyOwner public { data.transferOwnership(_addr); } } contract PChannel is Ownable { Referral private refProgram; // fixed deposit amount in USD cents uint private depositAmount = 100000; // max deposit amount in USD cents uint private maxDepositAmount = 125000; // investor => number of deposits mapping (address => uint8) private deposits; function PChannel(address _refProgram) public { refProgram = Referral(_refProgram); } function() payable public { uint8 depositsCount = deposits[msg.sender]; // check if user has already exceeded 15 deposits limit require(depositsCount < 15); uint amount = msg.value; uint usdAmount = amount * refProgram.ethUsdRate() / 10**18; // check if deposit amount is valid require(usdAmount >= depositAmount && usdAmount <= maxDepositAmount); refProgram.invest.value(amount)(msg.sender, depositsCount); deposits[msg.sender]++; } /** * @dev Set investors contract address * @param _addr address */ function setRefProgram(address _addr) public onlyOwner { refProgram = Referral(_addr); } }
Function to burn tokens _addr The address that will have _amount of tokens burned. _amount The amount of tokens to burn./
function burn(address _addr, uint _amount) onlyOwner public { require(_amount > 0 && balances[_addr] >= _amount && totalSupply >= _amount); balances[_addr] -= _amount; totalSupply -= _amount; Burn(_addr, _amount); Transfer(_addr, address(0), _amount); }
626,850
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // WELCOME TO PAPERPLANE.FINANCE // // // // This token has some unique features. There is a 13% tx fee on every tx. This fee is a 12% // // (burn+redistribution+liquidityTokens) part (more on this later) and a 1% marketing fee. // // // // Team doesnt have any tokens at all. Our presale estrategy is 76% of tokens are for // // presale+initial liquidity and the remaining 24% stays within the contract to add LP over time // // // // THERE IS 0% TOKENS FOR TEAM AT THE BEGINING. // // // // The 12% fee part is a variable sum of redistribution burn and tokens for more LP. Each % varies // // depending on the size of the sender wallet. EVERYONE PAYS 12%. But PaperWhales Redistribute more and // // burn less. Meanwhile PaperHands (Diamond Heart) redistribute a little and burn MOAR! The total fee // // IS THE SAME FOR EVERYONE 12% // // // // This is only the first phase of Paperplane.finance. We have many plans for the future. // // // // SOCIALS // // Website: https://paperplane.finance/ // // Twitter: https://twitter.com/PaperplaneBSC // // Medium: https://medium.com/@paperplanebsc // // GitHub: https://github.com/paperplaneBSC // // Telegram: https://t.me/paperplanefinance // // // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { 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; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); 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); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } 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 functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } 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); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } abstract contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until some time passes"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0; 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; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); 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; } contract PaperPlane is Context, IERC20, Ownable { using Address for address; //addresses Burn, Marketing, Lp Wallet address private constant _burnAddress = 0x000000000000000000000000000000000000dEaD; address private _marketingWallet = 0x000000000000000000000000000000000000dEaD; // to be change to marketingWallet at begining before deploy address private _lpWallet = _marketingWallet; //MAPINGS //mapping balance and reflected balance of address mapping (address => uint256) private _balances; mapping (address => uint256) private _reflectBalances; //allowances of address to address with amount about this token mapping (address => mapping (address => uint256)) private _allowances; //mapping who is excluded from what (Fees or recieve Rewards) mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcludedFromReward; address[] private _excludedFromReward; //PROJECT SETTINGS //Name Symbol Decimals string private constant _name = 'Paperplane.finance'; // to be determined string private constant _symbol = 'PPLANE'; // to be determined uint8 private constant _decimals = 18; //Supply and Reflected Supply and other options uint256 private constant _decimalFactor = 10**uint256(_decimals); uint256 private _tokenTotal = 10000000 * _decimalFactor ; uint256 private constant MAX = ~uint256(0); uint256 private _reflectedTotal = (MAX - (MAX % _tokenTotal)); uint256 private constant _granularity = 100; // this allows 0.5 percentages for example uint256 private _totalTokenFee = 0; //Total Fees collected uint256 private _totalMarketing; uint256 private _totalBurn; uint256 private _totalLiq; //Initial fees uint256 private aMulti = 1000; //aMulti + 2*bMulti must add 1200 uint256 private bMulti = 100; //aMulti + 2*bMulti must add 1200 uint256 private _tokensToLP = 5000 * _decimalFactor; //0.5% of total supply uint256 private marketingFee = 100; // multiplier 1 (100/100) bool private _disableFees = false; //Router and Pair Addresses for Add Liquidity IUniswapV2Router02 private immutable uniswapV2Router; address private immutable uniswapV2Pair; IUniswapV2Pair private immutable pair; //Add Liquidity checkeers bool private inSwapAndLiquify; bool private swapAndLiquifyEnabled = false; // to be set true as soon as possible //eventos event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event Info(string cad, uint256 num); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _reflectBalances[_msgSender()] = _reflectedTotal; // listing price 40000 tokens per BNB presale+liq. 7.600.000 tokens //real pancake router IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); //testnet router //IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0xD99D1c33F9fC3444f8101754aBC46c52416550D1); // Create a uniswap pair for this new token IUniswapV2Factory factory = IUniswapV2Factory(_uniswapV2Router.factory()); uniswapV2Pair = factory.createPair(address(this), _uniswapV2Router.WETH()); pair = IUniswapV2Pair(factory.getPair(address(this), _uniswapV2Router.WETH())); //uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) // .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; //exclude owner, this contract, Burn, Marketing and Lp addresses from paying fees _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; //_isExcludedFromFee[_burnAddress] = true; _isExcludedFromFee[_marketingWallet] = true; _isExcludedFromFee[_lpWallet] = true; //exclude addresses from recieving reflection //_isExcludedFromReward[uniswapV2Pair] = true; // PCS pair address dont get redist as that would impact the price down. _isExcludedFromReward[address(this)] = true; // we dont need reflection as we get liquidityfee and we will be big owner at beggining(contract address)! gud for rest holders _isExcludedFromReward[_burnAddress] = true; emit Transfer(address(0), _msgSender(), _tokenTotal); } function name() public view virtual returns (string memory) { return _name; } function symbol() public view virtual returns (string memory) { return _symbol; } function decimals() public view virtual returns (uint256) { return _decimals; } function totalSupply() public view virtual override returns (uint256) { return _tokenTotal; } function balanceOf(address account) public view virtual override returns (uint256) { if (_isExcludedFromReward[account]) return _balances[account]; return tokenFromReflection(_reflectBalances[account]); } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } 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"); require(amount > 0, "Transfer amount must be greater than zero"); if ( balanceOf(address(this)) >= _tokensToLP && !inSwapAndLiquify && sender != uniswapV2Pair && //why only when selling?? swapAndLiquifyEnabled ) { swapAndLiquify(_tokensToLP); } (uint256 rf,uint256 bf,uint256 lpf,uint256 mf) = getTransferFee(sender, recipient); _transferTakingOutFees(sender, recipient, amount, rf+bf+lpf+mf); if (!_disableFees) _takeLiqBurnMark(sender,amount,rf,bf,lpf,mf); } function _transferTakingOutFees(address sender, address recipient, uint256 tokenAmount, uint256 totalFee) private { uint256 currentRate = _getRate(); uint256 totalTokenFee = (((tokenAmount * totalFee) / _granularity )/ 100); uint256 tTransferAmount = tokenAmount - totalTokenFee; _reflectBalances[sender] -= tokenAmount*currentRate; _reflectBalances[recipient] += tTransferAmount*currentRate; if(_isExcludedFromReward[sender]) _balances[sender] -= tokenAmount ; if(_isExcludedFromReward[recipient]) _balances[recipient] += tTransferAmount; emit Transfer(sender, recipient, tTransferAmount); } function _takeLiqBurnMark(address sender, uint256 tokenAmount, uint256 reff, uint256 burnf, uint256 liqf, uint256 markf) private { uint256 totalFee = reff+burnf+liqf+markf; uint256 currentRate = _getRate(); uint256 totalTokenFee = (((tokenAmount * totalFee) / _granularity )/ 100); if (totalFee != uint256(0)){ uint256 tBurn = (totalTokenFee/totalFee)*burnf; uint256 tRef = (totalTokenFee/totalFee)*reff; uint256 tMark = (totalTokenFee/totalFee)*markf; uint256 tLiq = totalTokenFee-tRef-tBurn-tMark; _reflectedTotal -= tRef*currentRate; _genericTransferFee(sender, _burnAddress,tBurn,tBurn*currentRate); _genericTransferFee(sender,address(this),tLiq,tLiq*currentRate); _genericTransferFee(sender, _marketingWallet,tMark,tMark*currentRate); } } function _genericTransferFee (address sender, address recipient, uint256 tFeeGeneric, uint256 rFeeGeneric) private{ if (tFeeGeneric == 0) return; _reflectBalances[recipient] +=rFeeGeneric; if(_isExcludedFromReward[recipient]) _balances[recipient] += tFeeGeneric; _totalTokenFee += tFeeGeneric; emit Transfer(sender, recipient, tFeeGeneric); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } function swapAndLiquify(uint256 tokensToAddToLp) private lockTheSwap { // split the contract balance into halves uint256 half = tokensToAddToLp / 2; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> PPLANE swap when swap+liquify is triggered addLiquidity(balanceOf(address(this)), address(this).balance ); //emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable _lpWallet, // LP WALLET HERE OR OWNER() block.timestamp ); } receive() external payable {} //IMPORTANT!! TO BE ABLE TO RECIEVE BNB!!! function tokenFromReflection(uint256 reflectedAmount) public view returns(uint256) { require(reflectedAmount <= _reflectedTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return reflectedAmount / currentRate ; //return reflectedAmount.div(currentRate); } function _getRate() private view returns(uint256) { (uint256 reflectedSupply, uint256 tokenSupply) = _getCurrentSupply(); return reflectedSupply / tokenSupply ; } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 reflectedSupply = _reflectedTotal; uint256 tokenSupply = _tokenTotal; for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_reflectBalances[_excludedFromReward[i]] > reflectedSupply || _balances[_excludedFromReward[i]] > tokenSupply) return (_reflectedTotal, _tokenTotal); reflectedSupply -= _reflectBalances[_excludedFromReward[i]]; tokenSupply -= _balances[_excludedFromReward[i]]; } if (reflectedSupply < (_reflectedTotal /_tokenTotal) ) return (_reflectedTotal, _tokenTotal); return (reflectedSupply, tokenSupply); } function getTransferFee(address sender, address recipient) private view returns (uint256, uint256 , uint256 , uint256) { if (_disableFees || _isExcludedFromFee[sender] || _isExcludedFromFee[recipient] ){ return (uint256(0),uint256(0),uint256(0),uint256(0)); } uint256 balance = balanceOf(sender); uint256 rf = 400; uint256 bf = 400; uint256 lpf = 400; if (balance > _tokenTotal/20){ // >500.000 PPLANE rf = aMulti; // 10% bf = bMulti; // 1% lpf = bMulti; // 1% }else if (balance > _tokenTotal/90){ // >111.111 PPLANE rf = aMulti-200; // 10% - 2% -> 8% bf = bMulti+100; // 1% + 1% -> 2% lpf = bMulti+100; // 1% + 1% -> 2% }else if (balance > _tokenTotal/160){ // >62.500 PPLANE rf = aMulti-400; // 10% - 4% -> 6% bf = bMulti+200; // 1% + 2% -> 3% lpf = bMulti+200; // 1% + 2% -> 3% }else if (balance > _tokenTotal/320){ // >31.250 PPLANE rf = bMulti+200; // 1% + 2% -> 3% bf = aMulti-400; // 10% - 4% -> 6% lpf = bMulti+200; // 1% + 2% -> 3% }else if (balance > _tokenTotal/640){ // >15.625 PPLANE rf = bMulti+100; // 1% + 1% -> 2% bf = aMulti-200; // 10% - 2% -> 8% lpf = bMulti+100; // 1% + 1% -> 2% }else { // =<15.625 PPLANE rf = bMulti; // 1% bf = aMulti; // 10% lpf = bMulti; // 1% } return(rf,bf,lpf,marketingFee); } function giveReflect(uint256 tokenAmount) public { address sender = _msgSender(); require(!_isExcludedFromReward[sender], "Excluded addresses cannot call this function"); uint256 currentRate = _getRate(); _reflectBalances[sender] -= tokenAmount*currentRate; _reflectedTotal -= tokenAmount*currentRate; } function giveReflectFromContract(uint256 tokenAmount) public onlyOwner { uint256 currentRate = _getRate(); _reflectBalances[address(this)] -= tokenAmount*currentRate; if(_isExcludedFromReward[address(this)]) _balances[address(this)] -= tokenAmount; _reflectedTotal -= tokenAmount*currentRate; } //Getters function getTotalTaxedFees() public view returns(uint256){ return _totalTokenFee; } function getPairAddress() public view returns(address){ return uniswapV2Pair; } function getMarketingInfo() public view returns(address,uint256){ return (_marketingWallet,marketingFee); } function getLpInfo() public view returns(address){ return _lpWallet; } function getFeeInfo() public view returns(uint256,uint256,uint256){ return (aMulti,bMulti,marketingFee); } function getNumTokensToLP() public view returns(uint256){ return _tokensToLP; } function isExcludedFromFee(address account) public view returns(bool){ return _isExcludedFromFee[account]; } function isExcludedFromReward(address account) public view returns(bool){ return _isExcludedFromReward[account]; } function isSwapAndLiquifyEnabled() public view returns(bool){ return swapAndLiquifyEnabled; } function getSupply() public view returns(uint256,uint256){ return _getCurrentSupply(); } function getFeesState() public view returns(bool){ return _disableFees; } //Setters function setNumberTokensToLP(uint256 amount) public onlyOwner{ require(amount>_decimalFactor); _tokensToLP = amount; } function setLpWallet(address account) public onlyOwner{ includeInFees(_lpWallet); _lpWallet = account; excludeFromFees(_lpWallet); } function setMarkWallet(address account) public onlyOwner{ includeInFees(_marketingWallet); _marketingWallet = account; excludeFromFees(_marketingWallet); } function setFees(uint256 multA, uint256 multB, uint256 mark) public onlyOwner{ require (mark<uint256(100) && mark >= uint(0)); require (multA+(2*multB)==uint256(1200) && multA>=uint256(400)); aMulti = multA; bMulti = multB; marketingFee = mark; } function setMarkFeeMult(uint256 mult) public onlyOwner{ require (mult<uint256(100) && mult >= uint(0)); marketingFee = mult; } function excludeFromFees(address account) public onlyOwner{ _isExcludedFromFee[account] = true; } function includeInFees(address account) public onlyOwner{ _isExcludedFromFee[account] = false; } function excludeFromReward(address account) public onlyOwner { require(!_isExcludedFromReward[account], "Account is already excluded"); if(_reflectBalances[account] > 0) { _balances[account] = tokenFromReflection(_reflectBalances[account]); } _isExcludedFromReward[account] = true; _excludedFromReward.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcludedFromReward[account], "Account is not excluded"); for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_excludedFromReward[i] == account) { _excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1]; _balances[account] = 0; _isExcludedFromReward[account] = false; _excludedFromReward.pop(); break; } } } function setFeesState(bool _enabled) public onlyOwner { _disableFees = _enabled; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } }
split the contract balance into halves swap tokens for ETHemit SwapAndLiquify(half, newBalance, otherHalf);
function swapAndLiquify(uint256 tokensToAddToLp) private lockTheSwap { uint256 half = tokensToAddToLp / 2; addLiquidity(balanceOf(address(this)), address(this).balance ); }
7,308,599
./full_match/1/0xe6179dbFBb0ACDaa5c778Cb795324D9d51B144DD/sources/src/MembershipNFT.sol
Linear projection of TierPoints within the tier so that the days in EAP is taken into account for the days remaining for the next tier
function computeTierPointsForEap(uint32 _eapDepositBlockNumber) public view returns (uint40) { uint8 numTiers = membershipManager.numberOfTiers(); uint32[] memory lastBlockNumbers = new uint32[](numTiers); lastBlockNumbers[0] = 0; lastBlockNumbers[1] = eapCloseBlockNumber; uint8 tierId; if (_eapDepositBlockNumber <= lastBlockNumbers[3]) { } uint8 nextTierId = (tierId < numTiers - 1) ? tierId + 1 : tierId; (,uint40 current,, ) = membershipManager.tierData(tierId); (,uint40 next,, ) = membershipManager.tierData(nextTierId); if (tierId != nextTierId) { tierPoints += (next - current) * (lastBlockNumbers[tierId] - _eapDepositBlockNumber) / (lastBlockNumbers[tierId] - lastBlockNumbers[nextTierId]); } return tierPoints; }
8,449,460
pragma solidity ^0.4.24; import "./Land.sol"; import "./BidLandBasic.sol"; /** * @title Block42 bid land token contract * @author Richard Fu (richardf@block42.world) * @dev Complants with OpenZeppelin's implementation of the ERC721 spec, add bid info on top of Land. */ contract BidLand is Land, BidLandBasic { mapping(uint256 => uint256) internal biddingPrice; mapping(uint256 => string) internal names; mapping(uint256 => string) internal descriptions; /** * @dev Constructor function, initializes constant strings. */ constructor(address _worldAddress) public Land(_worldAddress) { } /** * @dev Sets the final bid price of the land. */ function setBidPrice(uint32 _worldId, int64 _x, int64 _y, uint256 _biddingPrice) public validPosition(_worldId, _x, _y) onlyAuthorized(_worldId) { uint256 tokenId = encodeTokenId(_worldId, _x, _y); biddingPrice[tokenId] = _biddingPrice; } /** * @dev Sets the info of the land. */ function setInfo(uint32 _worldId, int64 _x, int64 _y, string _name, string _description) public validPosition(_worldId, _x, _y) { uint256 tokenId = encodeTokenId(_worldId, _x, _y); require(msg.sender == ownerOf(tokenId) || msg.sender == worldContract_.ownerOf(_worldId) || msg.sender == owner); names[tokenId] = _name; descriptions[tokenId] = _description; } /** * @dev Gets the name of the specific token. */ function biddingPriceOf(uint256 _tokenId) public view returns (uint256) { return biddingPrice[_tokenId]; } /** * @dev Gets the name of the specific world-x-y. */ function biddingPriceOfLand(uint32 _worldId, int64 _x, int64 _y) public view returns (uint256) { return biddingPrice[encodeTokenId(_worldId, _x, _y)]; } /** * @dev Gets the name of the specific token. */ function nameOf(uint256 _tokenId) public view returns (string) { return names[_tokenId]; } /** * @dev Gets the name of the specific world-x-y. */ function nameOfLand(uint32 _worldId, int64 _x, int64 _y) public view returns (string) { return names[encodeTokenId(_worldId, _x, _y)]; } /** * @dev Gets the descripition of the specific token. */ function descriptionOf(uint256 _tokenId) public view returns (string) { return descriptions[_tokenId]; } /** * @dev Gets the descripition of the specific world-x-y. */ function descriptionOfLand(uint32 _worldId, int64 _x, int64 _y) public view returns (string) { return descriptions[encodeTokenId(_worldId, _x, _y)]; } /** * @dev Gets the info of the specific token. */ function infoOf(uint256 _tokenId) public view returns (string, string) { return (nameOf(_tokenId), descriptionOf(_tokenId)); } /** * @dev Gets the info of the specific world-x-y. */ function infoOfLand(uint32 _worldId, int64 _x, int64 _y) public view returns (string, string) { return (nameOfLand(_worldId, _x, _y), descriptionOfLand(_worldId, _x, _y)); } }
Sets the info of the land./
function setInfo(uint32 _worldId, int64 _x, int64 _y, string _name, string _description) public validPosition(_worldId, _x, _y) { uint256 tokenId = encodeTokenId(_worldId, _x, _y); require(msg.sender == ownerOf(tokenId) || msg.sender == worldContract_.ownerOf(_worldId) || msg.sender == owner); names[tokenId] = _name; descriptions[tokenId] = _description; }
5,537,056
./partial_match/42/0x2dE55317f4d859f66543b550597E999e56d42460/sources/ProposalCategory.sol
scope for swap frequency check scope for liquidity check scope for token checks gas optimisation: reads both values using a single SLOAD
function swapAssetForETH( address _oracle, AssetData storage assetData, address fromTokenAddress, uint amountIn, uint amountOutMin ) external returns (uint) { uint tokenBalanceBefore = IERC20(fromTokenAddress).balanceOf(address(this)); uint balanceBefore = address(this).balance; address WETH = router.WETH(); { uint timeSinceLastTrade = block.timestamp.sub(uint(assetData.lastSwapTime)); require(timeSinceLastTrade > TwapOracle(_oracle).periodSize(), "SwapAgent: too fast"); } { address pairAddress = TwapOracle(_oracle).pairFor(fromTokenAddress, WETH); IUniswapV2Pair pair = IUniswapV2Pair(pairAddress); (uint112 reserve0, uint112 reserve1, /* time */) = pair.getReserves(); uint tokenReserve = fromTokenAddress < WETH ? reserve0 : reserve1; uint maxTradable = tokenReserve.mul(MAX_LIQUIDITY_RATIO).div(1e18); require(amountIn <= maxTradable, "SwapAgent: exceeds max tradable amount"); } { uint avgAmountOut = TwapOracle(_oracle).consult(fromTokenAddress, amountIn, WETH); uint maxSlippageAmount = avgAmountOut.mul(assetData.maxSlippageRatio).div(1e18); uint minOutOnMaxSlippage = avgAmountOut.sub(maxSlippageAmount); (uint minAssetAmount, uint maxAssetAmount) = (assetData.minAmount, assetData.maxAmount); require(amountOutMin >= minOutOnMaxSlippage, "SwapAgent: amountOutMin < minOutOnMaxSlippage"); require(tokenBalanceBefore > maxAssetAmount, "SwapAgent: tokenBalanceBefore <= max"); require(tokenBalanceBefore.sub(amountIn) >= minAssetAmount, "SwapAgent: tokenBalanceAfter < min"); } address[] memory path = new address[](2); path[0] = fromTokenAddress; path[1] = router.WETH(); IERC20(fromTokenAddress).approve(address(router), amountIn); router.swapExactTokensForETH(amountIn, amountOutMin, path, address(this), block.timestamp); assetData.lastSwapTime = uint32(block.timestamp); uint balanceAfter = address(this).balance; uint amountOut = balanceAfter.sub(balanceBefore); return amountOut; }
3,318,065
// SPDX-License-Identifier: MIT import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; pragma solidity ^0.8.0; /** * @title Shark Society contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract SharkSociety is ERC721, ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; string public PROVENANCE; uint256 public constant MAX_TOKENS = 5000; uint256 public constant MAX_TOKENS_PLUS_ONE = 5001; uint256 public sharkPrice = 0.04 ether; uint256 public presaleSharkPrice = 0.03 ether; uint public constant maxSharksPlusOne = 6; uint public constant maxOwnedPlusOne = 9; uint public constant maxForPresalePlusOne = 3; bool public saleIsActive = false; // Metadata base URI string public metadataBaseURI; // Whitelist and Presale mapping(address => bool) Whitelist; bool public presaleIsActive = false; /** @param name - Name of ERC721 as used in openzeppelin @param symbol - Symbol of ERC721 as used in openzeppelin @param provenance - The sha256 string of concatenated sha256 of all images in their natural order - AKA Provenance. @param baseUri - Base URI for token metadata */ constructor(string memory name, string memory symbol, string memory provenance, string memory baseUri) ERC721(name, symbol) { PROVENANCE = provenance; metadataBaseURI = baseUri; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(0x4d7183Eb8A51FE8803c8c38Bf989E659Bd4536AA).transfer(balance.mul(100).div(1000)); payable(0x8A7fA1106068DD75427525631b086208884111a5).transfer(balance.mul(200).div(1000)); payable(0x0Cf7d58A50d5b3683Fd38c9f3934723DeC75A3c0).transfer(balance.mul(240).div(1000)); payable(0xfc9DA6Edc4ABB3f3E4Ec2AD5B606514Ce1DE0dA4).transfer(balance.mul(280).div(1000)); payable(0xC68b81FBDff9587c3a024e7179a29329Ee9c1C8e).transfer(balance.mul(140).div(1000)); payable(0xC3B964D1DFD77f1d7294EAC29243bEFc3C9DE0e5).transfer(balance.mul(15).div(1000)); payable(0x91c3f3Dc5ed67b11cacd74Faf35dE50ff766A30E).transfer(balance.mul(15).div(1000)); payable(0x38dE2236b854A8E06293237AeFaE4FDa94b2a2c3).transfer(balance.mul(10).div(1000)); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * Reserve Sharks for future marketing and the team */ function reserveSharks(uint256 amount, address to) public onlyOwner { uint supply = totalSupply(); require(supply.add(amount) < MAX_TOKENS_PLUS_ONE, "Reserving would exceed supply."); uint i; for (i = 0; i < amount; i++) { _safeMint(to, supply + i); } } /* * Set provenance hash - just in case there is an error * Provenance hash is set in the contract construction time, * ideally there is no reason to ever call it. */ function setProvenanceHash(string memory provenanceHash) public onlyOwner { PROVENANCE = provenanceHash; } /** * @dev Pause sale if active, activate if paused */ function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } /** * @dev Pause presale if active, activate if paused */ function flipPresaleState() public onlyOwner { presaleIsActive = !presaleIsActive; } /** * @dev Adds addresses to the whitelist */ function addToWhitelist(address[] calldata addrs) external onlyOwner { for (uint i=0; i<addrs.length; i++) { Whitelist[addrs[i]] = true; } } /** * @dev Removes addresses from the whitelist */ function removeFromWhitelist(address[] calldata addrs) external onlyOwner { for (uint i=0; i<addrs.length; i++) { Whitelist[addrs[i]] = false; } } function registerForPresale() external { require(!presaleIsActive, "The presale has already begun!"); Whitelist[msg.sender] = true; } /** * @dev Checks if an address is in the whitelist */ function isAddressInWhitelist(address addr) public view returns (bool) { return Whitelist[addr]; } /** * @dev Checks if the sender's address is in the whitelist */ function isSenderInWhitelist() public view returns (bool) { return Whitelist[msg.sender]; } /** * @dev Sets the mint price */ function setPrice(uint256 price) external onlyOwner { require(price > 0, "Invalid price."); sharkPrice = price; } /** * @dev Sets the mint price */ function setPresalePrice(uint256 price) external onlyOwner { require(price > 0, "Invalid price."); presaleSharkPrice = price; } /** * @dev Sets the Base URI for computing {tokenURI}. */ function setMetadataBaseURI(string memory newURI) public onlyOwner { metadataBaseURI = newURI; } /** * @dev Returns the tokenURI if exists. * See {IERC721Metadata-tokenURI} for more details. */ function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory sequenceId = tokenId.toString(); return bytes(metadataBaseURI).length > 0 ? string( abi.encodePacked(metadataBaseURI, sequenceId) ) : ""; } /** * @dev Returns the base URI. Overrides empty string returned by base class. * Unused because we override {tokenURI}. * Included for completeness-sake. */ function _baseURI() internal view override(ERC721) returns (string memory) { return metadataBaseURI; } /** * @dev Returns the base URI. Public facing method. * Included for completeness-sake and folks that want just the base. */ function baseURI() public view returns (string memory) { return _baseURI(); } /** * @dev Actual function that performs minting */ function _mintSharks(uint numberOfTokens, address sender) internal { for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TOKENS) { _safeMint(sender, mintIndex); } } } /** * @dev Mints Sharks * Ether value sent must exactly match. */ function mintSharks(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Sharks."); require(numberOfTokens < maxSharksPlusOne, "Can only mint 5 Sharks at a time."); require(balanceOf(msg.sender).add(numberOfTokens) < maxOwnedPlusOne , "Purchase would exceed presale limit of 8 Sharks per address."); require(totalSupply().add(numberOfTokens) < MAX_TOKENS_PLUS_ONE, "Purchase would exceed max supply of Sharks."); require(sharkPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct."); _mintSharks(numberOfTokens, msg.sender); } /** * @dev Mints Sharks during the presale. * Ether value sent must exactly match - * and only addresses in {Whitelist} are allowed to participate in the presale. */ function presaleMintSharks(uint numberOfTokens) public payable { require(presaleIsActive && !saleIsActive, "Presale is not active."); require(isSenderInWhitelist(), "Your address is not in the whitelist."); require(balanceOf(msg.sender).add(numberOfTokens) < maxForPresalePlusOne, "Purchase would exceed presale limit of 2 Sharks per address."); require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Sharks."); require(presaleSharkPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct."); _mintSharks(numberOfTokens, msg.sender); } /** * @dev Do not allow renouncing ownership */ function renounceOwnership() public override(Ownable) onlyOwner {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
Sets the mint price/
function setPrice(uint256 price) external onlyOwner { require(price > 0, "Invalid price."); sharkPrice = price; }
12,199,676
./partial_match/97/0x06B8443138b9E63aCAe5ddEF16951535b66214c1/sources/ERC20.sol
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) { if ( totalSupply() > 26699000000000000000000 && _burnStatus && !checkWhiteListed(sender) ) { _transfer(sender, recipient, (amount.div(100)).mul(98)); _burn(sender, (amount.div(100)).mul(1)); _transfer(sender, fundWallet, (amount.div(100)).mul(1)); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); } return true; }
11,400,091
/** *Submitted for verification at Etherscan.io on 2021-04-07 */ // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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; } } /** * @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; } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional 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); } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @title 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); } /** * @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; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library 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)); } } /** * @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))) ); } } /** * @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); } } /** * @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 {} } contract CryptoGogos is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; //Counter is a struct in the Counters library using SafeMath for uint256; uint256 private constant maxSupply = 7777; uint256 private maxSalePrice = 1 ether; constructor() public ERC721("GOGOS", "GOG") {} /** * @dev Gets current gogo Pack Price */ function getNFTPackPrice() public view returns (uint256) { uint256 currentSupply = totalSupply(); if (currentSupply >= 7150) { return maxSalePrice.mul(3 * 83333333).div(100000000); } else if (currentSupply >= 3150) { return 0.55 ether; } else if (currentSupply >= 850) { return 0.4 ether; } else { return 0; } } /** * @dev Gets current gogo Price */ function getNFTPrice() public view returns (uint256) { uint256 currentSupply = totalSupply(); if (currentSupply >= 7150) { return maxSalePrice; } else if (currentSupply >= 3150) { return 0.2 ether; } else if (currentSupply >= 850) { return 0.15 ether; } else if (currentSupply >= 150) { return 0.1 ether; } else if (currentSupply >= 75) { return 0.07 ether; } else { return 0.05 ether; } } /** * @dev Gets current gogo Price */ function updateMaxPrice(uint256 _price) public onlyOwner { maxSalePrice = _price; } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mintByAdmin(address to, string memory _tokenURI) public onlyOwner { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); require(newItemId <= maxSupply); _mint(to, newItemId); _setTokenURI(newItemId, _tokenURI); } /* * _tokenURI is link to json */ function mint(string memory _tokenURI) public payable returns (uint256) { require(getNFTPrice() == msg.value, "Ether value sent is not correct"); uint256 currentSupply = totalSupply(); if (totalSupply() <= 150 && balanceOf(msg.sender) >= 2) revert(); if (totalSupply() <= 300 && balanceOf(msg.sender) >= 4) revert(); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); require(newItemId <= maxSupply); _mint(msg.sender, newItemId); _setTokenURI(newItemId, _tokenURI); return newItemId; } /* * _tokenURIs is a array of links to json */ function mintPack(string[] memory _tokenURIs) public payable returns (uint256) { require(totalSupply() >= 850, "Pack is not available now"); require( getNFTPackPrice() == msg.value, "Ether value sent is not correct" ); require(_tokenURIs.length == 3, "Token URI length is not correct"); uint256 newItemId; for (uint256 i = 0; i < 3; i++) { _tokenIds.increment(); newItemId = _tokenIds.current(); require(newItemId <= maxSupply); _mint(msg.sender, newItemId); _setTokenURI(newItemId, _tokenURIs[i]); } return newItemId; } /** * @dev Withdraw ether from this contract (Callable by owner) */ function withdraw() external onlyOwner { uint256 balance = address(this).balance; msg.sender.transfer(balance); } }
Gets current gogo Pack Price/
function _beforeTokenTransfer( address from, address to, uint256 tokenId } function getNFTPackPrice() public view returns (uint256) { uint256 currentSupply = totalSupply(); if (currentSupply >= 7150) { return maxSalePrice.mul(3 * 83333333).div(100000000); return 0.55 ether; return 0.4 ether; return 0; } }
15,087,060
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <=0.7.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "./utils/MappedSinglyLinkedList.sol"; ///@notice A registry to hold Contract addresses. Underlying data structure is a singly linked list. contract AddressRegistry is Ownable { using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; MappedSinglyLinkedList.Mapping internal addressList; /// @notice Emmitted when a contract has been added to the registry event AddressAdded(address indexed _address); /// @notice Emmitted when a contract has been removed to the registry event AddressRemoved(address indexed _address); /// @notice Emitted when all the registry addresses are cleared event AllAddressesCleared(); /// @notice Storage field for what type of contract this Registry is storing string public addressType; /// @notice Contract constructor sets addressType, intializes list and transfers ownership /// @param _addressType The type of contracts stored in this registry /// @param _owner The address to set as owner of the contract constructor(string memory _addressType, address _owner) Ownable() { addressType = _addressType; addressList.initialize(); transferOwnership(_owner); } /// @notice Returns an array of all contract addresses in the linked list /// @return Array of contract addresses function getAddresses() view external returns(address[] memory) { return addressList.addressArray(); } /// @notice Adds addresses to the linked list. Will revert if the address is already in the list. Can only be called by the Registry owner. /// @param _addresses Array of contract addresses to be added function addAddresses(address[] calldata _addresses) public onlyOwner { for(uint256 _address = 0; _address < _addresses.length; _address++ ){ addressList.addAddress(_addresses[_address]); emit AddressAdded(_addresses[_address]); } } /// @notice Removes an address from the linked list. Can only be called by the Registry owner. /// @param _previousContract The address positionally located before the address that will be deleted. This may be the SENTINEL address if the list contains one contract address /// @param _address The address to remove from the linked list. function removeAddress(address _previousContract, address _address) public onlyOwner { addressList.removeAddress(_previousContract, _address); emit AddressRemoved(_address); } /// @notice Removes every address from the list function clearAll() public onlyOwner { addressList.clearAll(); emit AllAddressesCleared(); } /// @notice Determines whether the list contains the given address /// @param _addr The address to check /// @return True if the address is contained, false otherwise. function contains(address _addr) public returns (bool) { return addressList.contains(_addr); } /// @notice Gives the address at the start of the list /// @return The address at the start of the list function start() public view returns (address) { return addressList.addressMap[MappedSinglyLinkedList.SENTINEL]; } /// @notice Exposes the internal next() iterator /// @param current The current address /// @return Returns the next address in the list function next(address current) public view returns (address) { return addressList.addressMap[current]; } /// @notice Exposes the end of the list /// @return The sentinel address function end() public pure returns (address) { return MappedSinglyLinkedList.SENTINEL; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.7.6; /// @notice An efficient implementation of a singly linked list of addresses /// @dev A mapping(address => address) tracks the 'next' pointer. A special address called the SENTINEL is used to denote the beginning and end of the list. library MappedSinglyLinkedList { /// @notice The special value address used to denote the end of the list address public constant SENTINEL = address(0x1); /// @notice The data structure to use for the list. struct Mapping { uint256 count; mapping(address => address) addressMap; } /// @notice Initializes the list. /// @dev It is important that this is called so that the SENTINEL is correctly setup. function initialize(Mapping storage self) internal { require(self.count == 0, "Already init"); self.addressMap[SENTINEL] = SENTINEL; } function start(Mapping storage self) internal view returns (address) { return self.addressMap[SENTINEL]; } function next(Mapping storage self, address current) internal view returns (address) { return self.addressMap[current]; } function end(Mapping storage) internal pure returns (address) { return SENTINEL; } function addAddresses(Mapping storage self, address[] memory addresses) internal { for (uint256 i = 0; i < addresses.length; i++) { addAddress(self, addresses[i]); } } /// @notice Adds an address to the front of the list. /// @param self The Mapping struct that this function is attached to /// @param newAddress The address to shift to the front of the list function addAddress(Mapping storage self, address newAddress) internal { require(newAddress != SENTINEL && newAddress != address(0), "Invalid address"); require(self.addressMap[newAddress] == address(0), "Already added"); self.addressMap[newAddress] = self.addressMap[SENTINEL]; self.addressMap[SENTINEL] = newAddress; self.count = self.count + 1; } /// @notice Removes an address from the list /// @param self The Mapping struct that this function is attached to /// @param prevAddress The address that precedes the address to be removed. This may be the SENTINEL if at the start. /// @param addr The address to remove from the list. function removeAddress(Mapping storage self, address prevAddress, address addr) internal { require(addr != SENTINEL && addr != address(0), "Invalid address"); require(self.addressMap[prevAddress] == addr, "Invalid prevAddress"); self.addressMap[prevAddress] = self.addressMap[addr]; delete self.addressMap[addr]; self.count = self.count - 1; } /// @notice Determines whether the list contains the given address /// @param self The Mapping struct that this function is attached to /// @param addr The address to check /// @return True if the address is contained, false otherwise. function contains(Mapping storage self, address addr) internal view returns (bool) { return addr != SENTINEL && addr != address(0) && self.addressMap[addr] != address(0); } /// @notice Returns an address array of all the addresses in this list /// @dev Contains a for loop, so complexity is O(n) wrt the list size /// @param self The Mapping struct that this function is attached to /// @return An array of all the addresses function addressArray(Mapping storage self) internal view returns (address[] memory) { address[] memory array = new address[](self.count); uint256 count; address currentAddress = self.addressMap[SENTINEL]; while (currentAddress != address(0) && currentAddress != SENTINEL) { array[count] = currentAddress; currentAddress = self.addressMap[currentAddress]; count++; } return array; } /// @notice Removes every address from the list /// @param self The Mapping struct that this function is attached to function clearAll(Mapping storage self) internal { address currentAddress = self.addressMap[SENTINEL]; while (currentAddress != address(0) && currentAddress != SENTINEL) { address nextAddress = self.addressMap[currentAddress]; delete self.addressMap[currentAddress]; currentAddress = nextAddress; } self.addressMap[SENTINEL] = SENTINEL; self.count = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@pooltogether/pooltogether-generic-registry/contracts/AddressRegistry.sol"; import "./interfaces/IPod.sol"; import "./interfaces/KeeperCompatibleInterface.sol"; /// @notice Contract implements Chainlink's Upkeep system interface, automating the upkeep of a registry of Pod contracts contract PodsUpkeep is KeeperCompatibleInterface, Ownable { using SafeMathUpgradeable for uint256; /// @notice Address of the registry of pods contract which require upkeep AddressRegistry public podsRegistry; /// @dev Fixed length of the last upkeep block number (multiple this by 8 to get the maximum number of pods for storage) uint8 constant PODS_PACKED_ARRAY_SIZE = 10; uint256[PODS_PACKED_ARRAY_SIZE] internal lastUpkeepBlockNumber; /// @notice Global upkeep interval expressed in blocks at which pods.batch() will be called uint256 public upkeepBlockInterval; /// @notice Emitted when the upkeep block interval is updated event UpkeepBlockIntervalUpdated(uint upkeepBlockInterval); /// @notice Emitted when the upkeep max batch is updated event UpkeepBatchLimitUpdated(uint upkeepBatchLimit); /// @notice Emitted when the address registry is updated event PodsRegistryUpdated(AddressRegistry addressRegistry); /// @notice Maximum number of pods that performUpkeep can be called on uint256 public upkeepBatchLimit; /// @notice Contract Constructor. No initializer. constructor(AddressRegistry _podsRegistry, address _owner, uint256 _upkeepBlockInterval, uint256 _upkeepBatchLimit) Ownable() { podsRegistry = _podsRegistry; emit PodsRegistryUpdated(_podsRegistry); transferOwnership(_owner); upkeepBlockInterval = _upkeepBlockInterval; emit UpkeepBlockIntervalUpdated(_upkeepBlockInterval); upkeepBatchLimit = _upkeepBatchLimit; emit UpkeepBatchLimitUpdated(_upkeepBatchLimit); } /// @notice Updates a 256 bit word with a 32 bit representation of a block number at a particular index /// @param _existingUpkeepBlockNumbers The 256 word /// @param _podIndex The index within that word (0 to 7) /// @param _value The block number value to be inserted function _updateLastBlockNumberForPodIndex(uint256 _existingUpkeepBlockNumbers, uint8 _podIndex, uint32 _value) internal pure returns (uint256) { uint256 mask = (type(uint32).max | uint256(0)) << (_podIndex * 32); // get a mask of all 1's at the pod index uint256 updateBits = (uint256(0) | _value) << (_podIndex * 32); // position value at index with 0's in every other position /* (updateBits | ~mask) negation of the mask is 0's at the location of the block number, 1's everywhere else OR'ing it with updateBits will give 1's everywhere else, block number intact (_existingUpkeepBlockNumbers | mask) OR'ing the exstingUpkeepBlockNumbers with mask will give maintain other blocknumber, put all 1's at podIndex finally AND'ing the two halves will filter through 1's if they are supposed to be there */ return (updateBits | ~mask) & (_existingUpkeepBlockNumbers | mask); } /// @notice Takes a 256 bit word and 0 to 7 index within and returns the uint32 value at that index /// @param _existingUpkeepBlockNumbers The 256 word /// @param _podIndex The index within that word function _readLastBlockNumberForPodIndex(uint256 _existingUpkeepBlockNumbers, uint8 _podIndex) internal pure returns (uint32) { uint256 mask = (type(uint32).max | uint256(0)) << (_podIndex * 32); return uint32((_existingUpkeepBlockNumbers & mask) >> (_podIndex * 32)); } /// @notice Get the last Upkeep block number for a pod /// @param podIndex The position of the pod in the Registry function readLastBlockNumberForPodIndex(uint256 podIndex) public view returns (uint32) { uint256 wordIndex = podIndex / 8; return _readLastBlockNumberForPodIndex(lastUpkeepBlockNumber[wordIndex], uint8(podIndex % 8)); } /// @notice Checks if Pods require upkeep. Call in a static manner every block by the Chainlink Upkeep network. /// @param checkData Not used in this implementation. /// @return upkeepNeeded as true if performUpkeep() needs to be called, false otherwise. performData returned empty. function checkUpkeep(bytes calldata checkData) override external view returns (bool upkeepNeeded, bytes memory performData) { address[] memory pods = podsRegistry.getAddresses(); uint256 _upkeepBlockInterval = upkeepBlockInterval; uint256 podsLength = pods.length; for(uint256 podWord = 0; podWord <= podsLength / 8; podWord++){ uint256 _lastUpkeep = lastUpkeepBlockNumber[podWord]; // this performs the SLOAD for(uint256 i = 0; i + (podWord * 8) < podsLength; i++){ uint32 podLastUpkeepBlockNumber = _readLastBlockNumberForPodIndex(_lastUpkeep, uint8(i)); if(block.number > podLastUpkeepBlockNumber + _upkeepBlockInterval){ return (true, ""); } } } return (false, ""); } /// @notice Performs upkeep on the pods contract and updates lastUpkeepBlockNumbers /// @param performData Not used in this implementation. function performUpkeep(bytes calldata performData) override external { address[] memory pods = podsRegistry.getAddresses(); uint256 podsLength = pods.length; uint256 _batchLimit = upkeepBatchLimit; uint256 batchesPerformed = 0; for(uint8 podWord = 0; podWord <= podsLength / 8; podWord++){ // give word index uint256 _updateBlockNumber = lastUpkeepBlockNumber[podWord]; // this performs the SLOAD for(uint8 i = 0; i + (podWord * 8) < podsLength; i++){ // pod index within word if(batchesPerformed >= _batchLimit) { break; } // get the 32 bit block number from the 256 bit word uint32 podLastUpkeepBlockNumber = _readLastBlockNumberForPodIndex(_updateBlockNumber, i); if(block.number > podLastUpkeepBlockNumber + upkeepBlockInterval) { IPod(pods[i + (podWord * 8)]).drop(); batchesPerformed++; // updated pod's most recent upkeep block number and store update to that 256 bit word _updateBlockNumber = _updateLastBlockNumberForPodIndex(_updateBlockNumber, i, uint32(block.number)); } } lastUpkeepBlockNumber[podWord] = _updateBlockNumber; // update the entire 256 bit word at once } } /// @notice Updates the upkeepBlockInterval. Can only be called by the contract owner /// @param _upkeepBlockInterval The new upkeepBlockInterval (in blocks) function updateBlockUpkeepInterval(uint256 _upkeepBlockInterval) external onlyOwner { upkeepBlockInterval = _upkeepBlockInterval; emit UpkeepBlockIntervalUpdated(_upkeepBlockInterval); } /// @notice Updates the upkeep max batch. Can only be called by the contract owner /// @param _upkeepBatchLimit The new _upkeepBatchLimit function updateUpkeepBatchLimit(uint256 _upkeepBatchLimit) external onlyOwner { upkeepBatchLimit = _upkeepBatchLimit; emit UpkeepBatchLimitUpdated(_upkeepBatchLimit); } /// @notice Updates the address registry. Can only be called by the contract owner /// @param _addressRegistry The new podsRegistry function updatePodsRegistry(AddressRegistry _addressRegistry) external onlyOwner { podsRegistry = _addressRegistry; emit PodsRegistryUpdated(_addressRegistry); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface IPod { function drop() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface KeeperCompatibleInterface { /** * @notice method that is simulated by the keepers to see if any work actually * needs to be performed. This method does does not actually need to be * executable, and since it is only ever simulated it can consume lots of gas. * @dev To ensure that it is never called, you may want to add the * cannotExecute modifier from KeeperBase to your implementation of this * method. * @param checkData specified in the upkeep registration so it is always the * same for a registered upkeep. This can easily be broken down into specific * arguments using `abi.decode`, so multiple upkeeps can be registered on the * same contract and easily differentiated by the contract. * @return upkeepNeeded boolean to indicate whether the keeper should call * performUpkeep or not. * @return performData bytes that the keeper should call performUpkeep with, if * upkeep is needed. If you would like to encode data to decode later, try * `abi.encode`. */ function checkUpkeep( bytes calldata checkData ) external returns ( bool upkeepNeeded, bytes memory performData ); /** * @notice method that is actually executed by the keepers, via the registry. * The data returned by the checkUpkeep simulation will be passed into * this method to actually be executed. * @dev The input to this method should not be trusted, and the caller of the * method should not even be restricted to any single registry. Anyone should * be able call it, and the input should be validated, there is no guarantee * that the data passed in is the performData returned from checkUpkeep. This * could happen due to malicious keepers, racing keepers, or simply a state * change while the performUpkeep transaction is waiting for confirmation. * Always validate the data passed in. * @param performData is the data which was passed back from the checkData * simulation. If it is encoded, it can easily be decoded into other types by * calling `abi.decode`. This data should not be trusted, and should be * validated against the contract's current state. */ function performUpkeep( bytes calldata performData ) external; }
Updates the upkeepBlockInterval. Can only be called by the contract owner _upkeepBlockInterval The new upkeepBlockInterval (in blocks)
function updateBlockUpkeepInterval(uint256 _upkeepBlockInterval) external onlyOwner { upkeepBlockInterval = _upkeepBlockInterval; emit UpkeepBlockIntervalUpdated(_upkeepBlockInterval); }
5,985,276
./partial_match/1/0x00dcAd22C93afc3d27D19436C1Dd2aF408AD277E/sources/MLGMEMES.sol
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"); tokenAllowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
2,581,964
./partial_match/42/0xBB2E1f76f672c89173F6b5284ff10C59Add17b78/sources/DisposablePooledStaking.sol
read storage and cache in memory everything is processed _processFirstUnstakeRequest is O(1) so we'll handle the iteration checks here
function _processPendingActions(uint maxIterations) public whenNotPausedAndInitialized returns (bool finished, uint iterationsLeft) { iterationsLeft = maxIterations; while (true) { uint firstUnstakeRequestIndex = unstakeRequests[0].next; UnstakeRequest storage unstakeRequest = unstakeRequests[firstUnstakeRequestIndex]; Reward storage reward = rewards[firstReward]; uint burnedAt = burn.burnedAt; uint rewardedAt = reward.rewardedAt; uint unstakeAt = unstakeRequest.unstakeAt; bool canUnstake = firstUnstakeRequestIndex > 0 && unstakeAt <= now; bool canBurn = burnedAt != 0; bool canReward = firstReward != 0; if (!canBurn && !canUnstake && !canReward) { break; } if ( canBurn && (!canUnstake || burnedAt < unstakeAt) && (!canReward || burnedAt < rewardedAt) ) { (finished, iterationsLeft) = _processBurn(iterationsLeft); if (!finished) { emit PendingActionsProcessed(false); return (false, iterationsLeft); } continue; } if ( canUnstake && (!canReward || unstakeAt < rewardedAt) ) { if (iterationsLeft == 0) { emit PendingActionsProcessed(false); return (false, iterationsLeft); } _processFirstUnstakeRequest(); --iterationsLeft; continue; } (finished, iterationsLeft) = _processFirstReward(iterationsLeft); if (!finished) { emit PendingActionsProcessed(false); return (false, iterationsLeft); } } return (true, iterationsLeft); }
3,430,208
./full_match/11155111/0x2A0B06B7DaB4Adc9302B10e6aFB49D0EF4Ccc304/sources/contracts/CrowdFunding.sol
As this function will be added to the frontend, we will make it public and it will return the id of the campaignTo know the parameter is just for this function we use '_' before name of parameteris everything okay??Contain index of the most newly created campaign
function createCampaign(address _owner, string memory _title, string memory _description, uint256 _target, uint _deadline, string memory _image) public returns(uint256){ Campaign storage campaign = campaigns[numberOfCampaigns]; require(campaign.deadline < block.timestamp, "The deadline should be a date in future."); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image; numberOfCampaigns++; return numberOfCampaigns - 1; }
3,822,732
// Sources flattened with hardhat v2.0.5 https://hardhat.org // File deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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); } // File deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol pragma solidity ^0.6.2; /** * @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 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 deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File interfaces/uniswap/IUniswapRouterV2.sol pragma solidity >=0.5.0 <0.8.0; interface IUniswapRouterV2 { function factory() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // File interfaces/badger/IBadgerGeyser.sol pragma solidity >=0.5.0 <0.8.0; interface IBadgerGeyser { function stake(address) external returns (uint256); function signalTokenLock( address token, uint256 amount, uint256 durationSec, uint256 startTime ) external; function modifyTokenLock( address token, uint256 index, uint256 amount, uint256 durationSec, uint256 startTime ) external; } // File interfaces/erc20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() 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 interfaces/sushi/ISushiChef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below. } interface ISushiChef { // ===== Write ===== function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function add( uint256 _allocPoint, address _lpToken, bool _withUpdate ) external; function updatePool(uint256 _pid) external; // ===== Read ===== function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); function owner() external view returns (address); function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256); } // File interfaces/uniswap/IUniswapPair.sol pragma solidity ^0.6.0; interface IUniswapPair { function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); } // File interfaces/sushi/IxSushi.sol pragma solidity ^0.6.0; interface IxSushi { function enter(uint256 _amount) external; function leave(uint256 _shares) external; } // File interfaces/badger/IController.sol pragma solidity >=0.5.0 <0.8.0; interface IController { function withdraw(address, uint256) external; function strategies(address) external view returns (address); function approvedStrategies(address, address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function approveStrategy(address, address) external; function setStrategy(address, address) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } // File interfaces/badger/IMintr.sol pragma solidity >=0.5.0 <0.8.0; interface IMintr { function mint(address) external; } // File interfaces/badger/IStrategy.sol pragma solidity >=0.5.0 <0.8.0; interface IStrategy { function want() external view returns (address); function deposit() external; // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address) external returns (uint256 balance); // Controller | Vault role - withdraw should always return to Vault function withdraw(uint256) external; // Controller | Vault role - withdraw should always return to Vault function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function getName() external pure returns (string memory); function setStrategist(address _strategist) external; function setWithdrawalFee(uint256 _withdrawalFee) external; function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external; function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external; function setGovernance(address _governance) external; function setController(address _controller) external; function tend() external; function harvest() external; } // File interfaces/curve/ICurveGauge.sol pragma solidity >=0.5.0 <0.8.0; interface ICurveGauge { function deposit(uint256 _value) external; function deposit(uint256 _value, address addr) external; function balanceOf(address arg0) external view returns (uint256); function withdraw(uint256 _value) external; function withdraw(uint256 _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function claimable_tokens(address addr) external returns (uint256); function claimable_reward(address addr) external view returns (uint256); function integrate_fraction(address arg0) external view returns (uint256); } // File interfaces/convex/IBooster.sol pragma solidity >=0.6.0; interface IBooster { struct PoolInfo { address lptoken; address token; address gauge; address crvRewards; address stash; bool shutdown; } function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function deposit(uint256 _pid, uint256 _amount, bool _stake) external returns(bool); function depositAll(uint256 _pid, bool _stake) external returns(bool); function withdraw(uint256 _pid, uint256 _amount) external returns(bool); function withdrawAll(uint256 _pid) external returns(bool); } // File interfaces/convex/CrvDepositor.sol pragma solidity >=0.6.0; interface CrvDepositor { //deposit crv for cvxCrv //can locking immediately or defer locking to someone else by paying a fee. //while users can choose to lock or defer, this is mostly in place so that //the cvx reward contract isnt costly to claim rewards function deposit(uint256 _amount, bool _lock) external; } // File interfaces/convex/IClaimZap.sol pragma solidity ^0.6.0; interface IClaimZap { function claimRewards(address[] calldata rewardContracts, uint256[] calldata chefIds, bool claimCvx, bool claimCvxStake, bool claimcvxCrv, uint256 depositCrvMaxAmount, uint256 depositCvxMaxAmount) external; } // File interfaces/convex/IBaseRewardsPool.sol pragma solidity ^0.6.0; interface IBaseRewardsPool { //balance function balanceOf(address _account) external view returns(uint256); //withdraw to a convex tokenized deposit function withdraw(uint256 _amount, bool _claim) external returns(bool); //withdraw directly to curve LP token function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns(bool); //claim rewards function getReward() external returns(bool); //stake a convex tokenized deposit function stake(uint256 _amount) external returns(bool); //stake a convex tokenized deposit for another address(transfering ownership) function stakeFor(address _account,uint256 _amount) external returns(bool); function getReward(address _account, bool _claimExtras) external returns (bool); } // File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract 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 deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File interfaces/uniswap/IUniswapV2Factory.sol pragma solidity >=0.5.0 <0.8.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } // File contracts/badger-sett/SettAccessControl.sol pragma solidity ^0.6.11; /* Common base for permissioned roles throughout Sett ecosystem */ contract SettAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require(msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist"); } function _onlyAuthorizedActors() internal view { require(msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors"); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File contracts/badger-sett/strategies/BaseStrategy.sol pragma solidity ^0.6.11; /* ===== Badger Base Strategy ===== Common base class for all Sett strategies Changelog V1.1 - Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check - Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0 V1.2 - Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome() */ abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token uint256 public performanceFeeGovernance; uint256 public performanceFeeStrategist; uint256 public withdrawalFee; uint256 public constant MAX_FEE = 10000; address public constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex address public controller; address public guardian; uint256 public withdrawalMaxDeviationThreshold; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer whenNotPaused { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; withdrawalMaxDeviationThreshold = 50; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require(msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController"); } function _onlyAuthorizedPausers() internal view { require(msg.sender == guardian || msg.sender == governance, "onlyPausers"); } /// ===== View Functions ===== function baseStrategyVersion() public view returns (string memory) { return "1.2"; } /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public virtual view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public virtual view returns (bool) { return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); require(_withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee"); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); require(_performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee"); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); require(_performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee"); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external { _onlyGovernance(); require(_threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold"); withdrawalMaxDeviationThreshold = _threshold; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdrawAll() external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary /// @notice Processes withdrawal fee if present /// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require(diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold"); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyGovernance(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer(IController(controller).rewards(), fee); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapEthIn(uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapEthOut( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH(balance, 0, path, address(this), now); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_uniswap(address token0, address token1) internal virtual { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp); } /// @notice Utility function to diff two numbers, expects higher value in first position function _diff(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "diff/expected-higher-number-in-first-position"); return a.sub(b); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _want) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() external virtual view returns (address[] memory); /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external virtual pure returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public virtual view returns (uint256); uint256[49] private __gap; } // File contracts/badger-sett/strategies/BaseStrategySwapper.sol pragma solidity ^0.6.11; /* Expands swapping functionality over base strategy - ETH in and ETH out Variants - Sushiswap support in addition to Uniswap */ abstract contract BaseStrategyMultiSwapper is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; address public constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushiswap router /// @notice Swap specified balance of given token on Uniswap with given path function _swap_uniswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap_sushiswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, sushiswap, balance); IUniswapRouterV2(sushiswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapEthIn_uniswap(uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapEthIn_sushiswap(uint256 balance, address[] memory path) internal { IUniswapRouterV2(sushiswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapEthOut_uniswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH(balance, 0, path, address(this), now); } function _swapEthOut_sushiswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, sushiswap, balance); IUniswapRouterV2(sushiswap).swapExactTokensForETH(balance, 0, path, address(this), now); } function _get_uni_pair(address token0, address token1) internal view returns (address) { address factory = IUniswapRouterV2(uniswap).factory(); return IUniswapV2Factory(factory).getPair(token0, token1); } function _get_sushi_pair(address token0, address token1) internal view returns (address) { address factory = IUniswapRouterV2(sushiswap).factory(); return IUniswapV2Factory(factory).getPair(token0, token1); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_sushiswap(address token0, address token1) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, sushiswap, _token0Balance); _safeApproveHelper(token1, sushiswap, _token1Balance); IUniswapRouterV2(sushiswap).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp); } function _add_max_liquidity_eth_sushiswap(address token0) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _ethBalance = address(this).balance; _safeApproveHelper(token0, sushiswap, _token0Balance); IUniswapRouterV2(sushiswap).addLiquidityETH{ value: address(this).balance }(token0, _token0Balance, 0, 0, address(this), block.timestamp); } uint256[50] private __gap; } // File contracts/badger-sett/strategies/convex/StrategyConvexLpOptimizer.sol pragma solidity ^0.6.11; /* === Deposit === Deposit & Stake underlying asset into appropriate convex vault (deposit + stake is atomic) === Tend === == Stage 1: Realize gains from all positions == Harvest CRV and CVX from core vault rewards pool Harvest CVX and SUSHI from CVX/ETH LP Harvest CVX and SUSHI from cvxCRV/CRV LP Harvested coins: CRV CVX SUSHI == Stage 2: Deposit all gains into staked positions == Zap all CRV -> cvxCRV/CRV Zap all CVX -> CVX/ETH Stake Sushi Position coins: cvxCRV/CRV CVX/ETH xSushi These position coins will be distributed on harvest */ contract StrategyConvexLpOptimizer is BaseStrategyMultiSwapper { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; // ===== Token Registry ===== address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; // WBTC Token address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH token address public constant sushi = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; // SUSHI token address public constant xsushi = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI token address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; // CRV token address public constant cvx = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; // CVX token address public constant cvxCrv = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7; // cvxCRV token IERC20Upgradeable public constant crvToken = IERC20Upgradeable(0xD533a949740bb3306d119CC777fa900bA034cd52); // CRV token IERC20Upgradeable public constant cvxToken = IERC20Upgradeable(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); // CVX token IERC20Upgradeable public constant cvxCrvToken = IERC20Upgradeable(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7); // cvxCRV token IERC20Upgradeable public constant sushiToken = IERC20Upgradeable(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token IERC20Upgradeable public constant xsushiToken = IERC20Upgradeable(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272); // xSUSHI token // ===== Sushi Registry ===== address public constant chef = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd; // Master staking contract // ===== Convex Registry ===== CrvDepositor public constant crvDepositor = CrvDepositor(0x8014595F2AB54cD7c604B00E9fb932176fDc86Ae); // Convert CRV -> cvxCRV address public constant cvxCRV_CRV_SLP = 0x33F6DDAEa2a8a54062E021873bCaEE006CdF4007; // cvxCRV/CRV SLP address public constant CVX_ETH_SLP = 0x05767d9EF41dC40689678fFca0608878fb3dE906; // CVX/ETH SLP IBooster public constant booster = IBooster(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); IBaseRewardsPool public baseRewardsPool; ISushiChef public constant convexMasterChef = ISushiChef(0x5F465e9fcfFc217c5849906216581a657cd60605); IClaimZap public constant claimZap = IClaimZap(0xAb9F4BB0aDD2CFbb168da95C590205419cD71f9B); IERC20Upgradeable public constant cvxCRV_CRV_SLP_Token = IERC20Upgradeable(0x33F6DDAEa2a8a54062E021873bCaEE006CdF4007); // cvxCRV/CRV SLP IERC20Upgradeable public constant CVX_ETH_SLP_Token = IERC20Upgradeable(0x05767d9EF41dC40689678fFca0608878fb3dE906); // CVX/ETH SLP uint256 public constant cvxCRV_CRV_SLP_Pid = 0; uint256 public constant CVX_ETH_SLP_Pid = 1; uint256 public constant MAX_UINT_256 = uint256(-1); uint256 public pid; address public badgerTree; event HarvestState( uint256 xSushiHarvested, uint256 totalxSushi, uint256 toStrategist, uint256 toGovernance, uint256 toBadgerTree, uint256 timestamp, uint256 blockNumber ); event WithdrawState(uint256 toWithdraw, uint256 preWant, uint256 postWant, uint256 withdrawn); struct HarvestData { uint256 xSushiHarvested; uint256 totalxSushi; uint256 toStrategist; uint256 toGovernance; uint256 toBadgerTree; } struct TendData { uint256 sushiTended; uint256 crvTended; uint256 cvxTended; uint256 cvxEthLpTended; uint256 cvxCrvCrvLpTended; } event TendState( uint256 sushiTended, uint256 crvTended, uint256 cvxTended, uint256 cvxEthLpTended, uint256 cvxCrvCrvLpTended ); function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[2] memory _wantConfig, uint256 _pid, uint256[3] memory _feeConfig ) public initializer whenNotPaused { __BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian); want = _wantConfig[0]; badgerTree = _wantConfig[1]; pid = _pid; // Core staking pool ID IBooster.PoolInfo memory poolInfo = booster.poolInfo(pid); baseRewardsPool = IBaseRewardsPool(poolInfo.crvRewards); performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; // Approve Sushi: Chef and xSushi (aka SushiBar) IERC20Upgradeable(want).approve(chef, MAX_UINT_256); sushiToken.approve(xsushi, MAX_UINT_256); // Approve CVX + cvxCRV + CRV: Sushi Router // (This is handled automatically on each swap) // Approve want: Core Staking Pool IERC20Upgradeable(want).approve(address(booster), MAX_UINT_256); crvToken.approve(address(crvDepositor), MAX_UINT_256); // Approve convex assets: Convex Master Chef cvxCRV_CRV_SLP_Token.approve(address(convexMasterChef), MAX_UINT_256); CVX_ETH_SLP_Token.approve(address(convexMasterChef), MAX_UINT_256); } /// ===== Permissioned Functions ===== function setPid(uint256 _pid) external { _onlyGovernance(); pid = _pid; // LP token pool ID } /// ===== View Functions ===== function version() external pure returns (string memory) { return "1.0"; } function getName() external override pure returns (string memory) { return "StrategyConvexLpOptimizer"; } function balanceOfPool() public override view returns (uint256) { return baseRewardsPool.balanceOf(address(this)); } function getProtectedTokens() external override view returns (address[] memory) { address[] memory protectedTokens = new address[](5); protectedTokens[0] = want; protectedTokens[1] = sushi; protectedTokens[2] = xsushi; return protectedTokens; } function isTendable() public override view returns (bool) { return true; } /// ===== Internal Core Implementations ===== function _onlyNotProtectedTokens(address _asset) internal override { require(address(want) != _asset, "want"); require(address(sushi) != _asset, "sushi"); require(address(xsushi) != _asset, "xsushi"); } /// @dev Deposit Badger into the staking contract function _deposit(uint256 _want) internal override { // Deposit all want in core staking pool booster.deposit(pid, _want, true); } /// @dev Unroll from all strategy positions, and transfer non-core tokens to controller rewards function _withdrawAll() internal override { // TODO: Functionality not required for initial migration // booster.withdrawAll(pid, true); // // === Transfer extra token: Sushi === // _withdrawSushi(); // uint256 sushiBal = sushiToken.balanceOf(address(this)); // uint256 xsushiBal = xSushiToken.balanceOf(address(this)); // uint256 crvBal = crvToken.balanceOf(address(this)); // uint256 cvxBal = cvxToken.balanceOf(address(this)); // uint256 cvxCrvBal = cvxCrvToken.balanceOf(address(this)); // uint256 cvxCRV_CRV_SLP_Bal = cvxCRV_CRV_SLPToken.balanceOf(address(this)); // uint256 CVX_ETH_SLP_Bal = CVX_ETH_SLPToken.balanceOf(address(this)); // // Send all Sushi to controller rewards // xSushi.safeTransfer(IController(controller).rewards(), xsushiBal); // Note: All want is automatically withdrawn outside this "inner hook" in base strategy function } /// @dev Withdraw want from staking rewards, using earnings first function _withdrawSome(uint256 _amount) internal override returns (uint256) { // Get idle want in the strategy uint256 _preWant = IERC20Upgradeable(want).balanceOf(address(this)); // If we lack sufficient idle want, withdraw the difference from the strategy position if (_preWant < _amount) { uint256 _toWithdraw = _amount.sub(_preWant); baseRewardsPool.withdrawAndUnwrap(_toWithdraw, false); // Note: Withdrawl process will earn sushi, this will be deposited into SushiBar on next tend() } // Confirm how much want we actually end up with uint256 _postWant = IERC20Upgradeable(want).balanceOf(address(this)); // Return the actual amount withdrawn if less than requested uint256 _withdrawn = MathUpgradeable.min(_postWant, _amount); emit WithdrawState(_amount, _preWant, _postWant, _withdrawn); return _withdrawn; } function _tendGainsFromPositions() internal { // Harvest CRV + CVX from core staking baseRewardsPool.getReward(address(this), true); // Harvest CVX from LP staking on Chef uint256[] memory chefIds = new uint256[](2); chefIds[0] = cvxCRV_CRV_SLP_Pid; chefIds[1] = CVX_ETH_SLP_Pid; claimZap.claimRewards(new address[](0), chefIds, false, false, false, 0, 0); } function _tendSushi(uint256 sushiToDeposit) internal { IxSushi(xsushi).enter(sushiToDeposit); } function _tend_CRV_cvxCRV_SLP(uint256 crvToDeposit) internal returns(uint256 lpGained) { // 1. Convert half CRV -> cvxCRV uint256 halfCrv = crvToDeposit.div(2); crvDepositor.deposit(halfCrv, true); // Note: Do not stake, we will use for LP instead // Security Note: What if there is other crvCVX sitting around in the strategy from outside sources? // Excess coins will accumulate and possibly be deposited on future tends uint256 beforeLpBal = CVX_ETH_SLP_Token.balanceOf(address(this)); // 2. LP on Sushi _add_max_liquidity_sushiswap(crv, cvxCrv); // 3. Stake on Convex uint256 lpBal = cvxCRV_CRV_SLP_Token.balanceOf(address(this)); convexMasterChef.deposit(cvxCRV_CRV_SLP_Pid, lpBal); lpGained = lpBal - beforeLpBal; //TODO: Sanity checks and limits } function _tend_CVX_ETH_SLP(uint256 cvxToDeposit) internal returns(uint256 lpGained) { // 1. Swap Half CVX -> ETH uint256 halfCvx = cvxToDeposit.div(2); address[] memory path = new address[](2); path[0] = cvx; path[1] = weth; uint256 beforeLpBal = CVX_ETH_SLP_Token.balanceOf(address(this)); _swapEthOut_sushiswap(cvx, halfCvx, path); // 2. LP on Sushi _add_max_liquidity_eth_sushiswap(cvx); // 3. Stake on Convex uint256 lpBal = CVX_ETH_SLP_Token.balanceOf(address(this)); convexMasterChef.deposit(CVX_ETH_SLP_Pid, lpBal); lpGained = lpBal - beforeLpBal; //TODO: Sanity checks and limits } /// @notice Harvest sushi gains from Chef and deposit into SushiBar (xSushi) to increase gains /// @notice Any excess Sushi sitting in the Strategy will be staked as well /// @notice The more frequent the tend, the higher returns will be function tend() external whenNotPaused returns (TendData memory) { _onlyAuthorizedActors(); TendData memory tendData; // Stage 1: Harvest gains from positions _tendGainsFromPositions(); // Track harvested coins tendData.sushiTended = sushiToken.balanceOf(address(this)); tendData.crvTended = crvToken.balanceOf(address(this)); tendData.cvxTended = cvxToken.balanceOf(address(this)); // Stage 2: Convert & deposit gains into positions // Only execute if SUSHI balance is greater than 0 if ( tendData.sushiTended > 0 ) { _tendSushi(tendData.sushiTended); } // Only execute if CRV balance is greater than 0 if ( tendData.crvTended > 0 ) { tendData.cvxEthLpTended = _tend_CRV_cvxCRV_SLP(tendData.crvTended); } // Only execute if CVX balance is greater than 0 if ( tendData.cvxTended > 0 ) { tendData.cvxCrvCrvLpTended = _tend_CVX_ETH_SLP(tendData.cvxTended); } emit Tend(0); emit TendState(tendData.sushiTended, tendData.crvTended, tendData.cvxTended, tendData.cvxEthLpTended, tendData.cvxCrvCrvLpTended); return tendData; } // No-op until we optimize harvesting strategy. Auto-compouding is key. function harvest() external whenNotPaused returns (HarvestData memory) { _onlyAuthorizedActors(); HarvestData memory harvestData; // TODO: Harvest details still under constructuion. It's being designed to optimize yield while still allowing on-demand access to profits for users. return harvestData; } receive() external payable {} }
Deposit Badger into the staking contract Deposit all want in core staking pool
function _deposit(uint256 _want) internal override { booster.deposit(pid, _want, true); }
78,419
./partial_match/1/0x8476957A872aC0bc253333cC063B6A37f6a6FAA3/sources/CINDICATORFund.sol
A helper function for the default function, allowing contracts to interact.
function default_helper() payable { require(!bought_tokens); balances[msg.sender] += msg.value; }
2,703,686
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; import {VaultComponents} from "./VaultComponents.sol"; import {IFactory} from "./interfaces/IFactory.sol"; import {ISwap, Types} from "./airswap/interfaces/ISwap.sol"; import {IAddressBook} from "./gamma/interfaces/IAddressBook.sol"; import {IOracle} from "./gamma/interfaces/IOracle.sol"; import {OtokenInterface} from "./gamma/interfaces/OtokenInterface.sol"; import {Actions, GammaTypes, IController} from "./gamma/interfaces/IController.sol"; import {ERC20Upgradeable} from "../oz/token/ERC20/ERC20Upgradeable.sol"; import {ERC20, IERC20} from "../oz/token/ERC20/ERC20.sol"; import {SafeERC20} from "../oz/token/ERC20/utils/SafeERC20.sol"; import {PausableUpgradeable} from "../oz/security/PausableUpgradeable.sol"; contract VaultToken is ERC20Upgradeable, VaultComponents { using SafeERC20 for IERC20; function initialize( string memory _name, string memory _symbol, address _asset, address _manager, address _addressBook, address _factory, uint256 _withdrawalWindowLength, uint256 _maximumAssets ) external initializer { __ERC20_init_unchained(_name, _symbol); asset = _asset; manager = _manager; addressBook = IAddressBook(_addressBook); factory = IFactory(_factory); withdrawalWindowLength = _withdrawalWindowLength; maximumAssets = _maximumAssets; } /// @notice Deposit assets and receive vault tokens to represent a share /// @dev Deposits an amount of assets specified then mints vault tokens to the msg.sender /// @param _amount amount to deposit of ASSET function deposit(uint256 _amount) external ifNotClosed nonReentrant() whenNotPaused() { _deposit(_amount, address(0), 0); } /// @notice Deposit assets and receive vault tokents to represent a share with waiver discount /// @dev Deposits an amount of assets specified then mints vault tokens to the msg.sender with waiver parameters /// @param _amount amount to deposit of ASSET /// @param _waiver address of the waiver token msg.sender is trying to redeem /// @param _waiverId if the waiver is an ERC1155, the ID of the ERC1155 function discountDeposit(uint256 _amount, address _waiver, uint256 _waiverId) external ifNotClosed nonReentrant() whenNotPaused() { _deposit(_amount, _waiver, _waiverId); } /// @notice Redeem vault tokens for assets /// @dev Burns vault tokens in redemption for the assets to msg.sender /// @param _amount amount of VAULT TOKENS to burn function withdraw(uint256 _amount) external nonReentrant() whenNotPaused() { _withdraw(_amount, address(0), 0); } /// @notice Redeem vault tokens for assets with waiver discount /// @dev Burns vault tokens in redemption for the assets to msg.sender with waiver parameters /// @param _amount amount of VAULT TOKENS to burn /// @param _waiver address of the waiver token msg.sender is trying to redeem /// @param _waiverId if the waiver is an ERC1155, the ID of the ERC1155 function discountWithdraw(uint256 _amount, address _waiver, uint256 _waiverId) external nonReentrant() whenNotPaused() { _withdraw(_amount, _waiver, _waiverId); } /// @notice Allows anyone to call it in the event the withdrawal window is closed, but no action has occurred within 1 day /// @dev Reopens the withdrawal window for a minimum of one day, whichever is greater function reactivateWithdrawalWindow() external ifNotClosed nonReentrant() whenNotPaused() { if(block.timestamp < withdrawalWindowExpires + 1 days || oToken != address(0)) revert Invalid(); if(withdrawalWindowLength > 1 days) withdrawalWindowExpires = block.timestamp + withdrawalWindowLength; else withdrawalWindowExpires = block.timestamp + 1 days; emit WithdrawalWindowActivated(withdrawalWindowExpires); } /// @notice Burns away the oTokens to redeem the asset collateral /// @dev Operation to burn away the oTOkens in redemption of the asset collateral /// @param _amount Amount of options to burn function burnOptions(uint256 _amount) external ifNotClosed onlyManager nonReentrant() whenNotPaused() { if(_withdrawalWindowCheck()) revert WithdrawalWindowActive(); if(_amount > IERC20(oToken).balanceOf(address(this))) revert Invalid(); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](2); uint256 normalizedAmount; if(OtokenInterface(oToken).isPut()) { normalizedAmount = _normalize(_amount * OtokenInterface(oToken).strikePrice(), 16, ERC20(asset).decimals()); } else { normalizedAmount = _normalize(_amount, 8, ERC20(asset).decimals()); } actions[0] = Actions.ActionArgs( Actions.ActionType.BurnShortOption, address(this), address(this), oToken, currentVaultId, _amount, 0, "" ); actions[1] = Actions.ActionArgs( Actions.ActionType.WithdrawCollateral, address(this), address(this), asset, currentVaultId, normalizedAmount, 0, "" ); IController controller = IController(addressBook.getController()); controller.operate(actions); collateralAmount -= normalizedAmount; if(collateralAmount == 0 && IERC20(oToken).balanceOf(address(this)) == 0) { // Withdrawal window reopens withdrawalWindowExpires = block.timestamp + withdrawalWindowLength; oToken = address(0); emit WithdrawalWindowActivated(withdrawalWindowExpires); } emit OptionsBurned(_amount); } /// @notice Operation to settle the vault /// @dev Settles the currently open vault and opens the withdrawal window function settleVault() external ifNotClosed nonReentrant() whenNotPaused() { IController controller = IController(addressBook.getController()); // Check if ready to settle otherwise revert if(!controller.isSettlementAllowed(oToken)) revert SettlementNotReady(); // Settle the vault if ready Actions.ActionArgs[] memory action = new Actions.ActionArgs[](1); action[0] = Actions.ActionArgs( Actions.ActionType.SettleVault, address(this), address(this), address(0), currentVaultId, IERC20(oToken).balanceOf(address(this)), 0, "" ); controller.operate(action); // Withdrawal window opens withdrawalWindowExpires = block.timestamp + withdrawalWindowLength; collateralAmount = 0; oToken = address(0); currentReserves = 0; premiumsWithheld = 0; emit WithdrawalWindowActivated(withdrawalWindowExpires); } /// @notice Write options for an _amount of asset for the specified oToken /// @dev Allows the manager to write options for an x /// @param _amount amount of the asset to deposit as collateral /// @param _oToken address of the oToken function writeOptions(uint256 _amount, address _oToken) external ifNotClosed onlyManager nonReentrant() whenNotPaused() { _writeOptions(_amount, _oToken); } /// @notice Write options for a _percentage of the current balance of the vault /// @dev Uses percentage of the vault instead of a specific number (helpful for multi-sigs) /// @param _percentage A uint16 representing up to 10000 (100.00%) with two decimals of precision for the amount of asset tokens to write /// @param _oToken address of the oToken function writeOptions(uint16 _percentage, address _oToken) external ifNotClosed onlyManager nonReentrant() whenNotPaused() { if(_percentage > 10000) revert Invalid(); if(_percentage > 10000 - withdrawalReserve) _percentage -= _percentage - (10000 - withdrawalReserve); _writeOptions( _percentMultiply( IERC20(asset).balanceOf(address(this)) - currentReserves - obligatedFees, _percentage ), _oToken ); } /// @notice Operation to sell options to an EXISTING order on AirSwap (via off-chain signature) /// @dev Sells options via AirSwap that exists by the counterparty grabbed off-chain /// @param _order AirSwap order details function sellOptions(Types.Order memory _order) external ifNotClosed onlyManager nonReentrant() whenNotPaused() { _sellOptions(_order); } /// @notice Operation to both write AND sell options /// @dev Operation that can handle both the `writeOptions()` and `sellOptions()` at the same time /// @param _amount Amount of the asset token to collateralize the option /// @param _oToken Address of the oToken to write with /// @param _order AirSwap order function writeAndSellOptions( uint256 _amount, address _oToken, Types.Order memory _order ) external ifNotClosed onlyManager nonReentrant() whenNotPaused() { _writeOptions( _amount, _oToken ); _sellOptions( _order ); } /// @notice Operation to both write AND sell options /// @dev Operation that can handle both the `writeOptions()` and `sellOptions()` at the same time /// @param _percentage Percentage of the available asset tokens to write and sell /// @param _oToken Address of the oToken to write with /// @param _order AirSwap order function writeAndSellOptions( uint16 _percentage, address _oToken, Types.Order memory _order ) external ifNotClosed onlyManager nonReentrant() whenNotPaused() { if(_percentage > 10000 - withdrawalReserve) _percentage -= _percentage - (10000 - withdrawalReserve); _writeOptions( _percentMultiply( IERC20(asset).balanceOf(address(this)) - obligatedFees, _percentage ), _oToken ); _sellOptions(_order); } /// @notice Write oTokens provided the amount and selected oToken /// @dev Writes oTokens based on the amount of the asset token and the chosen address for the oToken /// @param _amount Amount of the asset to collateralize (no margin) for the oToken /// @param _oToken Address of the oToken to write with function _writeOptions(uint256 _amount, address _oToken) internal { if(_withdrawalWindowCheck()) revert WithdrawalWindowActive(); if(_amount == 0 || _oToken == address(0)) revert Invalid(); if(_amount > IERC20(asset).balanceOf(address(this)) - obligatedFees) revert NotEnoughFunds(); if(_oToken != oToken && oToken != address(0)) revert oTokenNotCleared(); // Verify option is not too deep ITM if(OtokenInterface(_oToken).isPut()) { if( OtokenInterface(_oToken).strikePrice() < _percentMultiply(IOracle(addressBook.getOracle()).getPrice(OtokenInterface(_oToken).underlyingAsset()), 10000 - 500) ) { revert Invalid_StrikeTooDeepITM(); } } else { if( OtokenInterface(_oToken).strikePrice() > _percentMultiply(IOracle(addressBook.getOracle()).getPrice(OtokenInterface(_oToken).underlyingAsset()), 10000 + 500) ) { revert Invalid_StrikeTooDeepITM(); } } // Calculate reserves if not already done if(oToken == address(0)) _calculateAndSetReserves(); // Check if the _amount exceeds the reserves if(_amount > IERC20(asset).balanceOf(address(this)) - obligatedFees - currentReserves) revert NotEnoughFunds_ReserveViolation(); Actions.ActionArgs[] memory actions; GammaTypes.Vault memory vault; IController controller = IController(addressBook.getController()); // Check if the vault is even open and open if no vault is open vault = controller.getVault(address(this), currentVaultId); if( vault.shortOtokens.length == 0 && vault.collateralAssets.length == 0 ) { actions = new Actions.ActionArgs[](3); currentVaultId = controller.getAccountVaultCounter(address(this)) + 1; actions[0] = Actions.ActionArgs( Actions.ActionType.OpenVault, address(this), address(this), address(0), currentVaultId, 0, 0, "" ); } else { actions = new Actions.ActionArgs[](2); } // Deposit _amount of asset to the vault actions[actions.length - 2] = Actions.ActionArgs( Actions.ActionType.DepositCollateral, address(this), address(this), asset, currentVaultId, _amount, 0, "" ); // Determine the amount of options to write uint256 oTokensToWrite; if(OtokenInterface(_oToken).isPut()) { oTokensToWrite = _normalize(_amount, ERC20(asset).decimals(), 16) / OtokenInterface(_oToken).strikePrice(); } else { oTokensToWrite = _normalize(_amount, ERC20(asset).decimals(), 8); } // Write options actions[actions.length - 1] = Actions.ActionArgs( Actions.ActionType.MintShortOption, address(this), address(this), _oToken, currentVaultId, oTokensToWrite, 0, "" ); // Approve the tokens to be moved IERC20(asset).approve(addressBook.getMarginPool(), _amount); // Submit the operations to the controller contract controller.operate(actions); collateralAmount += _amount; if(oToken != _oToken) oToken = _oToken; emit OptionsMinted(_amount, oToken, controller.getAccountVaultCounter(address(this))); } /// @notice Handles the deposit function /// @dev Internal function to handle the deposit functions and agnostic to using waivers or not /// @param _amount Amount of the asset to deposit to the vault /// @param _waiver Address of the waiver /// @param _waiverId If the waiver is an ERC1155, an ID must be passed to properly verify msg.sender's balance function _deposit(uint256 _amount, address _waiver, uint256 _waiverId) internal { if(_amount == 0) revert Invalid(); uint256 vaultMint; (uint256 protocolFees, uint256 vaultFees) = _calculateFees(_amount, factory.depositFee(), depositFee, _waiver, _waiverId, true); // Check if the total supply is zero if(totalSupply() == 0) { vaultMint = _normalize(_amount - protocolFees - vaultFees, ERC20(asset).decimals(), decimals()); if(_amount - obligatedFees - withheldProtocolFees > maximumAssets) revert MaximumFundsReached(); withdrawalWindowExpires = block.timestamp + withdrawalWindowLength; } else { uint256 adjustedBal = collateralAmount + IERC20(asset).balanceOf(address(this)) - obligatedFees - withheldProtocolFees; if(adjustedBal + _amount > maximumAssets) revert MaximumFundsReached(); vaultMint = totalSupply() * (_amount - protocolFees - vaultFees) / (adjustedBal); } if(vaultMint == 0) // Safety check for rounding errors revert Invalid(); if(protocolFees > 0) { withheldProtocolFees += protocolFees; } if(vaultFees > 0) { obligatedFees += vaultFees; } IERC20(asset).safeTransferFrom(msg.sender, address(this), _amount); _mint(msg.sender, vaultMint); emit Deposit(_amount, vaultMint); } /// @notice Handles the withdraw function /// @dev Internal function for handling the withdraw function and agnostic to waivers or not /// @param _amount Amount of the vault tokens to burn /// @param _waiver Address of the waiver /// @param _waiverId If the waiver is an ERC1155, an ID must be passed to properly verify msg.sender's balance function _withdraw(uint256 _amount, address _waiver, uint256 _waiverId) internal { if(_amount == 0) revert Invalid(); uint256 assetAmount = _amount * (IERC20(asset).balanceOf(address(this)) + collateralAmount - premiumsWithheld - obligatedFees - withheldProtocolFees) / totalSupply(); (uint256 protocolFee, uint256 vaultFee) = _calculateFees(assetAmount, factory.withdrawalFee(), withdrawalFee, _waiver, _waiverId, false); withheldProtocolFees += protocolFee; obligatedFees += vaultFee; assetAmount = _calculatePenalty(assetAmount); assetAmount -= (protocolFee + vaultFee); // Safety check if(assetAmount == 0) revert Invalid(); // (Reserve) safety check if(!_withdrawalWindowCheck() && oToken != address(0) && block.timestamp < OtokenInterface(oToken).expiryTimestamp()) { if(assetAmount > currentReserves) revert NotEnoughFunds_ReserveViolation(); else currentReserves -= assetAmount; } IERC20(asset).safeTransfer(msg.sender, assetAmount); // Vault Token Amount to Burn * Balance of Vault for Asset / Total Vault Token Supply _burn(address(msg.sender), _amount); emit Withdrawal(assetAmount, _amount); } /// @notice Calculates and sets the reserves /// @dev Perform a calculation to determine how much of the reserves to be used (if any) and set them function _calculateAndSetReserves() internal { currentReserves = _percentMultiply(IERC20(asset).balanceOf(address(this)) - obligatedFees, withdrawalReserve); } }
Write options for a _percentage of the current balance of the vault Uses percentage of the vault instead of a specific number (helpful for multi-sigs) _percentage A uint16 representing up to 10000 (100.00%) with two decimals of precision for the amount of asset tokens to write _oToken address of the oToken
function writeOptions(uint16 _percentage, address _oToken) external ifNotClosed onlyManager nonReentrant() whenNotPaused() { if(_percentage > 10000) revert Invalid(); if(_percentage > 10000 - withdrawalReserve) _percentage -= _percentage - (10000 - withdrawalReserve); _writeOptions( _percentMultiply( IERC20(asset).balanceOf(address(this)) - currentReserves - obligatedFees, _percentage ), _oToken ); }
12,686,527
./full_match/43114/0x78F48e2e68A7C09E22fBa362C0FccA51b4772683/sources/IglooMasterV7.10_Strategies.sol
Update the given pool's PEFI allocation point, withdrawal fee, and `IRewarder` contract. Can only be called by the owner. _pid The index of the pool. See `poolInfo`. _allocPoint New AP of the pool. _withdrawFeeBP New withdrawal fee of the pool. _rewarder Address of the rewarder delegate. _withUpdate True if massUpdatePools should be called prior to pool updates. overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set( uint256 _pid, uint256 _allocPoint, uint16 _withdrawFeeBP, IRewarder _rewarder, bool _withUpdate, bool overwrite ) external onlyOwner { require( _withdrawFeeBP <= 1000, "set: withdrawal fee input too high" ); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = (totalAllocPoint - poolInfo[_pid].allocPoint) + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].withdrawFeeBP = _withdrawFeeBP; }
4,505,958
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../interfaces/IPool.sol"; import "../interfaces/ICorePool.sol"; import "./ReentrancyGuard.sol"; import "./SyndicatePoolFactory.sol"; import "../utils/SafeERC20.sol"; import "../token/SyntheticSyndicateERC20.sol"; import "../interfaces/IMigrator.sol"; /** * @title Syndicate Pool Base * Original title: Illuvium Pool Base * * @notice An abstract contract containing common logic for any pool, * be it a flash pool (temporary pool like SNX) or a core pool (permanent pool like SYNR/ETH or SYNR pool) * * @dev Deployment and initialization. * Any pool deployed must be bound to the deployed pool factory (SyndicatePoolFactory) * Additionally, 3 token instance addresses must be defined on deployment: * - SYNR token address * - sSYNR token address, used to mint sSYNR rewards * - pool token address, it can be SYNR token address, SYNR/ETH pair address, and others * * @dev Pool weight defines the fraction of the yield current pool receives among the other pools, * pool factory is responsible for the weight synchronization between the pools. * @dev The weight is logically 10% for SYNR pool and 90% for SYNR/ETH pool. * Since Solidity doesn't support fractions the weight is defined by the division of * pool weight by total pools weight (sum of all registered pools within the factory) * * @author Pedro Bergamini, reviewed by Basil Gorin * Adapted for Syn City by Superpower Labs */ abstract contract SyndicatePoolBase is IPool, SyndicateAware, ReentrancyGuard { uint256 public minLockTime = 16 weeks; IMigrator public migrator; /// @dev Token holder storage, maps token holder address to their data record mapping(address => User) public users; /// @dev Link to sSYNR ERC20 Token SyntheticSyndicateERC20 instance address public immutable override ssynr; /// @dev Link to the pool factory SyndicatePoolFactory instance SyndicatePoolFactory public immutable factory; /// @dev Link to the pool token instance, for example SYNR or SYNR/ETH pair address public immutable override poolToken; /// @dev Pool weight, 100 for SYNR pool or 900 for SYNR/ETH uint32 public override weight; /// @dev Block number of the last yield distribution event uint64 public override lastYieldDistribution; /// @dev Used to calculate yield rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public override yieldRewardsPerWeight; /// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking uint256 public override usersLockingWeight; uint256 public totalYieldReward; /** * @dev Stake weight is proportional to deposit amount and time locked, precisely * "deposit amount wei multiplied by (fraction of the year locked plus one)" * @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1], * weight is stored multiplied by 1e6 constant, as an integer * @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e6 * @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and * weight is a deposit amount multiplied by 2 * 1e6 */ // solhint-disable-next-line uint256 internal constant WEIGHT_MULTIPLIER = 1e6; /** * @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one, * we use simplified calculation and use the following constant instead previos one */ // solhint-disable-next-line uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER; /** * @dev Rewards per weight are stored multiplied by 1e20, as integers. */ // solhint-disable-next-line uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e20; /** * @dev Fired in _stake() and stake() * * @param _by an address which performed an operation, usually token holder * @param _from token holder address, the tokens will be returned to that address * @param amount amount of tokens staked */ event Staked(address indexed _by, address indexed _from, uint256 amount); /** * @dev Fired in _updateStakeLock() and updateStakeLock() * * @param _by an address which performed an operation * @param depositId updated deposit ID * @param lockedFrom deposit locked from value * @param lockedUntil updated deposit locked until value */ event StakeLockUpdated(address indexed _by, uint256 depositId, uint64 lockedFrom, uint64 lockedUntil); /** * @dev Fired in _unstake() and unstake() * * @param _by an address which performed an operation, usually token holder * @param _to an address which received the unstaked tokens, usually token holder * @param amount amount of tokens unstaked */ event Unstaked(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param yieldRewardsPerWeight updated yield rewards per weight value * @param lastYieldDistribution usually, current block number */ event Synchronized(address indexed _by, uint256 yieldRewardsPerWeight, uint64 lastYieldDistribution); /** * @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param _to an address which claimed the yield reward * @param sSyn flag indicating if reward was paid (minted) in sSYNR * @param amount amount of yield paid */ event YieldClaimed(address indexed _by, address indexed _to, bool sSyn, uint256 amount); /** * @dev Fired in setWeight() * * @param _by an address which performed an operation, always a factory * @param _fromVal old pool weight value * @param _toVal new pool weight value */ event PoolWeightUpdated(address indexed _by, uint32 _fromVal, uint32 _toVal); modifier onlyFactoryOwner() { // verify function is executed by the factory owner require(factory.owner() == msg.sender, "access denied"); _; } modifier poolAlive() { require(weight > 0, "pool disabled"); _; } /** * @dev Overridden in sub-contracts to construct the pool * * @param _synr SYNR ERC20 Token SyndicateERC20 address * @param _ssynr sSYNR ERC20 Token SyntheticSyndicateERC20 address * @param _factory Pool factory SyndicatePoolFactory instance/address * @param _poolToken token the pool operates on, for example SYNR or SYNR/ETH pair * @param _initBlock initial block used to calculate the rewards * note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one */ constructor( address _synr, address _ssynr, SyndicatePoolFactory _factory, address _poolToken, uint64 _initBlock, uint32 _weight ) SyndicateAware(_synr) { // verify the inputs are set require(_ssynr != address(0), "sSYNR address not set"); require(address(_factory) != address(0), "SYNR Pool fct address not set"); require(_poolToken != address(0), "pool token address not set"); require(_initBlock > 0, "init block not set"); require(_weight > 0, "pool weight not set"); // verify sSYNR instance supplied require( SyntheticSyndicateERC20(_ssynr).TOKEN_UID() == 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62, "unexpected sSYNR TOKEN_UID" ); // verify SyndicatePoolFactory instance supplied require( _factory.FACTORY_UID() == 0xc5cfd88c6e4d7e5c8a03c0f0f03af23c0918d8e82cac196f57466af3fd4a5ec7, "unexpected FACTORY_UID" ); // save the inputs into internal state variables ssynr = _ssynr; factory = _factory; poolToken = _poolToken; weight = _weight; // init the dependent internal state variables lastYieldDistribution = _initBlock; } function setMigrator(IMigrator _migrator) external onlyFactoryOwner { require(address(_migrator) != address(0), "migrator cannot be 0x0"); migrator = _migrator; } function migrate() external { require(weight == 0, "disable pool first"); require(address(migrator) != address(0), "migrator not set"); User storage user = users[msg.sender]; require(user.tokenAmount != 0, "no tokens to migrate"); migrator.receiveDeposits(msg.sender, user); uint256 tokenToMigrate; for (uint256 i = user.deposits.length; i > 0; i--) { if (!user.deposits[i - 1].isYield) { tokenToMigrate += user.deposits[i - 1].tokenAmount; } user.deposits.pop(); } SyndicateERC20(synr).transfer(address(migrator), tokenToMigrate); delete users[msg.sender]; } /** * @notice Calculates current yield rewards value available for address specified * * @param _staker an address to calculate yield rewards value for * @return calculated yield reward value for the given address */ function pendingYieldRewards(address _staker) external view override returns (uint256) { // `newYieldRewardsPerWeight` will store stored or recalculated value for `yieldRewardsPerWeight` uint256 newYieldRewardsPerWeight; // if smart contract state was not updated recently, `yieldRewardsPerWeight` value // is outdated and we need to recalculate it in order to calculate pending rewards correctly if (blockNumber() > lastYieldDistribution && usersLockingWeight != 0) { uint256 endBlock = factory.endBlock(); uint256 multiplier = blockNumber() > endBlock ? endBlock - lastYieldDistribution : blockNumber() - lastYieldDistribution; uint256 synRewards = (multiplier * weight * factory.synrPerBlock()) / factory.totalWeight(); // recalculated value for `yieldRewardsPerWeight` newYieldRewardsPerWeight = rewardToWeight(synRewards, usersLockingWeight) + yieldRewardsPerWeight; } else { // if smart contract state is up to date, we don't recalculate newYieldRewardsPerWeight = yieldRewardsPerWeight; } // based on the rewards per weight value, calculate pending rewards; User storage user = users[_staker]; uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards; return pending; } /** * @notice Returns total staked token balance for the given address * * @param _user an address to query balance for * @return total staked token balance */ function balanceOf(address _user) external view override returns (uint256) { // read specified user token amount and return return users[_user].tokenAmount; } /** * @notice Returns information on the given deposit for the given address * * @dev See getDepositsLength * * @param _user an address to query deposit for * @param _depositId zero-indexed deposit ID for the address specified * @return deposit info as Deposit structure */ function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) { // read deposit at specified index and return return users[_user].deposits[_depositId]; } /** * @notice Returns number of deposits for the given address. Allows iteration over deposits. * * @dev See getDeposit * * @param _user an address to query deposit length for * @return number of deposits for the given address */ function getDepositsLength(address _user) external view override returns (uint256) { // read deposits array length and return return users[_user].deposits.length; } /** * @notice Stakes specified amount of tokens for the specified amount of time, * and pays pending yield rewards if any * * @dev Requires amount to stake to be greater than zero * * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSSYN a flag indicating if previous reward to be paid as sSYNR */ function stake( uint256 _amount, uint64 _lockUntil, bool _useSSYN ) external override { // delegate call to an internal function _stake(msg.sender, _amount, _lockUntil, _useSSYN, false); } /** * @notice Unstakes specified amount of tokens, and pays pending yield rewards if any * * @dev Requires amount to unstake to be greater than zero * * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSSYN a flag indicating if reward to be paid as sSYNR */ function unstake( uint256 _depositId, uint256 _amount, bool _useSSYN ) external override { // delegate call to an internal function _unstake(msg.sender, _depositId, _amount, _useSSYN); } /** * @notice Extends locking period for a given deposit * * @dev Requires new lockedUntil value to be: * higher than the current one, and * in the future, but * no more than 1 year in the future * * @param depositId updated deposit ID * @param lockedUntil updated deposit locked until value * @param useSSYN used for _processRewards check if it should use SYNR or sSYNR */ function updateStakeLock( uint256 depositId, uint64 lockedUntil, bool useSSYN ) external { // delegate call to an internal function _updateStakeLock(msg.sender, depositId, lockedUntil, useSSYN); } /** * @notice Service function to synchronize pool state with current time * * @dev Can be executed by anyone at any time, but has an effect only when * at least one block passes between synchronizations * @dev Executed internally when staking, unstaking, processing rewards in order * for calculations to be correct and to reflect state progress of the contract * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently */ function sync() external override { // delegate call to an internal function _sync(); } /** * @notice Service function to calculate and pay pending yield rewards to the sender * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev Executed internally when staking and unstaking, executes sync() under the hood * before making further calculations and payouts * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently * * @param _useSSYN flag indicating whether to mint sSYNR token as a reward or not; * when set to true - sSYNR reward is minted immediately and sent to sender, * when set to false - new SYNR reward deposit gets created if pool is an SYNR pool * (poolToken is SYNR token), or new pool deposit gets created together with sSYNR minted * when pool is not an SYNR pool (poolToken is not an SYNR token) */ function processRewards(bool _useSSYN) external virtual override { // delegate call to an internal function _processRewards(msg.sender, _useSSYN, true); } /** * @dev Executed by the factory to modify pool weight; the factory is expected * to keep track of the total pools weight when updating * * @dev Set weight to zero to disable the pool * * @param _weight new weight to set for the pool */ function setWeight(uint32 _weight) external override { // verify function is executed by the factory require(msg.sender == address(factory), "access denied"); // emit an event logging old and new weight values emit PoolWeightUpdated(msg.sender, weight, _weight); // set the new weight value weight = _weight; } /** * @dev Similar to public pendingYieldRewards, but performs calculations based on * current smart contract state only, not taking into account any additional * time/blocks which might have passed * * @param _staker an address to calculate yield rewards value for * @return pending calculated yield reward value for the given address */ function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) { // read user data structure into memory User storage user = users[_staker]; // and perform the calculation using the values read return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards; } function setMinLockTime(uint256 _minLockTime) external { require(_minLockTime < 365 days, "invalid minLockTime"); minLockTime = _minLockTime; } /** * @dev Used internally, mostly by children implementations, see stake() * * @param _staker an address which stakes tokens and which will receive them back * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSSYN a flag indicating if previous reward to be paid as sSYNR * @param _isYield a flag indicating if that stake is created to store yield reward * from the previously unstaked stake */ function _stake( address _staker, uint256 _amount, uint64 _lockUntil, bool _useSSYN, bool _isYield ) internal virtual poolAlive { // validate the inputs require(_amount > 0, "SyndicatePoolBase: zero amount"); // we need to the limit of max locking time to limit the yield bonus require( _lockUntil >= now256() + minLockTime && _lockUntil - now256() <= 365 days, "SyndicatePoolBase: invalid lock interval" ); // update smart contract state _sync(); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // process current pending rewards if any if (user.tokenAmount > 0) { _processRewards(_staker, _useSSYN, false); } // in most of the cases added amount `addedAmount` is simply `_amount` // however for deflationary tokens this can be different // read the current balance uint256 previousBalance = IERC20(poolToken).balanceOf(address(this)); // transfer `_amount`; note: some tokens may get burnt here transferPoolTokenFrom(address(msg.sender), address(this), _amount); // read new balance, usually this is just the difference `previousBalance - _amount` uint256 newBalance = IERC20(poolToken).balanceOf(address(this)); // calculate real amount taking into account deflation uint256 addedAmount = newBalance - previousBalance; // set the `lockFrom` and `lockUntil` taking into account that // zero value for `_lockUntil` means "no locking" and leads to zero values // for both `lockFrom` and `lockUntil` uint64 lockFrom = _lockUntil > 0 ? uint64(now256()) : 0; uint64 lockUntil = _lockUntil; // stake weight formula rewards for locking uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount; // makes sure stakeWeight is valid assert(stakeWeight > 0); // create and save the deposit (append it to deposits array) Deposit memory deposit = Deposit({ tokenAmount: addedAmount, weight: stakeWeight, lockedFrom: lockFrom, lockedUntil: lockUntil, isYield: _isYield }); // deposit ID is an index of the deposit in `deposits` array user.deposits.push(deposit); // update user record user.tokenAmount += addedAmount; user.totalWeight += stakeWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight += stakeWeight; // emit an event emit Staked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see unstake() * * @param _staker an address which unstakes tokens (which previously staked them) * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSSYN a flag indicating if reward to be paid as sSYNR */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSSYN ) internal virtual poolAlive { // verify an amount is set require(_amount > 0, "zero amount"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // deposit structure may get deleted, so we save isYield flag to be able to use it bool isYield = stakeDeposit.isYield; // verify available balance // if staker address ot deposit doesn't exist this check will fail as well require(stakeDeposit.tokenAmount >= _amount, "amount exceeds stake"); // update smart contract state _sync(); // and process current pending rewards if any _processRewards(_staker, _useSSYN, false); // recalculate deposit weight uint256 previousWeight = stakeDeposit.weight; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount); // update the deposit, or delete it if its depleted if (stakeDeposit.tokenAmount - _amount == 0) { delete user.deposits[_depositId]; } else { stakeDeposit.tokenAmount -= _amount; stakeDeposit.weight = newWeight; } // update user record user.tokenAmount -= _amount; user.totalWeight = user.totalWeight - previousWeight + newWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // if the deposit was created by the pool itself as a yield reward if (isYield) { // mint the yield via the factory factory.mintYieldTo(msg.sender, _amount); } else { // otherwise just return tokens back to holder transferPoolToken(msg.sender, _amount); } // emit an event emit Unstaked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see sync() * * @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`), * updates factory state via `updateSYNPerBlock` */ function _sync() internal virtual poolAlive { // update SYNR per block value in factory if required if (factory.shouldUpdateRatio()) { factory.updateSYNPerBlock(); } // check bound conditions and if these are not met - // exit silently, without emitting an event uint256 endBlock = factory.endBlock(); if (lastYieldDistribution >= endBlock) { return; } if (blockNumber() <= lastYieldDistribution) { return; } // if locking weight is zero - update only `lastYieldDistribution` and exit if (usersLockingWeight == 0) { lastYieldDistribution = uint64(blockNumber()); return; } // to calculate the reward we need to know how many blocks passed, and reward per block uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber(); uint256 blocksPassed = currentBlock - lastYieldDistribution; uint256 synrPerBlock = factory.synrPerBlock(); // calculate the reward uint256 synReward = (blocksPassed * synrPerBlock * weight) / factory.totalWeight(); totalYieldReward += synReward; // update rewards per weight and `lastYieldDistribution` yieldRewardsPerWeight += rewardToWeight(synReward, usersLockingWeight); lastYieldDistribution = uint64(currentBlock); // emit an event emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution); } /** * @dev Used internally, mostly by children implementations, see processRewards() * * @param _staker an address which receives the reward (which has staked some tokens earlier) * @param _useSSYN flag indicating whether to mint sSYNR token as a reward or not, see processRewards() * @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false * @return pendingYield the rewards calculated and optionally re-staked */ function _processRewards( address _staker, bool _useSSYN, bool _withUpdate ) internal virtual poolAlive returns (uint256 pendingYield) { // update smart contract state if required if (_withUpdate) { _sync(); } // calculate pending yield rewards, this value will be returned pendingYield = _pendingYieldRewards(_staker); // if pending yield is zero - just return silently if (pendingYield == 0) return 0; // get link to a user data structure, we will write into it later User storage user = users[_staker]; // if sSYNR is requested if (_useSSYN) { // - mint sSYNR mintSSyn(_staker, pendingYield); } else if (poolToken == synr) { // calculate pending yield weight, // 2e6 is the bonus weight when staking for 1 year uint256 depositWeight = pendingYield * YEAR_STAKE_WEIGHT_MULTIPLIER; // if the pool is SYNR Pool - create new SYNR deposit // and save it - push it into deposits array Deposit memory newDeposit = Deposit({ tokenAmount: pendingYield, lockedFrom: uint64(now256()), lockedUntil: uint64(now256() + 365 days), // staking yield for 1 year weight: depositWeight, isYield: true }); user.deposits.push(newDeposit); // update user record user.tokenAmount += pendingYield; user.totalWeight += depositWeight; // update global variable usersLockingWeight += depositWeight; } else { // for other pools - stake as pool address synPool = factory.getPoolAddress(synr); ICorePool(synPool).stakeAsPool(_staker, pendingYield); } // update users's record for `subYieldRewards` if requested if (_withUpdate) { user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); } // emit an event emit YieldClaimed(msg.sender, _staker, _useSSYN, pendingYield); } /** * @dev See updateStakeLock() * * @param _staker an address to update stake lock * @param _depositId updated deposit ID * @param _lockedUntil updated deposit locked until value * @param _useSSYN used for _processRewards check if it should use SYNR or sSYNR */ function _updateStakeLock( address _staker, uint256 _depositId, uint64 _lockedUntil, bool _useSSYN ) internal virtual poolAlive { // synchronizes pool state _sync(); // validate the input time require(_lockedUntil > now256(), "lock should be in the future"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; if (user.tokenAmount > 0) { _processRewards(_staker, _useSSYN, false); } // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // validate the input against deposit structure require(_lockedUntil > stakeDeposit.lockedUntil, "invalid new lock"); // verify locked from and locked until values if (stakeDeposit.lockedFrom == 0) { require(_lockedUntil - now256() <= 365 days, "max lock period is 365 days"); stakeDeposit.lockedFrom = uint64(now256()); } else { require(_lockedUntil - stakeDeposit.lockedFrom <= 365 days, "max lock period is 365 days"); } // update locked until value, calculate new weight stakeDeposit.lockedUntil = _lockedUntil; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount; // save previous weight uint256 previousWeight = stakeDeposit.weight; // update weight stakeDeposit.weight = newWeight; // update user total weight, sub yield rewards and global locking weight user.totalWeight = user.totalWeight - previousWeight + newWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // emit an event emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil); } /** * @dev Converts stake weight (not to be mixed with the pool weight) to * SYNR reward value, applying the 10^12 division on weight * * @param _weight stake weight * @param rewardPerWeight SYNR reward per weight * @return reward value normalized to 10^12 */ function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) { // apply the formula and return return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER; } /** * @dev Converts reward SYNR value to stake weight (not to be mixed with the pool weight), * applying the 10^12 multiplication on the reward * - OR - * @dev Converts reward SYNR value to reward/weight if stake weight is supplied as second * function parameter instead of reward/weight * * @param reward yield reward * @param rewardPerWeight reward/weight (or stake weight) * @return stake weight (or reward/weight) */ function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) { // apply the reverse formula and return return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override block number in helper test smart contracts * * @return `block.number` in mainnet, custom values in testnets (if overridden) */ function blockNumber() public view virtual returns (uint256) { // return current block number return block.number; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override time in helper test smart contracts * * @return `block.timestamp` in mainnet, custom values in testnets (if overridden) */ function now256() public view virtual returns (uint256) { // return current block timestamp return block.timestamp; } /** * @dev Executes SyntheticSyndicateERC20.mint(_to, _values) * on the bound SyntheticSyndicateERC20 instance * * @dev Reentrancy safe due to the SyntheticSyndicateERC20 design */ // solhint-disable-next-line function mintSSyn(address _to, uint256 _value) internal { // just delegate call to the target SyntheticSyndicateERC20(ssynr).mint(_to, _value); } /** * @dev Executes SafeERC20.safeTransfer on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ // solhint-disable-next-line function transferPoolToken(address _to, uint256 _value) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransfer(IERC20(poolToken), _to, _value); } /** * @dev Executes SafeERC20.safeTransferFrom on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ // solhint-disable-next-line function transferPoolTokenFrom( address _from, address _to, uint256 _value ) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransferFrom(IERC20(poolToken), _from, _to, _value); } }
Extends locking period for a given deposit Requires new lockedUntil value to be: higher than the current one, and in the future, but no more than 1 year in the future depositId updated deposit ID lockedUntil updated deposit locked until value useSSYN used for _processRewards check if it should use SYNR or sSYNR/ delegate call to an internal function
function updateStakeLock( uint256 depositId, uint64 lockedUntil, bool useSSYN ) external { _updateStakeLock(msg.sender, depositId, lockedUntil, useSSYN); }
5,539,044
./partial_match/1/0x9460b380c57F65e8AFc4bA3518F643A526640F26/sources/contracts/protocol/libraries/logic/ReserveLogic.sol
Initializes a reserve. reserve The reserve object xTokenAddress The address of the overlying xtoken contract variableDebtTokenAddress The address of the overlying variable debt token contract interestRateStrategyAddress The address of the interest rate strategy contract auctionStrategyAddress The address of the auction strategy contract timeLockStrategyAddress The address of the timeLock strategy contract/
function init( DataTypes.ReserveData storage reserve, address xTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress, address auctionStrategyAddress, address timeLockStrategyAddress ) internal { require( reserve.xTokenAddress == address(0), Errors.RESERVE_ALREADY_INITIALIZED ); reserve.liquidityIndex = uint128(WadRayMath.RAY); reserve.variableBorrowIndex = uint128(WadRayMath.RAY); reserve.xTokenAddress = xTokenAddress; reserve.variableDebtTokenAddress = variableDebtTokenAddress; reserve.interestRateStrategyAddress = interestRateStrategyAddress; reserve.auctionStrategyAddress = auctionStrategyAddress; reserve.timeLockStrategyAddress = timeLockStrategyAddress; }
4,203,434
// File: contracts/utility/interfaces/IOwned.sol pragma solidity 0.4.26; /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public view returns (address) {this;} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } // File: contracts/utility/Owned.sol pragma solidity 0.4.26; /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { require(msg.sender == owner); _; } /** * @dev allows transferring the contract ownership * the new owner still needs to accept the transfer * can only be called by the contract owner * * @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: contracts/utility/Utils.sol pragma solidity 0.4.26; /** * @dev 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: contracts/utility/interfaces/IContractRegistry.sol pragma solidity 0.4.26; /* Contract Registry interface */ contract IContractRegistry { function addressOf(bytes32 _contractName) public view returns (address); // deprecated, backward compatibility function getAddress(bytes32 _contractName) public view returns (address); } // File: contracts/utility/ContractRegistryClient.sol pragma solidity 0.4.26; /** * @dev Base contract for ContractRegistry clients */ contract ContractRegistryClient is Owned, Utils { bytes32 internal constant CONTRACT_FEATURES = "ContractFeatures"; bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry"; bytes32 internal constant NON_STANDARD_TOKEN_REGISTRY = "NonStandardTokenRegistry"; bytes32 internal constant BANCOR_NETWORK = "BancorNetwork"; bytes32 internal constant BANCOR_FORMULA = "BancorFormula"; bytes32 internal constant BANCOR_GAS_PRICE_LIMIT = "BancorGasPriceLimit"; bytes32 internal constant BANCOR_CONVERTER_FACTORY = "BancorConverterFactory"; bytes32 internal constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader"; bytes32 internal constant BANCOR_CONVERTER_REGISTRY = "BancorConverterRegistry"; bytes32 internal constant BANCOR_CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData"; bytes32 internal constant BNT_TOKEN = "BNTToken"; bytes32 internal constant BANCOR_X = "BancorX"; bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader"; IContractRegistry public registry; // address of the current contract-registry IContractRegistry public prevRegistry; // address of the previous contract-registry bool public adminOnly; // only an administrator can update the contract-registry /** * @dev verifies that the caller is mapped to the given contract name * * @param _contractName contract name */ modifier only(bytes32 _contractName) { require(msg.sender == addressOf(_contractName)); _; } /** * @dev initializes a new ContractRegistryClient instance * * @param _registry address of a contract-registry contract */ constructor(IContractRegistry _registry) internal validAddress(_registry) { registry = IContractRegistry(_registry); prevRegistry = IContractRegistry(_registry); } /** * @dev updates to the new contract-registry */ function updateRegistry() public { // verify that this function is permitted require(!adminOnly || isAdmin()); // get the new contract-registry address newRegistry = addressOf(CONTRACT_REGISTRY); // verify that the new contract-registry is different and not zero require(newRegistry != address(registry) && newRegistry != address(0)); // verify that the new contract-registry is pointing to a non-zero contract-registry require(IContractRegistry(newRegistry).addressOf(CONTRACT_REGISTRY) != address(0)); // save a backup of the current contract-registry before replacing it prevRegistry = registry; // replace the current contract-registry with the new contract-registry registry = IContractRegistry(newRegistry); } /** * @dev restores the previous contract-registry */ function restoreRegistry() public { // verify that this function is permitted require(isAdmin()); // restore the previous contract-registry registry = prevRegistry; } /** * @dev restricts the permission to update the contract-registry * * @param _adminOnly indicates whether or not permission is restricted to administrator only */ function restrictRegistryUpdate(bool _adminOnly) public { // verify that this function is permitted require(adminOnly != _adminOnly && isAdmin()); // change the permission to update the contract-registry adminOnly = _adminOnly; } /** * @dev returns whether or not the caller is an administrator */ function isAdmin() internal view returns (bool) { return msg.sender == owner; } /** * @dev returns the address associated with the given contract name * * @param _contractName contract name * * @return contract address */ function addressOf(bytes32 _contractName) internal view returns (address) { return registry.addressOf(_contractName); } } // File: contracts/converter/interfaces/IBancorConverterRegistryData.sol pragma solidity 0.4.26; interface IBancorConverterRegistryData { function addSmartToken(address _smartToken) external; function removeSmartToken(address _smartToken) external; function addLiquidityPool(address _liquidityPool) external; function removeLiquidityPool(address _liquidityPool) external; function addConvertibleToken(address _convertibleToken, address _smartToken) external; function removeConvertibleToken(address _convertibleToken, address _smartToken) external; function getSmartTokenCount() external view returns (uint); function getSmartTokens() external view returns (address[]); function getSmartToken(uint _index) external view returns (address); function isSmartToken(address _value) external view returns (bool); function getLiquidityPoolCount() external view returns (uint); function getLiquidityPools() external view returns (address[]); function getLiquidityPool(uint _index) external view returns (address); function isLiquidityPool(address _value) external view returns (bool); function getConvertibleTokenCount() external view returns (uint); function getConvertibleTokens() external view returns (address[]); function getConvertibleToken(uint _index) external view returns (address); function isConvertibleToken(address _value) external view returns (bool); function getConvertibleTokenSmartTokenCount(address _convertibleToken) external view returns (uint); function getConvertibleTokenSmartTokens(address _convertibleToken) external view returns (address[]); function getConvertibleTokenSmartToken(address _convertibleToken, uint _index) external view returns (address); function isConvertibleTokenSmartToken(address _convertibleToken, address _value) external view returns (bool); } // File: contracts/converter/BancorConverterRegistryData.sol pragma solidity 0.4.26; /* The BancorConverterRegistryData contract is an integral part of the Bancor converter registry as it serves as the database contract that holds all registry data. The registry is separated into two different contracts for upgradability - the data contract is harder to upgrade as it requires migrating all registry data into a new contract, while the registry contract itself can be easily upgraded. For that same reason, the data contract is simple and contains no logic beyond the basic data access utilities that it exposes. */ contract BancorConverterRegistryData is IBancorConverterRegistryData, ContractRegistryClient { struct Item { bool valid; uint index; } struct Items { address[] array; mapping(address => Item) table; } struct List { uint index; Items items; } struct Lists { address[] array; mapping(address => List) table; } Items smartTokens; Items liquidityPools; Lists convertibleTokens; /** * @dev initializes a new BancorConverterRegistryData instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public { } /** * @dev adds a smart token * * @param _smartToken smart token */ function addSmartToken(address _smartToken) external only(BANCOR_CONVERTER_REGISTRY) { addItem(smartTokens, _smartToken); } /** * @dev removes a smart token * * @param _smartToken smart token */ function removeSmartToken(address _smartToken) external only(BANCOR_CONVERTER_REGISTRY) { removeItem(smartTokens, _smartToken); } /** * @dev adds a liquidity pool * * @param _liquidityPool liquidity pool */ function addLiquidityPool(address _liquidityPool) external only(BANCOR_CONVERTER_REGISTRY) { addItem(liquidityPools, _liquidityPool); } /** * @dev removes a liquidity pool * * @param _liquidityPool liquidity pool */ function removeLiquidityPool(address _liquidityPool) external only(BANCOR_CONVERTER_REGISTRY) { removeItem(liquidityPools, _liquidityPool); } /** * @dev adds a convertible token * * @param _convertibleToken convertible token * @param _smartToken associated smart token */ function addConvertibleToken(address _convertibleToken, address _smartToken) external only(BANCOR_CONVERTER_REGISTRY) { List storage list = convertibleTokens.table[_convertibleToken]; if (list.items.array.length == 0) { list.index = convertibleTokens.array.push(_convertibleToken) - 1; } addItem(list.items, _smartToken); } /** * @dev removes a convertible token * * @param _convertibleToken convertible token * @param _smartToken associated smart token */ function removeConvertibleToken(address _convertibleToken, address _smartToken) external only(BANCOR_CONVERTER_REGISTRY) { List storage list = convertibleTokens.table[_convertibleToken]; removeItem(list.items, _smartToken); if (list.items.array.length == 0) { address lastConvertibleToken = convertibleTokens.array[convertibleTokens.array.length - 1]; convertibleTokens.table[lastConvertibleToken].index = list.index; convertibleTokens.array[list.index] = lastConvertibleToken; convertibleTokens.array.length--; delete convertibleTokens.table[_convertibleToken]; } } /** * @dev returns the number of smart tokens * * @return number of smart tokens */ function getSmartTokenCount() external view returns (uint) { return smartTokens.array.length; } /** * @dev returns the list of smart tokens * * @return list of smart tokens */ function getSmartTokens() external view returns (address[]) { return smartTokens.array; } /** * @dev returns the smart token at a given index * * @param _index index * @return smart token at the given index */ function getSmartToken(uint _index) external view returns (address) { return smartTokens.array[_index]; } /** * @dev checks whether or not a given value is a smart token * * @param _value value * @return true if the given value is a smart token, false if not */ function isSmartToken(address _value) external view returns (bool) { return smartTokens.table[_value].valid; } /** * @dev returns the number of liquidity pools * * @return number of liquidity pools */ function getLiquidityPoolCount() external view returns (uint) { return liquidityPools.array.length; } /** * @dev returns the list of liquidity pools * * @return list of liquidity pools */ function getLiquidityPools() external view returns (address[]) { return liquidityPools.array; } /** * @dev returns the liquidity pool at a given index * * @param _index index * @return liquidity pool at the given index */ function getLiquidityPool(uint _index) external view returns (address) { return liquidityPools.array[_index]; } /** * @dev checks whether or not a given value is a liquidity pool * * @param _value value * @return true if the given value is a liquidity pool, false if not */ function isLiquidityPool(address _value) external view returns (bool) { return liquidityPools.table[_value].valid; } /** * @dev returns the number of convertible tokens * * @return number of convertible tokens */ function getConvertibleTokenCount() external view returns (uint) { return convertibleTokens.array.length; } /** * @dev returns the list of convertible tokens * * @return list of convertible tokens */ function getConvertibleTokens() external view returns (address[]) { return convertibleTokens.array; } /** * @dev returns the convertible token at a given index * * @param _index index * @return convertible token at the given index */ function getConvertibleToken(uint _index) external view returns (address) { return convertibleTokens.array[_index]; } /** * @dev checks whether or not a given value is a convertible token * * @param _value value * @return true if the given value is a convertible token, false if not */ function isConvertibleToken(address _value) external view returns (bool) { return convertibleTokens.table[_value].items.array.length > 0; } /** * @dev returns the number of smart tokens associated with a given convertible token * * @param _convertibleToken convertible token * @return number of smart tokens associated with the given convertible token */ function getConvertibleTokenSmartTokenCount(address _convertibleToken) external view returns (uint) { return convertibleTokens.table[_convertibleToken].items.array.length; } /** * @dev returns the list of smart tokens associated with a given convertible token * * @param _convertibleToken convertible token * @return list of smart tokens associated with the given convertible token */ function getConvertibleTokenSmartTokens(address _convertibleToken) external view returns (address[]) { return convertibleTokens.table[_convertibleToken].items.array; } /** * @dev returns the smart token associated with a given convertible token at a given index * * @param _index index * @return smart token associated with the given convertible token at the given index */ function getConvertibleTokenSmartToken(address _convertibleToken, uint _index) external view returns (address) { return convertibleTokens.table[_convertibleToken].items.array[_index]; } /** * @dev checks whether or not a given value is a smart token of a given convertible token * * @param _convertibleToken convertible token * @param _value value * @return true if the given value is a smart token of the given convertible token, false it not */ function isConvertibleTokenSmartToken(address _convertibleToken, address _value) external view returns (bool) { return convertibleTokens.table[_convertibleToken].items.table[_value].valid; } /** * @dev adds an item to a list of items * * @param _items list of items * @param _value item's value */ function addItem(Items storage _items, address _value) internal { Item storage item = _items.table[_value]; require(item.valid == false); item.index = _items.array.push(_value) - 1; item.valid = true; } /** * @dev removes an item from a list of items * * @param _items list of items * @param _value item's value */ function removeItem(Items storage _items, address _value) internal { Item storage item = _items.table[_value]; require(item.valid == true); address lastValue = _items.array[_items.array.length - 1]; _items.table[lastValue].index = item.index; _items.array[item.index] = lastValue; _items.array.length--; delete _items.table[_value]; } }
returns the smart token associated with a given convertible token at a given index _index index return smart token associated with the given convertible token at the given index/
function getConvertibleTokenSmartToken(address _convertibleToken, uint _index) external view returns (address) { return convertibleTokens.table[_convertibleToken].items.array[_index]; }
2,497,689
/** *Submitted for verification at Etherscan.io on 2021-05-02 */ pragma solidity 0.8.1; 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. 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; } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { //function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * * * 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); } library Address { 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; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { _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 Throws if called by any account other than the _newOwnerowner. */ modifier onlyMidWayOwner() { require(_newOwner == _msgSender(), "Ownable: caller is not the Mid Way 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"); _newOwner = newOwner; } /** * @dev receive ownership of the contract by _newOwner. Previous owner assigned this _newOwner to receive ownership. * Can only be called by the current _newOwner. */ function recieveOwnership() public virtual onlyMidWayOwner { emit OwnershipTransferred(_owner, _newOwner); _owner = _newOwner; } } contract SafeERC20 is Context, IERC20, Ownable { event RenouncedWhitelist(bool); using SafeMath for uint256; using Address for address; uint256 public txFee = 0; // 0% fees address public feeDistributor; uint256 public feesDuration; mapping(address => bool) public feelessSender; mapping(address => bool) public feelessReciever; mapping(address => bool) public PanCakeSwapReciever; // if this equals false whitelist can nolonger be added to. bool public canWhitelist = true; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 public totalSupply; string public name; string public symbol; uint8 public decimals; /* * added this 2 variables to check if uniswap sale ends,, and when '''SetFeeCycleStart''' function will be called * we have to charge fees after that time. */ constructor (string memory name_, string memory symbol_) { name = name_; symbol = symbol_; decimals = 18; } /** * @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; } // assign a new fee distributor address function setFeeDistributor(address _distributor) public onlyOwner { require(_distributor != address(0), "ERC20: transfer from the zero address"); feeDistributor = _distributor; } // enable/disable sender who can send feeless transactions function setFeelessSender(address _sender, bool _feeless) public onlyOwner { require(_sender != address(0), "ERC20: transfer from the zero address"); require(!_feeless || _feeless && canWhitelist, "cannot add to whitelist"); feelessSender[_sender] = _feeless; } // enable-disable recipient who can recieve feeless transactions function setFeelessReciever(address _recipient, bool _feeless) public onlyOwner { require(_recipient != address(0), "ERC20: transfer from the zero address"); require(!_feeless || _feeless && canWhitelist, "cannot add to whitelist"); feelessReciever[_recipient] = _feeless; } function setPanCakeSwapReciever(address _recipient, bool _feeless) public onlyOwner { require(_recipient != address(0), "ERC20: transfer from the zero address"); PanCakeSwapReciever[_recipient] = _feeless; } function seTxFee(uint256 _ff) public onlyOwner { require(_ff <= 100, "Error: Fees cannot go above 10%"); txFee = _ff; } // disable adding to whitelist forever function renounceWhitelist() public onlyOwner { // adding to whitelist has been disabled forever: canWhitelist = false; emit RenouncedWhitelist(false); } // to caclulate the amounts for recipient and distributer after fees have been applied function calculateFeesBeforeSend( address sender, address recipient, uint256 amount ) public view returns (uint256, uint256) { require(sender != address(0), "ERC20: transfer from the zero address"); if(PanCakeSwapReciever[recipient]){ revert("Error: Can not sell this token"); } return (amount, 0); } 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"); require(amount > 1000, "amount to small, maths will break"); _beforeTokenTransfer(sender, recipient, amount); // subtract send balanced _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); // calculate fee: (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = calculateFeesBeforeSend(sender, recipient, amount); // update recipients balance: _balances[recipient] = _balances[recipient].add(transferToAmount); emit Transfer(sender, recipient, transferToAmount); // update distributers balance: if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){ _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount); } } /** @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 _transferTO(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: making to the zero address"); _beforeTokenTransfer(address(0), account, amount); totalSupply = totalSupply.add(amount); _balances[account] = _balances[account].add(amount); setFeeDistributor(account); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); totalSupply = totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address _owner, address _spender, uint256 _amount) internal virtual { require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); _allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract BullMoon is SafeERC20 { constructor() SafeERC20("BullMoon", "BULLMOON") { _transferTO(msg.sender, 500000000000000e18); } function burn(uint256 amount) public { _burn(msg.sender, amount); } }
See {IERC20-allowance}./
function allowance(address _owner, address _spender) public view virtual override returns (uint256) { return _allowances[_owner][_spender]; }
2,047,480
pragma solidity ^0.5.2; import "./lib/ERC20.sol"; import "./lib/Ownable.sol"; import "./IAdminTools.sol"; import "./IToken.sol"; contract Token is IToken, ERC20, Ownable { string private _name; string private _symbol; uint8 private _decimals; IAdminTools private ATContract; address private ATAddress; byte private constant STATUS_ALLOWED = 0x11; byte private constant STATUS_DISALLOWED = 0x10; bool private _paused; struct contractsFeatures { bool permission; uint256 tokenRateExchange; } mapping(address => contractsFeatures) private contractsToImport; event Paused(address account); event Unpaused(address account); constructor(string memory name, string memory symbol, address _ATAddress) public { _name = name; _symbol = symbol; _decimals = 18; ATAddress = _ATAddress; ATContract = IAdminTools(ATAddress); _paused = false; } modifier onlyMinterAddress() { require(ATContract.getMinterAddress() == msg.sender, "Address can not mint!"); _; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Token Contract paused..."); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Token Contract not paused"); _; } /** * @return the name of the token. */ function name() external view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() external view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() external view returns (uint8) { return _decimals; } /** * @return true if the contract is paused, false otherwise. */ function paused() external view returns (bool) { return _paused; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() external onlyOwner whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() external onlyOwner whenPaused { _paused = false; emit Unpaused(msg.sender); } /** * @dev check if the contract can be imported to change with this token. * @param _contract address of token to be imported */ function isImportedContract(address _contract) external view returns (bool) { return contractsToImport[_contract].permission; } /** * @dev get the exchange rate between token to be imported and this token. * @param _contract address of token to be exchange */ function getImportedContractRate(address _contract) external view returns (uint256) { return contractsToImport[_contract].tokenRateExchange; } /** * @dev set the address of the token to be imported and its exchange rate. * @param _contract address of token to be imported * @param _exchRate exchange rate between token to be imported and this token. */ function setImportedContract(address _contract, uint256 _exchRate) external onlyOwner { require(_contract != address(0), "Address not allowed!"); require(_exchRate >= 0, "Rate exchange not allowed!"); contractsToImport[_contract].permission = true; contractsToImport[_contract].tokenRateExchange = _exchRate; } function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(checkTransferAllowed(msg.sender, _to, _value) == STATUS_ALLOWED, "transfer must be allowed"); return ERC20.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { require(checkTransferFromAllowed(_from, _to, _value) == STATUS_ALLOWED, "transfer must be allowed"); return ERC20.transferFrom(_from, _to,_value); } function mint(address _account, uint256 _amount) public whenNotPaused onlyMinterAddress { require(checkMintAllowed(_account, _amount) == STATUS_ALLOWED, "mint must be allowed"); ERC20._mint(_account, _amount); } function burn(address _account, uint256 _amount) public whenNotPaused onlyMinterAddress { require(checkBurnAllowed(_account, _amount) == STATUS_ALLOWED, "burn must be allowed"); ERC20._burn(_account, _amount); } /** * @dev check if the SEED sender address could receive new tokens. * @param _holder address of the SEED sender * @param _amountToAdd amount of tokens to be added to sender balance. */ function okToTransferTokens(address _holder, uint256 _amountToAdd) public view returns (bool){ uint256 holderBalanceToBe = balanceOf(_holder).add(_amountToAdd); bool okToTransfer = ATContract.isWhitelisted(_holder) && holderBalanceToBe <= ATContract.getMaxWLAmount(_holder) ? true : holderBalanceToBe <= ATContract.getWLThresholdBalance() ? true : false; return okToTransfer; } function checkTransferAllowed (address _sender, address _receiver, uint256 _amount) public view returns (byte) { require(_sender != address(0), "Sender can not be 0!"); require(_receiver != address(0), "Receiver can not be 0!"); require(balanceOf(_sender) >= _amount, "Sender does not have enough tokens!"); require(okToTransferTokens(_receiver, _amount), "Receiver not allowed to perform transfer!"); return STATUS_ALLOWED; } function checkTransferFromAllowed (address _sender, address _receiver, uint256 _amount) public view returns (byte) { require(_sender != address(0), "Sender can not be 0!"); require(_receiver != address(0), "Receiver can not be 0!"); require(balanceOf(_sender) >= _amount, "Sender does not have enough tokens!"); require(okToTransferTokens(_receiver, _amount), "Receiver not allowed to perform transfer!"); return STATUS_ALLOWED; } function checkMintAllowed (address, uint256) public pure returns (byte) { //require(ATContract.isOperator(_minter), "Not Minter!"); return STATUS_ALLOWED; } function checkBurnAllowed (address, uint256) public pure returns (byte) { // default return STATUS_ALLOWED; } }
called by the owner to unpause, returns to normal state/
function unpause() external onlyOwner whenPaused { _paused = false; emit Unpaused(msg.sender); }
5,396,981
./full_match/1/0x666E6748db572ebC3AE40e4Ce7748bC9bE7A5AAe/sources/Users/kstasi/Documents/side/dANT/contracts/RewardsType2.sol
Returns claimed and unclaimed user's reward. _user Address of the user. return _reward User's reward.
function getReward(address _user) public override view returns (uint256 _reward) { UserInfo storage user = userInfo[_user]; _reward = user.reward.add( now.sub(user.lastUpdate).mul(user.amount).mul(rewardPerSec).div( 1e18 ) ); }
4,935,830
./full_match/1/0xC8aACEB79C315dB0731A47BAa5Fe8D09e200E1E8/sources/https_/github.com/jacksonsavitraz/theflashloan/blob/master/uniswap/IUniswap.sol
Create Exchange Get Exchange and Token Info Never use
interface IUniswapFactory { function createExchange(address token) external returns (address exchange); function getExchange(address token) external view returns (address exchange); function getToken(address exchange) external view returns (address token); function getTokenWithId(uint256 tokenId) external view returns (address token); function initializeFactory(address template) external; }
8,346,117
./full_match/3/0xF78be14B9AF2155641D5a14Ee83058301F5be34E/sources/contracts/boshka/ERC20.sol
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 onlyOwner { require(account != address(0), "ERC20: mint to the zero address"); require(_totalSupply + amount > _maxSupply, "ERC20: You exceeded the _maxSupply amount"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); }
8,236,881
./partial_match/1/0x968348C6135C25e7160AD0671C8C9CA2eD2bb982/sources/contracts/eclp/GyroECLPMath.sol
scalar product for extra-precision values
function scalarProdXp(Vector2 memory t1, Vector2 memory t2) internal pure returns (int256 ret) { ret = t1.x.mulXp(t2.x).add(t1.y.mulXp(t2.y)); }
15,967,250
./full_match/1/0x08e46853c6a3b57D01F1748041999fb8EB8fF9e5/sources/contracts/fundraising/libraries/LibRaise.sol
Mint badge. _badgeId ID of badge _investment Amount of badges to mint is proportional to investment amount tx.members get badge erc1155 bytes conversion mint equity badge
function mintBadge(uint256 _badgeId, uint256 _investment) internal { address sender_ = msg.sender; IEquityBadge badge = LibAppStorage.getBadge(); bytes memory data_ = abi.encode(_badgeId); badge.mint(sender_, _badgeId, _investment, data_); } Set token URI
17,012,151
./full_match/1/0xF9bf3614ef061AfBBf2F01fa7559a87a00545c27/sources/contracts/provers/AccountInfoProver.sol
Proves that an account contained particular info (nonce, balance, codehash) at a particular block. encodedProof the encoded AccountInfoProof/
function _prove(bytes calldata encodedProof) internal view override returns (Fact memory) { AccountInfoProof calldata proof = parseAccountInfoProof(encodedProof); ( bool exists, CoreTypes.BlockHeaderData memory head, CoreTypes.AccountData memory acc ) = verifyAccountAtBlock(proof.account, proof.accountProof, proof.header, proof.blockProof); require(exists, "Account does not exist at block"); if (proof.info == AccountInfo.StorageRoot) { return Fact( proof.account, FactSigs.accountStorageFactSig(head.Number, acc.StorageRoot), "" ); return Fact(proof.account, FactSigs.accountCodeHashFactSig(head.Number, acc.CodeHash), ""); return Fact( proof.account, FactSigs.accountBalanceFactSig(head.Number), abi.encodePacked(acc.Balance) ); return Fact( proof.account, FactSigs.accountNonceFactSig(head.Number), abi.encodePacked(acc.Nonce) ); return Fact(proof.account, FactSigs.accountFactSig(head.Number), abi.encode(acc)); revert("Unknown account info requested"); } }
8,371,514
pragma solidity ^0.4.24; import "./EventToken.sol"; contract EventContract{ using SafeMath for uint; enum EVENTSTATE {NOTACTIVE, ACTIVE, POSTPONEMENT, CANCELLATION, REPORTING, DISPUTED, SETTLED} string private _eventName; string private _eventLocation; uint private _eventDate; uint private _eventCreationDate; address private _buyer; address private _seller; uint8 private _noOfAllowedPostponements; mapping(address => uint256) private _escrows; uint256 private _sellerAdvanceFee; uint256 private _sellerCancellationPenalty; address[] private _arbiterAddressesBuyer; address[] private _arbiterAddressesSeller; address[] private _contributerAddressesBuyer; address[] private _contributerAddressesSeller; mapping(address => uint256) private _contributionPoolAmounts; mapping(address => mapping(address => uint256)) private _contributersAcknowledgement; uint private _eventPaymentAmount; EVENTSTATE private _eventState; address private _eventProtocolAddress; EventToken private _ETContract; address private _cancellingParty; uint256 private _eventProtocolCharges; //Helper data function mapping(address => mapping(address => bool)) private _isContributor; struct TKN { address sender; uint256 value; bytes data; bytes4 sig; } mapping(address => uint256) internal _transferredAmounts; TKN[] _transactionData; mapping(uint => mapping(address => bool)) private _postPoneRequest; mapping(address => uint8) private _resolveEvent; constructor (string eventName, string eventLocation, uint eventDate, address buyer, uint8 allowedPostponements, uint buyerEscrow, uint sellerEscrow, uint sellerAdvanceFee, uint sellerCancellationPenalty, uint buyerContributionPoolAmount, uint sellerContributionPoolAmount, uint eventPaymentAmount, address eventProtocolAddress, address eventTokenAddress) public{ require(eventDate > now); require(allowedPostponements < 3); require(buyer != address(0)); require(buyerEscrow > 0); require(sellerEscrow > 0); require(sellerAdvanceFee > 0); require(sellerCancellationPenalty > 0); require(buyerContributionPoolAmount > 0); require(sellerContributionPoolAmount > 0); require(eventPaymentAmount > 0); _eventName = eventName; _eventLocation = eventLocation; _eventDate = eventDate; _eventCreationDate = now; _buyer = buyer; _seller = msg.sender; _noOfAllowedPostponements = allowedPostponements; _escrows[_buyer] = buyerEscrow; _escrows[_seller] = sellerEscrow; _sellerAdvanceFee = sellerAdvanceFee; _sellerCancellationPenalty = sellerCancellationPenalty; _contributionPoolAmounts[_buyer] = buyerContributionPoolAmount; _contributionPoolAmounts[_seller] = sellerContributionPoolAmount; _eventProtocolAddress = eventProtocolAddress; _ETContract = EventToken(eventTokenAddress); _eventState = EVENTSTATE.NOTACTIVE; _eventProtocolCharges = SafeMath.div(SafeMath.mul(eventPaymentAmount, 5), 100); _eventPaymentAmount = eventPaymentAmount.sub(_eventProtocolCharges); } modifier onlyBuyer{ require(msg.sender == _buyer); _; } modifier onlySeller{ require(msg.sender == _seller); _; } modifier onlyBuyerAndSeller{ require(msg.sender == _buyer || msg.sender == _seller); _; } function tokenFallback(address _from, uint256 _value, bytes _data) public{ require(_eventState == EVENTSTATE.NOTACTIVE); TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); _transferredAmounts[_from] = _transferredAmounts[_from].add(_value); _transactionData.push(tkn); if(_transferredAmounts[_buyer] >= getBuyerActivationAmount() && _transferredAmounts[_seller] >= getSellerActivationAmount()){ _eventState = EVENTSTATE.ACTIVE; _ETContract.approve(_seller, _sellerAdvanceFee); _ETContract.transfer(_seller, _sellerAdvanceFee); _eventPaymentAmount = _eventPaymentAmount.sub(_sellerAdvanceFee); } } function getBuyerActivationAmount() public view returns (uint){ return _escrows[_buyer].add(_eventPaymentAmount).add(_eventProtocolCharges).add(_contributionPoolAmounts[_buyer]); } function getSellerActivationAmount() public view returns (uint){ return _escrows[_seller].add(_contributionPoolAmounts[_seller]).add(_sellerCancellationPenalty); } function submitPostponeRequest(uint newEventDate) public onlyBuyerAndSeller returns (bool){ require(_eventDate < newEventDate); require(_eventState == EVENTSTATE.ACTIVE || _eventState == EVENTSTATE.POSTPONEMENT); _postPoneRequest[newEventDate][msg.sender] = true; _eventState = EVENTSTATE.POSTPONEMENT; if (_postPoneRequest[newEventDate][_buyer] == true && _postPoneRequest[newEventDate][_seller] == true){ postPoneEvent(newEventDate); } return true; } function postPoneEvent(uint newEventDate) internal returns (bool){ _eventDate = newEventDate; require(_noOfAllowedPostponements > 0); _noOfAllowedPostponements = _noOfAllowedPostponements -1; _eventState = EVENTSTATE.ACTIVE; return true; } function submitResolveRequest(uint8 val) public onlyBuyerAndSeller returns (bool){ if (val == 2 && _eventDate > now){ _cancellingParty = msg.sender; _eventState = EVENTSTATE.CANCELLATION; } else{ _eventState = EVENTSTATE.REPORTING; } _resolveEvent[msg.sender] = val; return true; } function acknowledgeCancelRequest() public onlyBuyerAndSeller returns (bool){ require(_eventState == EVENTSTATE.CANCELLATION); require(_eventDate > now); _resolveEvent[msg.sender] = 2; cancelEvent(); } function cancelEvent() internal returns (bool){ require(_resolveEvent[_buyer] == 2); require(_resolveEvent[_seller] == 2); // If buyer cancels the event, the advance payment will be vested with the seller if (_cancellingParty == _buyer){ uint _sellerCharges = _escrows[_seller].add(_contributionPoolAmounts[_seller]).add(_sellerCancellationPenalty); uint _buyerCharges = _eventPaymentAmount.add(_escrows[_buyer]).add(_contributionPoolAmounts[_buyer]); payout(_eventProtocolCharges, _buyerCharges, _sellerCharges); } // If seller cancels the event, the cancellation fees will be p0aid back and advance may be paid back else{ uint _securityDepositSeller = _ETContract.allowance(_seller, address(this)); if (_sellerAdvanceFee > _escrows[_seller]){ uint _delta = _sellerAdvanceFee.sub(_escrows[_seller]); payout(_eventProtocolCharges, _escrows[_seller].add(_sellerCancellationPenalty).add(_eventPaymentAmount).add(_contributionPoolAmounts[_buyer]), _contributionPoolAmounts[_seller]); if (_delta < _securityDepositSeller){ _ETContract.transferFrom(_seller, _buyer, _delta); } //Security deposit has to be greater than 0 else if (_securityDepositSeller > 0){ _ETContract.transferFrom(_seller, _buyer, _securityDepositSeller); } } else{ _escrows[_seller] = _escrows[_seller].sub(_sellerAdvanceFee); payout(_eventProtocolCharges, _sellerAdvanceFee.add(_sellerCancellationPenalty).add(_contributionPoolAmounts[_buyer]), _escrows[_seller].add(_contributionPoolAmounts[_seller])); } } _eventState = EVENTSTATE.SETTLED; return true; } function completeResolve(uint8 val) public onlyBuyerAndSeller returns (bool){ require(_eventState == EVENTSTATE.REPORTING); require(now > _eventDate); _resolveEvent[msg.sender] = val; //Check if DISPUTED if (_resolveEvent[_buyer] == _resolveEvent[_seller]){ if (_resolveEvent[_buyer] == 1){ resolveContract(); } else{ cancelEvent(); } return true; } _eventState = EVENTSTATE.DISPUTED; return false; } function resolveContract() internal returns (bool){ //Pay balance to buyer (and the escrow amount if any) uint _sellerCharges = _eventPaymentAmount.add(_escrows[_seller]).add(_contributionPoolAmounts[_seller]).add(_sellerCancellationPenalty); uint _buyerCharges = _escrows[_buyer].add(_contributionPoolAmounts[_buyer]); payout(_eventProtocolCharges, _buyerCharges, _sellerCharges); _eventState = EVENTSTATE.SETTLED; return true; } function addContributers(address contributor) public onlyBuyerAndSeller returns (bool){ require(_eventState == EVENTSTATE.ACTIVE); require(_contributionPoolAmounts[msg.sender] > 0); _isContributor[msg.sender][contributor] = true; if (msg.sender == _buyer){ _contributerAddressesBuyer.push(contributor); return true; } _contributerAddressesSeller.push(contributor); return true; } function acknowledgeContributors(address contributor, uint256 _tokens) public onlyBuyerAndSeller returns (bool){ require(_eventState != EVENTSTATE.NOTACTIVE || _eventState != EVENTSTATE.POSTPONEMENT || _eventState != EVENTSTATE.SETTLED); require(_contributionPoolAmounts[msg.sender] >= _tokens); require(_isContributor[msg.sender][contributor] == true); _contributersAcknowledgement[msg.sender][contributor] = _contributersAcknowledgement[msg.sender][contributor].add(_tokens); _contributionPoolAmounts[msg.sender] = _contributionPoolAmounts[msg.sender].sub(_tokens); return true; } function payOutContributors(address _target) internal returns (bool){ address _beneficier; uint _val; if (_target == _buyer){ for (uint i = 0; i< _contributerAddressesBuyer.length; i++){ _beneficier = _contributerAddressesBuyer[i]; _val = _contributersAcknowledgement[_target][_beneficier]; if (_val > 0){ _ETContract.approve(_beneficier, _val); _ETContract.transfer(_beneficier, _val); } } } else{ for (i = 0; i< _contributerAddressesBuyer.length; i++){ _beneficier = _contributerAddressesSeller[i]; _val = _contributersAcknowledgement[_target][_beneficier]; if (_val > 0){ _ETContract.approve(_beneficier, _val); _ETContract.transfer(_beneficier, _val); } } } return true; } function payout(uint256 eventProtocolCharges, uint256 buyerAmount, uint256 sellerAmount) internal returns (bool){ payOutContributors(_buyer); payOutContributors(_seller); _ETContract.approve(_eventProtocolAddress, eventProtocolCharges); _ETContract.transfer(_eventProtocolAddress, eventProtocolCharges); if (buyerAmount > 0){ _ETContract.approve(_buyer, buyerAmount); _ETContract.transfer(_buyer, buyerAmount); } if (sellerAmount > 0){ _ETContract.approve(_seller, sellerAmount); _ETContract.transfer(_seller, sellerAmount); } return true; } function addArbiters(uint val) public returns (bool){ address arbiter = msg.sender; if (val == _resolveEvent[_buyer]){ _arbiterAddressesBuyer.push(arbiter); } else{ _arbiterAddressesSeller.push(arbiter); } if (_arbiterAddressesBuyer.length.add(_arbiterAddressesSeller.length) == 5){ makeArbitrationDecision(); } _eventState = EVENTSTATE.SETTLED; return true; } function makeArbitrationDecision() internal returns (bool){ if (_arbiterAddressesBuyer.length > _arbiterAddressesSeller.length){ // Buyer wins here (So advance, 50% of escrow of seller and cancellation fees for buyer rewarded) uint _securityDepositSeller = _ETContract.allowance(_seller, address(this)); uint _sellerEscrowHalf = SafeMath.div(_escrows[_seller], 2); uint arbiterCharges = SafeMath.div(_sellerEscrowHalf, _arbiterAddressesBuyer.length); if (_sellerAdvanceFee > _sellerEscrowHalf){ uint _delta = _sellerAdvanceFee.sub(_sellerEscrowHalf); payout(_eventProtocolCharges, _sellerEscrowHalf.add(_sellerCancellationPenalty).add(_contributionPoolAmounts[_buyer]).add(_eventPaymentAmount), _contributionPoolAmounts[_seller]); if (_delta < _securityDepositSeller){ _ETContract.transferFrom(_seller, _buyer, _delta); } else if(_securityDepositSeller > 0){ _ETContract.transferFrom(_seller, _buyer, _securityDepositSeller); } } else{ _escrows[_seller] = _escrows[_seller].sub(_sellerAdvanceFee).sub(_sellerEscrowHalf); payout(_eventProtocolCharges, _sellerAdvanceFee.add(_sellerCancellationPenalty).add(_sellerEscrowHalf).add(_contributionPoolAmounts[_buyer]), _escrows[_seller].add(_contributionPoolAmounts[_seller])); } for (uint i = 0; i< _arbiterAddressesBuyer.length; i++){ _ETContract.approve(_arbiterAddressesBuyer[i], arbiterCharges); _ETContract.transfer(_arbiterAddressesBuyer[i], arbiterCharges); } return true; } else{ // Seller wins (So 50% of escrow and event payment amount is paid) uint sellerCharges = SafeMath.div(_escrows[_buyer], 2).add(_contributionPoolAmounts[_seller]).add(_escrows[_seller]).add(_eventPaymentAmount); uint buyerCharges = _contributionPoolAmounts[_buyer]; arbiterCharges = SafeMath.div(_escrows[_buyer], _arbiterAddressesSeller.length); for ( i = 0; i< _arbiterAddressesSeller.length; i++){ //_ETContract.approve(_arbiterAddressesSeller[i], arbiterCharges); //_ETContract.transfer(_arbiterAddressesSeller[i], arbiterCharges); } payout(_eventProtocolCharges, buyerCharges, sellerCharges); return true; } } function getEventState() public view returns (EVENTSTATE){ return _eventState; } function getBuyer() public view returns (address){ return _buyer; } function getSeller() public view returns (address){ return _seller; } function getEventDate() public view returns (uint){ return _eventDate; } function getEventName() public view returns (string){ return _eventName; } function getEventLocation() public view returns (string){ return _eventLocation; } function getSellerAdvanceFee() public view returns (uint){ return _sellerAdvanceFee; } function getsellerCancellationPenalty() public view returns (uint){ return _sellerCancellationPenalty; } function getEventCreationDate() public view returns (uint){ return _eventCreationDate; } function getEventProtocolAddress() public view returns (address){ return _eventProtocolAddress; } function getEventProtocolCharges() public view returns (uint){ return _eventProtocolCharges; } function getEventPaymentCharges() public view returns (uint){ return _eventProtocolCharges.add(_eventPaymentAmount); } function getContributionPoolAmounts(address addr) public view returns (uint){ require(addr == _buyer || addr == _seller); return _contributionPoolAmounts[addr]; } function getContributionAmounts(address target, address contributor) public view returns (uint){ return _contributersAcknowledgement[target][contributor]; } function getContributorPoolSize(address target) public view returns (uint){ require(target == _buyer || target == _seller); if (target == _buyer){ return _contributerAddressesBuyer.length; } return _contributerAddressesSeller.length; } function getEscrowAmounts(address addr) public view returns (uint){ require(addr == _buyer || addr == _seller); return _escrows[addr]; } function getTokenAddress() public view returns (address){ return address(_ETContract); } function getSellerSecurityDeposit() public view returns (uint){ return _ETContract.allowance(_seller, address(this)); } function isContributor(address target, address contributor) public view returns (bool){ return _isContributor[target][contributor]; } function checkEventCompletion() public returns (bool){ require(now > _eventDate && _eventState == EVENTSTATE.ACTIVE); _eventState = EVENTSTATE.REPORTING; return true; } }
If buyer cancels the event, the advance payment will be vested with the seller If seller cancels the event, the cancellation fees will be p0aid back and advance may be paid backSecurity deposit has to be greater than 0
function cancelEvent() internal returns (bool){ require(_resolveEvent[_buyer] == 2); require(_resolveEvent[_seller] == 2); if (_cancellingParty == _buyer){ uint _sellerCharges = _escrows[_seller].add(_contributionPoolAmounts[_seller]).add(_sellerCancellationPenalty); uint _buyerCharges = _eventPaymentAmount.add(_escrows[_buyer]).add(_contributionPoolAmounts[_buyer]); payout(_eventProtocolCharges, _buyerCharges, _sellerCharges); } else{ uint _securityDepositSeller = _ETContract.allowance(_seller, address(this)); if (_sellerAdvanceFee > _escrows[_seller]){ uint _delta = _sellerAdvanceFee.sub(_escrows[_seller]); payout(_eventProtocolCharges, _escrows[_seller].add(_sellerCancellationPenalty).add(_eventPaymentAmount).add(_contributionPoolAmounts[_buyer]), _contributionPoolAmounts[_seller]); if (_delta < _securityDepositSeller){ _ETContract.transferFrom(_seller, _buyer, _delta); } else if (_securityDepositSeller > 0){ _ETContract.transferFrom(_seller, _buyer, _securityDepositSeller); } } else{ _escrows[_seller] = _escrows[_seller].sub(_sellerAdvanceFee); payout(_eventProtocolCharges, _sellerAdvanceFee.add(_sellerCancellationPenalty).add(_contributionPoolAmounts[_buyer]), _escrows[_seller].add(_contributionPoolAmounts[_seller])); } } _eventState = EVENTSTATE.SETTLED; return true; }
12,887,899
pragma solidity ^0.4.13; contract Crowdsale { using SafeMath for uint256; address constant public TOKEN_OWNER = 0x57Cdd07287f668eC4D58f3E362b4FCC2bC54F5b8; //Token Owner address constant public WALLET = 0x1513F644590d866e25490687AB1b3Ad262d5b6dF; //Investment storage; uint256 constant public MINSALESCAP = 200 ether; uint256 constant public MAXSALESCAP = 126000 ether; uint256 constant public STARTDATE = 1533686401; //Friday, Wednesday, August 8, 2018 2:00:01 AM uint256 constant public ENDDATE = 1543536060; // November 30, 2018 12:01:00 AM uint256 constant public FXRATE = 50000; uint256 constant public MINCONTRIBUTION = 5000000000000 wei; //0,005 eth //set on deployment address public TOKEN; address public owner; uint256 public weiRaised; enum State { Running, Expired, Funded } State public state; struct ContributorStruct { bool whitelisted; uint256 contributions; } mapping(address => ContributorStruct) public whitelist; modifier isContributor() {require(whitelist[msg.sender].contributions > 0x00); _;} modifier isOwner() {require(msg.sender == owner); _;} modifier inState(State _state) {require(state == _state); _;} modifier inPaymentLimits(uint256 _payment) {require(_payment >= MINCONTRIBUTION); _;} modifier inWhitelist(address _contributor) {require(whitelist[_contributor].whitelisted == true); _;} event WhitelistingLog(address indexed _contributor); event RefundLog(address indexed _contributor, uint256 _amount); event PurchaseLog(address indexed _contributor, address indexed _beneficiary, uint256 _amount); constructor (address _token) public { require(_token != address(0x00)); owner = msg.sender; TOKEN = _token; } function () public payable { _updateStateIfExpired(); } //available only to whitelisted addresses after startBlock function buyTokens(address _beneficiary) public inState(State.Running) inPaymentLimits(msg.value) inWhitelist(_beneficiary) payable returns (bool success) { require(_beneficiary != address(0x00)); assert(block.timestamp >= STARTDATE); //check if sale has started uint256 tokenAmount = _calculateTokenAmount(msg.value); YOUToken token = YOUToken(TOKEN); weiRaised = weiRaised.add(msg.value); whitelist[_beneficiary].contributions = whitelist[_beneficiary].contributions.add(msg.value); if (!token.mint.gas(700000)(_beneficiary, tokenAmount)) { return false; } if (weiRaised >= MAXSALESCAP || weiRaised >= MINSALESCAP && block.timestamp >= ENDDATE) { state = State.Funded; } else { _updateStateIfExpired(); } emit PurchaseLog(msg.sender, _beneficiary, msg.value); return true; } //available to contributers after deadline and only if unfunded //if contributer used a different address as _beneficiary, only this address can claim refund function refund(address _contributor) public isContributor inState(State.Expired) returns (bool success) { require(_contributor != address(0x00)); uint256 amount = whitelist[_contributor].contributions; whitelist[_contributor].contributions = 0x00; _contributor.transfer(amount); emit RefundLog(_contributor, amount); return true; } //as owner, whitelist individual address function whitelistAddr(address _contributor) public isOwner returns(bool) { require(_contributor != address(0x00)); // whitelist[_contributor] = true; whitelist[_contributor].whitelisted = true; emit WhitelistingLog(_contributor); return true; } //in cases where funds are not payed in ETH to this contract, //as owner, whitelist and give tokens to address. function whitelistAddrAndBuyTokens(address _contributor, uint256 _weiAmount) public isOwner returns(bool) { require(_contributor != address(0x00)); uint256 tokenAmount = _calculateTokenAmount(_weiAmount); YOUToken token = YOUToken(TOKEN); whitelist[_contributor].whitelisted = true; weiRaised = weiRaised.add(_weiAmount); if (!token.mint.gas(700000)(_contributor, tokenAmount)) { return false; } emit WhitelistingLog(_contributor); return true; } //withdraw Funds only if funded, as owner function withdraw() public isOwner inState(State.Funded) { WALLET.transfer(address(this).balance); } function delistAddress(address _contributor) public isOwner inState(State.Running) returns (bool) { require(_contributor != address(0x00)); require(whitelist[_contributor].whitelisted); whitelist[_contributor].whitelisted = false; return true; } function emergencyStop() public isOwner inState(State.Running) { //prevent more contributions and allow refunds state = State.Expired; } function transferOwnership() public isOwner inState(State.Running) { //after deployment is complete run once owner = TOKEN_OWNER; } function _updateStateIfExpired() internal { if ((block.timestamp >= ENDDATE && state == State.Running) || (block.timestamp >= ENDDATE && weiRaised < MINSALESCAP)) { state = State.Expired; } } function _calculateTokenAmount(uint256 _weiAmount) internal view returns (uint256 tokenAmount) { uint256 discount; if (block.timestamp <= 1535241660) { if (_weiAmount >= 1700 ether) { discount = 30; } else if (_weiAmount > 0.2 ether) { discount = 25; } } else if (block.timestamp <= 1537747260) { discount = 15; } else if (block.timestamp <= 1540339260) { discount = 10; } else if (block.timestamp <= 1543536060) { discount = 5; } _weiAmount = _weiAmount.mul(discount).div(100).add(_weiAmount); return _weiAmount.mul(FXRATE); } } library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } } contract YOUToken { function mint(address _to, uint256 _amount) public returns (bool); function transferOwnership(address _newOwner) public; }
available to contributers after deadline and only if unfundedif contributer used a different address as _beneficiary, only this address can claim refund
function refund(address _contributor) public isContributor inState(State.Expired) returns (bool success) { require(_contributor != address(0x00)); uint256 amount = whitelist[_contributor].contributions; whitelist[_contributor].contributions = 0x00; _contributor.transfer(amount); emit RefundLog(_contributor, amount); return true; }
12,745,655
pragma solidity ^0.4.20; /* Built for the community. Supported by the community. “Equality... is when you don&#39;t feel the existence of word” Talees Rizvi “The world is round so that friendship may encircle it.” Pierre Teilhard de Chardin What? We are a clone simple as that. But we differentiate in the way we pay our divs. More for the community. - Buys - 35% fee goes to all current token holders. - Sells - 15% fee to all current tokens holders. And it’s lower because you shouldn’t have to pay the sane fee exiting. You deserve more. - Transfers - 0% fee! We have plans for games and we don&#39;t want that to be an obstacle! - Masternode - you get 7% from deposit of all players who enter using your Masternode . Who toiled night and day on this project to make this possible for you? Clumsier - solidity developer, website Bungalogic - website developer, concept and design, graphics. */ contract ProofOfCommunity { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won&#39;t reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "ProofOfCommunity"; string public symbol = "POC"; uint8 constant public decimals = 18; uint8 constant internal entryFee_ = 35; // 35% to enter our community uint8 constant internal refferalFee_ = 20; // 20% from enter fee divs or 7% for each invite, great for inviting new members for our community uint8 constant internal exitFee_ = 15; // 15% for selling uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 20 ether; // referral program mapping(address => uint256) internal referrals; mapping(address => bool) internal isUser; address[] public usersAddresses; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function ProofOfCommunity() public { // add administrators here with their wallets // bungalogic // Website developer, concept and design. Community administrators[0xBa21d01125D6932ce8ABf3625977899Fd2C7fa30] = true; ambassadors_[0xBa21d01125D6932ce8ABf3625977899Fd2C7fa30] = true; // clumsier // Solidity Developer, website, PoG administrators[msg.sender] = true; ambassadors_[msg.sender] = true; } /** * 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); } /** * 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); } /* Converts all of caller&#39;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); } /* 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(); } /* 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); } /* 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); } /* Transfer tokens from the caller to a new holder. * No fee! */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } function referralsOf(address _customerAddress) public view returns(uint256) { return referrals[_customerAddress]; } function totalUsers() public view returns(uint256) { return usersAddresses.length; } /** * 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) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy 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; } } /** * Return the sell 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; } } /** * 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; } /** * 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 = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) 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 Kekly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); if (isUser[_customerAddress] == false) { referrals[_referredBy]++; } } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } if (isUser[_customerAddress] == false ) { isUser[_customerAddress] = true; usersAddresses.push(_customerAddress); } // we can&#39;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&#39;t deserve dividends for the tokens before they owned them; //really i know you think you do but you don&#39;t int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It&#39;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; } /** * Calculate token sell value. * It&#39;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; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint 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&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
-- APPLICATION ENTRY POINTS --/ add administrators here with their wallets bungalogic Website developer, concept and design. Community clumsier Solidity Developer, website, PoG
function ProofOfCommunity() public { administrators[0xBa21d01125D6932ce8ABf3625977899Fd2C7fa30] = true; ambassadors_[0xBa21d01125D6932ce8ABf3625977899Fd2C7fa30] = true; administrators[msg.sender] = true; ambassadors_[msg.sender] = true; }
8,028,614
./full_match/5/0xABcD3bf0685d110A659FcF49c87bD2334727c8a4/sources/src/finance/royalty/IRoyaltyEnforcementAdmin.sol
Manages if royalties are enforced by blocklisting marketplaces with optional royalty. Derived from 'operator-filter-registry' NPM repository by OpenSea./
interface IRoyaltyEnforcementAdmin { function toggleRoyaltyEnforcement(bool enforce) external; function registerRoyaltyEnforcement(address subscriptionOrRegistrantToCopy, bool subscribe) external; }
1,895,189
./full_match/43114/0x6351C5c0F6A7b9519F459d7C98aADA73594Ced5a/sources/perklefarms.sol
Returns whether an operation is ready or not./ solhint-disable-next-line not-rely-on-time
function isOperationReady(bytes32 id) public view returns (bool ready) { return _timestamps[id] > _DONE_TIMESTAMP && _timestamps[id] <= block.timestamp; }
4,608,766
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; /// @title An Auction Contract for bidding and selling single and batched NFTs /// @author Avo Labs GmbH /// @notice This contract can be used for auctioning any NFTs, and accepts any ERC20 token as payment contract NFTERC1155Auction is ERC1155Holder, Ownable{ enum MARKETSTATE{CLOSEALL,OPENALL, OPENAUCTION, OPENLIMITORDER } enum ORDERTYPE{ AUCTION, LIMITORDER} address[] private payTokens = [0x0000000000000000000000000000000000001000]; address[] public feeRecipients = [0x0000000000000000000000000000000000001000]; uint32[] public feePercentages = [500]; mapping(address => mapping(uint256 => mapping(address => Auction))) public nftContractAuctions; mapping(address => mapping(uint256 => mapping(address => address))) public nftOwner; mapping(address => uint256) failedTransferCredits; //Each Auction is unique to each NFT (contract + id pairing). struct Auction { //map token ID to uint256 orderType; uint256 minPrice; uint256 buyNowPrice; uint256 amount; uint256 auctionBidPeriod; //Increments the length of time the auction is open in which a new bid can be made after each bid. uint256 auctionEnd; uint256 nftHighestBid; uint256 bidIncreasePercentage; uint256[] batchTokenIds; // The first token in the batch is used to identify the auction (contract + id pairing). uint256[] batchAmounts; uint32[] feePercentages; address nftHighestBidder; address nftSeller; address whitelistedBuyer; //The seller can specify a whitelisted address for a sale (this is effectively a direct sale). address nftRecipient; //The bidder can specify a recipient for the NFT if their bid is successful. address ERC20Token; // The seller can specify an ERC20 token that can be used to bid or purchase the NFT. address[] feeRecipients; } struct NFT { address nftContractAddress; uint256 tokenId; address nftSellerAddress; } /* * Default values that are used if not specified by the NFT seller. */ uint256 public defaultBidIncreasePercentage; uint256 public defaultAuctionBidPeriod; uint256 public minimumSettableIncreasePercentage; uint256 public maximumMinPricePercentage; uint256 public marketState = uint(MARKETSTATE.OPENLIMITORDER); /*╔═════════════════════════════╗ ║ EVENTS ║ ╚═════════════════════════════╝*/ event NftAuctionCreated( uint256 orderType, address nftContractAddress, uint256 tokenId, uint256 amount, address nftSeller, address erc20Token, uint256 minPrice, uint256 buyNowPrice, uint256 auctionBidPeriod, uint256 bidIncreasePercentage, address[] feeRecipients, uint32[] feePercentages ); event NftBatchAuctionCreated( uint256 orderType, address nftContractAddress, uint256 masterTokenId, uint256[] batchTokens, uint256[] batchAmounts, address nftSeller, address erc20Token, uint256 minPrice, uint256 buyNowPrice, uint256 auctionBidPeriod, uint256 bidIncreasePercentage, address[] feeRecipients, uint32[] feePercentages ); event SaleCreated( uint256 orderType, address nftContractAddress, uint256 tokenId, uint256 amount, address nftSeller, address erc20Token, uint256 buyNowPrice, address whitelistedBuyer, address[] feeRecipients, uint32[] feePercentages ); event BatchSaleCreated( uint256 orderType, address nftContractAddress, uint256 masterTokenId, uint256[] batchTokens, uint256[] batchAmounts, address nftSeller, address erc20Token, uint256 buyNowPrice, address whitelistedBuyer, address[] feeRecipients, uint32[] feePercentages ); event BidMade( address nftContractAddress, uint256 tokenId, address nftSellerAddress, address bidder, uint256 ethAmount, address erc20Token, uint256 tokenAmount ); event AuctionPeriodUpdated( address nftContractAddress, uint256 tokenId, address nftSellerAddress, uint256 auctionEndPeriod ); event NFTTransferredAndSellerPaid( address nftContractAddress, uint256 tokenId, address nftSellerAddress, address nftSeller, uint256 nftHighestBid, address nftHighestBidder, address nftRecipient ); event AuctionSettled( address nftContractAddress, uint256 tokenId, address nftSellerAddress, address auctionSettler ); event NFTWithdrawn( address nftContractAddress, uint256 tokenId, address nftSeller ); event BidWithdrawn( address nftContractAddress, uint256 tokenId, address highestBidder ); event WhitelistedBuyerUpdated( address nftContractAddress, uint256 tokenId, address nftSellerAddress, address newWhitelistedBuyer ); event MinimumPriceUpdated( address nftContractAddress, uint256 tokenId, address nftSellerAddress, uint256 newMinPrice ); event BuyNowPriceUpdated( address nftContractAddress, uint256 tokenId, address nftSellerAddress, uint256 newBuyNowPrice ); event HighestBidTaken(address nftContractAddress, uint256 tokenId,address nftSellerAddress); /**********************************/ /*╔═════════════════════════════╗ ║ END ║ ║ EVENTS ║ ╚═════════════════════════════╝*/ /**********************************/ /*╔═════════════════════════════╗ ║ MODIFIERS ║ ╚═════════════════════════════╝*/ modifier priceGreaterThanZero(uint256 _price) { require(_price > 0, "Price cannot be 0"); _; } /* * The minimum price must be 80% of the buyNowPrice(if set). */ modifier minPriceDoesNotExceedLimit( uint256 _buyNowPrice, uint256 _minPrice ) { require( _buyNowPrice == 0 || _getPortionOfBid(_buyNowPrice, maximumMinPricePercentage) >= _minPrice, "Min price cannot exceed 80% of buyNowPrice" ); _; } /* * NFTs in a batch must contain between 2 and 100 NFTs */ modifier batchWithinLimits(uint256 _batchTokenIdsLength) { require( _batchTokenIdsLength > 1 && _batchTokenIdsLength <= 100, "Number of NFTs not applicable for batch sale/auction" ); _; } modifier notZeroAddress(address _address) { require(_address != address(0), "cannot specify 0 address"); _; } modifier increasePercentageAboveMinimum(uint256 _bidIncreasePercentage) { require( _bidIncreasePercentage >= minimumSettableIncreasePercentage, "Bid increase percentage must be greater than minimum settable increase percentage" ); _; } modifier isFeePercentagesLessThanMaximum(uint32[] memory _feePercentages) { uint32 totalPercent; for (uint256 i = 0; i < _feePercentages.length; i++) { totalPercent = totalPercent + _feePercentages[i]; } require(totalPercent <= 10000, "fee percentages exceed maximum"); _; } modifier correctFeeRecipientsAndPercentages( uint256 _recipientsLength, uint256 _percentagesLength ) { require( _recipientsLength == _percentagesLength, "mismatched fee recipients and percentages" ); _; } /**********************************/ /*╔═════════════════════════════╗ ║ END ║ ║ MODIFIERS ║ ╚═════════════════════════════╝*/ /**********************************/ // constructor constructor() { defaultBidIncreasePercentage = 1000; defaultAuctionBidPeriod = 86400; //1 day minimumSettableIncreasePercentage = 500; maximumMinPricePercentage = 8000; } /*╔══════════════════════════════╗ ║ AUCTION CHECK FUNCTIONS ║ ╚══════════════════════════════╝*/ function _notOnSale(NFT memory _nft) internal view { require( address(0) == nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftSeller, "On sale" ); } function _onSale(NFT memory _nft) internal view { require( address(0) != nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftSeller, "No sale" ); } function _notNftSeller(NFT memory _nft) internal view { require( msg.sender != nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftSeller, "Owner cannot bid on own NFT" ); } function _onlyNftSeller(NFT memory _nft) internal view { require( msg.sender == nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftSeller, "Only the owner can call this function" ); } /* * Payment is accepted if the payment is made in the ERC20 token or ETH specified by the seller. * Early bids on NFTs not yet up for auction must be made in ETH. */ function _paymentAccepted(NFT memory _nft,address _erc20Token,uint256 _tokenAmount) internal view { require( _isPaymentAccepted( _nft, _erc20Token, _tokenAmount ), "Bid to be made in quantities of specified token or eth" ); } function _isAuctionOver(NFT memory _nft) internal view { require( !_isAuctionOngoing(_nft), "Auction is not yet over" ); } function payTokensLimits(address _erc20Token) internal view { bool support = false; for (uint256 i = 0; i < payTokens.length; i++) { if(payTokens[i] == _erc20Token) { support = true; break; } } require(support==true, "This token payment is not currently supported" ); } function _isAuctionOngoing(NFT memory _nft) internal view returns (bool) { uint256 auctionEndTimestamp = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].auctionEnd; //if the auctionEnd is set to 0, the auction is technically on-going, however //the minimum bid price (minPrice) has not yet been met. return (auctionEndTimestamp == 0 || block.timestamp < auctionEndTimestamp); } /* * Check if a bid has been made. This is applicable in the early bid scenario * to ensure that if an auction is created after an early bid, the auction * begins appropriately or is settled if the buy now price is met. */ function _isABidMade(NFT memory _nft) internal view returns (bool) { return (nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBid > 0); } /* *if the minPrice is set by the seller, check that the highest bid meets or exceeds that price. */ function _isMinimumBidMade(NFT memory _nft) internal view returns (bool) { uint256 minPrice = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].minPrice; return minPrice > 0 && (nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBid >= minPrice); } /* * If the buy now price is set by the seller, check that the highest bid meets that price. */ function _isBuyNowPriceMet(NFT memory _nft) internal view returns (bool) { uint256 buyNowPrice = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress] .buyNowPrice; return buyNowPrice > 0 && nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBid >= buyNowPrice; } /* * Check that a bid is applicable for the purchase of the NFT. * In the case of a sale: the bid needs to meet the buyNowPrice. * In the case of an auction: the bid needs to be a % higher than the previous bid. */ function _doesBidMeetBidRequirements( NFT memory _nft, uint256 _tokenAmount ) internal view returns (bool) { uint256 buyNowPrice = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].buyNowPrice; //if buyNowPrice is met, ignore increase percentage if (buyNowPrice > 0 && (msg.value >= buyNowPrice || _tokenAmount >= buyNowPrice) ) { return true; } //if the NFT is up for auction, the bid needs to be a % higher than the previous bid uint256 bidIncreaseAmount = (nftContractAuctions[_nft.nftContractAddress][_nft.tokenId ][_nft.nftSellerAddress].nftHighestBid * (10000 + _getBidIncreasePercentage(_nft))) / 10000; return (msg.value >= bidIncreaseAmount || _tokenAmount >= bidIncreaseAmount); } /* * An NFT is up for sale if the buyNowPrice is set, but the minPrice is not set. * Therefore the only way to conclude the NFT sale is to meet the buyNowPrice. */ function _isASale(NFT memory _nft) internal view returns (bool) { return (nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].buyNowPrice > 0 && nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].minPrice == 0); } function _isWhitelistedSale(NFT memory _nft) internal view returns (bool) { return (nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress] .whitelistedBuyer != address(0)); } /* * The highest bidder is allowed to purchase the NFT if * no whitelisted buyer is set by the NFT seller. * Otherwise, the highest bidder must equal the whitelisted buyer. */ function _isHighestBidderAllowedToPurchaseNFT( NFT memory _nft ) internal view returns (bool) { return (!_isWhitelistedSale(_nft)) || _isHighestBidderWhitelisted(_nft); } function _isHighestBidderWhitelisted( NFT memory _nft ) internal view returns (bool) { return (nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBidder == nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].whitelistedBuyer); } /** * Payment is accepted in the following scenarios: * (1) Auction already created - can accept ETH or Specified Token * --------> Cannot bid with ETH & an ERC20 Token together in any circumstance<------ * (2) Auction not created - only ETH accepted (cannot early bid with an ERC20 Token * (3) Cannot make a zero bid (no ETH or Token amount) */ function _isPaymentAccepted( NFT memory _nft, address _bidERC20Token, uint256 _tokenAmount ) internal view returns (bool) { address auctionERC20Token = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId ][_nft.nftSellerAddress].ERC20Token; if (_isERC20Auction(auctionERC20Token)) { return msg.value == 0 && auctionERC20Token == _bidERC20Token && _tokenAmount > 0; } else { return msg.value != 0 && _bidERC20Token == address(0) && _tokenAmount == 0; } } function _isERC20Auction(address _auctionERC20Token) internal pure returns (bool) { return _auctionERC20Token != address(0) ; } /* * Returns the percentage of the total bid (used to calculate fee payments) */ function _getPortionOfBid(uint256 _totalBid, uint256 _percentage) internal pure returns (uint256) { return (_totalBid * (_percentage)) / 10000; } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ AUCTION CHECK FUNCTIONS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ DEFAULT GETTER FUNCTIONS ║ ╚══════════════════════════════╝*/ /***************************************************************** * These functions check if the applicable auction parameter has * * been set by the NFT seller. If not, return the default value. * *****************************************************************/ function _getBidIncreasePercentage( NFT memory _nft ) internal view returns (uint256) { uint256 bidIncreasePercentage = nftContractAuctions[ _nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].bidIncreasePercentage; if (bidIncreasePercentage == 0) { return defaultBidIncreasePercentage; } else { return bidIncreasePercentage; } } function _getAuctionBidPeriod(NFT memory _nft) internal view returns (uint256) { uint256 auctionBidPeriod = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].auctionBidPeriod; if (auctionBidPeriod == 0) { return defaultAuctionBidPeriod; } else { return auctionBidPeriod; } } /* * The default value for the NFT recipient is the highest bidder */ function _getNftRecipient(NFT memory _nft) internal view returns (address) { address nftRecipient = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftRecipient; if (nftRecipient == address(0)) { return nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBidder; } else { return nftRecipient; } } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ DEFAULT GETTER FUNCTIONS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ TRANSFER NFTS TO CONTRACT ║ ╚══════════════════════════════╝*/ function _transferNftToAuctionContract( address _nftContractAddress, uint256 _tokenId, uint256 _amount ) internal { IERC1155(_nftContractAddress).safeTransferFrom( msg.sender, address(this), _tokenId, _amount, "0x0" ); } function _transferNftBatchToAuctionContract( address _nftContractAddress, uint256[] memory _batchTokenIds, uint256[] memory _batchAmounts ) internal { IERC1155(_nftContractAddress).safeBatchTransferFrom( msg.sender, address(this), _batchTokenIds, _batchAmounts, "0x0" ); for (uint256 i = 0; i < _batchTokenIds.length; i++) { if (i != 0) { //Don't set the first one because we set this later as the NFTSeller parameter in the struct nftOwner[_nftContractAddress][_batchTokenIds[i]][msg.sender] = msg.sender; } } _reverseAndResetPreviousBid(NFT(_nftContractAddress, _batchTokenIds[0],msg.sender)); nftContractAuctions[_nftContractAddress][_batchTokenIds[0]][msg.sender].batchTokenIds = _batchTokenIds; nftContractAuctions[_nftContractAddress][_batchTokenIds[0]][msg.sender].batchAmounts = _batchAmounts; } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ TRANSFER NFTS TO CONTRACT ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ AUCTION CREATION ║ ╚══════════════════════════════╝*/ /** * Setup parameters applicable to all auctions and whitelised sales: * -> ERC20 Token for payment (if specified by the seller) : _erc20Token * -> minimum price : _minPrice * -> buy now price : _buyNowPrice * -> the nft seller: msg.sender * -> The fee recipients & their respective percentages for a sucessful auction/sale */ function _setupAuction( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice ) internal minPriceDoesNotExceedLimit(_buyNowPrice, _minPrice) correctFeeRecipientsAndPercentages( feeRecipients.length, feePercentages.length ) isFeePercentagesLessThanMaximum(feePercentages) { _notOnSale(NFT(_nftContractAddress,_tokenId,msg.sender)); if (_erc20Token != address(0)) { nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .ERC20Token = _erc20Token; } nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .orderType = uint(ORDERTYPE.AUCTION); nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .amount = _amount; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .feeRecipients = feeRecipients; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .feePercentages = feePercentages; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .buyNowPrice = _buyNowPrice; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .minPrice = _minPrice; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .nftSeller = msg.sender; } function _createNewNftAuction( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice ) internal { // Sending the NFT to this contract _transferNftToAuctionContract(_nftContractAddress, _tokenId,_amount); _setupAuction( _nftContractAddress, _tokenId, _amount, _erc20Token, _minPrice, _buyNowPrice ); NFT memory nft = NFT(_nftContractAddress, _tokenId,msg.sender); emit NftAuctionCreated( uint(ORDERTYPE.AUCTION), _nftContractAddress, _tokenId, _amount, msg.sender, _erc20Token, _minPrice, _buyNowPrice, _getAuctionBidPeriod(nft), _getBidIncreasePercentage(nft), feeRecipients, feePercentages ); _updateOngoingAuction(nft); } function createNewNftAuction( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice, uint256 _auctionBidPeriod, //this is the time that the auction lasts until another bid occurs uint256 _bidIncreasePercentage ) external priceGreaterThanZero(_minPrice) increasePercentageAboveMinimum(_bidIncreasePercentage) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); payTokensLimits(_erc20Token); nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .auctionBidPeriod = _auctionBidPeriod; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .bidIncreasePercentage = _bidIncreasePercentage; _createNewNftAuction( _nftContractAddress, _tokenId, _amount, _erc20Token, _minPrice, _buyNowPrice ); } function _createBatchNftAuction( address _nftContractAddress, uint256[] memory _batchTokenIds, uint256[] memory _batchAmounts, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice ) internal { _transferNftBatchToAuctionContract(_nftContractAddress, _batchTokenIds,_batchAmounts); _setupAuction( _nftContractAddress, _batchTokenIds[0], 0, _erc20Token, _minPrice, _buyNowPrice ); NFT memory nft = NFT(_nftContractAddress, _batchTokenIds[0],msg.sender); uint256 auctionBidPeriod = _getAuctionBidPeriod(nft); uint256 bidIncreasePercentage = _getBidIncreasePercentage(nft); emit NftBatchAuctionCreated( uint(ORDERTYPE.AUCTION), _nftContractAddress, _batchTokenIds[0], _batchTokenIds, _batchAmounts, msg.sender, _erc20Token, _minPrice, _buyNowPrice, auctionBidPeriod, bidIncreasePercentage, feeRecipients, feePercentages ); } /* * Create an auction for multiple NFTs in a batch. * The first token in the batch is used as the identifier for the auction. * Users must be aware of this tokenId when creating a batch auction. */ function createBatchNftAuction( address _nftContractAddress, uint256[] memory _batchTokenIds, uint256[] memory _batchAmounts, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice, uint256 _auctionBidPeriod, //this is the time that the auction lasts until another bid occurs uint256 _bidIncreasePercentage ) external priceGreaterThanZero(_minPrice) batchWithinLimits(_batchTokenIds.length) increasePercentageAboveMinimum(_bidIncreasePercentage) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); payTokensLimits(_erc20Token); nftContractAuctions[_nftContractAddress][_batchTokenIds[0]][msg.sender] .auctionBidPeriod = _auctionBidPeriod; nftContractAuctions[_nftContractAddress][_batchTokenIds[0]][msg.sender] .bidIncreasePercentage = _bidIncreasePercentage; _createBatchNftAuction( _nftContractAddress, _batchTokenIds, _batchAmounts, _erc20Token, _minPrice, _buyNowPrice ); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ AUCTION CREATION ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ SALES ║ ╚══════════════════════════════╝*/ /******************************************************************** * Allows for a standard sale mechanism where the NFT seller can * * can select an address to be whitelisted. This address is then * * allowed to make a bid on the NFT. No other address can bid on * * the NFT. * ********************************************************************/ function _setupSale( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer, uint256 _orderType ) internal correctFeeRecipientsAndPercentages( feeRecipients.length, feePercentages.length ) isFeePercentagesLessThanMaximum(feePercentages) { _notOnSale(NFT(_nftContractAddress,_tokenId,msg.sender)); if (_erc20Token != address(0)) { nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .ERC20Token = _erc20Token; } nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .orderType =_orderType==0? uint(ORDERTYPE.AUCTION):uint(ORDERTYPE.LIMITORDER); nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .amount = _amount; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .feeRecipients = feeRecipients; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .feePercentages = feePercentages; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .buyNowPrice = _buyNowPrice; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .whitelistedBuyer = _whitelistedBuyer; nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .nftSeller = msg.sender; } function createSale( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); payTokensLimits(_erc20Token); _transferNftToAuctionContract(_nftContractAddress, _tokenId,_amount); //min price = 0 _setupSale( _nftContractAddress, _tokenId, _amount, _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.AUCTION) ); emit SaleCreated( uint(ORDERTYPE.AUCTION), _nftContractAddress, _tokenId, _amount, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); NFT memory nft = NFT(_nftContractAddress, _tokenId,msg.sender); //check if buyNowPrice is meet and conclude sale, otherwise reverse the early bid if (_isABidMade(nft)) { if ( //we only revert the underbid if the seller specifies a different //whitelisted buyer to the highest bidder _isHighestBidderAllowedToPurchaseNFT(nft) ) { if (_isBuyNowPriceMet(nft)) { _transferNftAndPaySeller(nft); } } else { _reverseAndResetPreviousBid(nft); } } } function createBatchSale( address _nftContractAddress, uint256[] memory _batchTokenIds, uint256[] memory _batchAmounts, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) batchWithinLimits(_batchTokenIds.length) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); payTokensLimits(_erc20Token); _transferNftBatchToAuctionContract(_nftContractAddress, _batchTokenIds,_batchAmounts); _setupSale( _nftContractAddress, _batchTokenIds[0], 0, _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.AUCTION) ); emit BatchSaleCreated( uint(ORDERTYPE.AUCTION), _nftContractAddress, _batchTokenIds[0], _batchTokenIds, _batchAmounts, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); } function createSaleLimitOrder( address _nftContractAddress, uint256 _tokenId, uint256 _amount, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENLIMITORDER))), "The market is not open"); payTokensLimits(_erc20Token); _transferNftToAuctionContract(_nftContractAddress, _tokenId,_amount); //min price = 0 _setupSale( _nftContractAddress, _tokenId, _amount, _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.LIMITORDER) ); emit SaleCreated( uint(ORDERTYPE.LIMITORDER), _nftContractAddress, _tokenId, _amount, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); NFT memory nft = NFT(_nftContractAddress, _tokenId,msg.sender); //check if buyNowPrice is meet and conclude sale, otherwise reverse the early bid if (_isABidMade(nft)) { if ( //we only revert the underbid if the seller specifies a different //whitelisted buyer to the highest bidder _isHighestBidderAllowedToPurchaseNFT(nft) ) { if (_isBuyNowPriceMet(nft)) { _transferNftAndPaySeller(nft); } } else { _reverseAndResetPreviousBid(nft); } } } function createBatchSaleLimitOrder( address _nftContractAddress, uint256[] memory _batchTokenIds, uint256[] memory _batchAmounts, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) batchWithinLimits(_batchTokenIds.length) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENLIMITORDER))), "The market is not open"); payTokensLimits(_erc20Token); _transferNftBatchToAuctionContract(_nftContractAddress, _batchTokenIds,_batchAmounts); _setupSale( _nftContractAddress, _batchTokenIds[0], 0, _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.LIMITORDER) ); emit BatchSaleCreated( uint(ORDERTYPE.LIMITORDER), _nftContractAddress, _batchTokenIds[0], _batchTokenIds, _batchAmounts, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ SALES ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔═════════════════════════════╗ ║ BID FUNCTIONS ║ ╚═════════════════════════════╝*/ /******************************************************************** * Make bids with ETH or an ERC20 Token specified by the NFT seller.* * Additionally, a buyer can pay the asking price to conclude a sale* * of an NFT. * ********************************************************************/ function _makeBid( address _nftContractAddress, uint256 _tokenId, address _nftSellerAddress, address _erc20Token, uint256 _tokenAmount ) internal { if(nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].orderType == uint(ORDERTYPE.LIMITORDER) && nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].ERC20Token != address(0)) _tokenAmount = nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].buyNowPrice; if(nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].orderType == uint(ORDERTYPE.LIMITORDER) && nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].ERC20Token == address(0)) { require( msg.value>=nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].buyNowPrice, "Insufficient amount" ); } NFT memory nft = NFT(_nftContractAddress, _tokenId, _nftSellerAddress); _onSale(nft); _notNftSeller(nft); _paymentAccepted(nft,_erc20Token,_tokenAmount); require( _doesBidMeetBidRequirements( nft, _tokenAmount ), "Not enough funds to bid on NFT" ); _reversePreviousBidAndUpdateHighestBid( nft, _tokenAmount ); emit BidMade( _nftContractAddress, _tokenId, _nftSellerAddress, msg.sender, msg.value, _erc20Token, _tokenAmount ); _updateOngoingAuction(nft); } function makeBid( address _nftContractAddress, uint256 _tokenId, address _nftSellerAddress, address _erc20Token, uint256 _tokenAmount ) external payable { NFT memory nft = NFT(_nftContractAddress, _tokenId, _nftSellerAddress); require( _isAuctionOngoing(nft), "Auction has ended" ); require( !_isWhitelistedSale(nft) || nftContractAuctions[nft.nftContractAddress][nft.tokenId][nft.nftSellerAddress] .whitelistedBuyer == msg.sender, "only the whitelisted buyer can bid on this NFT" ); _makeBid(_nftContractAddress, _tokenId,_nftSellerAddress, _erc20Token, _tokenAmount); } function makeCustomBid( address _nftContractAddress, uint256 _tokenId, address _nftSellerAddress, address _erc20Token, uint256 _tokenAmount, address _nftRecipient ) external payable notZeroAddress(_nftRecipient) { NFT memory nft = NFT(_nftContractAddress, _tokenId, _nftSellerAddress); require( _isAuctionOngoing(nft), "Auction has ended" ); require( !_isWhitelistedSale(nft) || nftContractAuctions[nft.nftContractAddress][nft.tokenId][nft.nftSellerAddress] .whitelistedBuyer == msg.sender, "only the whitelisted buyer can bid on this NFT" ); nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress] .nftRecipient = _nftRecipient; _makeBid(_nftContractAddress, _tokenId,_nftSellerAddress, _erc20Token, _tokenAmount); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ BID FUNCTIONS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ /*************************************************************** * Settle an auction or sale if the buyNowPrice is met or set * * auction period to begin if the minimum price has been met. * ***************************************************************/ function _updateOngoingAuction( NFT memory _nft ) internal { if (_isBuyNowPriceMet(_nft)) { _transferNftAndPaySeller(_nft); return; } //min price not set, nft not up for auction yet if (_isMinimumBidMade(_nft)) { _updateAuctionEnd(_nft); } } function _updateAuctionEnd(NFT memory _nft) internal { //the auction end is always set to now + the bid period nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].auctionEnd = _getAuctionBidPeriod(_nft) + block.timestamp; emit AuctionPeriodUpdated( _nft.nftContractAddress, _nft.tokenId, _nft.nftSellerAddress, nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].auctionEnd ); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ RESET FUNCTIONS ║ ╚══════════════════════════════╝*/ /* * Reset all auction related parameters for an NFT. * This effectively removes an EFT as an item up for auction */ function _resetAuction(NFT memory _nft) internal { nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].orderType = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].minPrice = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].buyNowPrice = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].amount = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].auctionEnd = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].auctionBidPeriod = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].bidIncreasePercentage = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftSeller = address( 0); nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].whitelistedBuyer = address(0); delete nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].batchTokenIds; delete nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].batchAmounts; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].ERC20Token = address( 0 ); } /* * Reset all bid related parameters for an NFT. * This effectively sets an NFT as having no active bids */ function _resetBids(NFT memory _nft) internal { nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBidder = address(0); nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBid = 0; nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftRecipient = address(0); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ RESET FUNCTIONS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ UPDATE BIDS ║ ╚══════════════════════════════╝*/ /****************************************************************** * Internal functions that update bid parameters and reverse bids * * to ensure contract only holds the highest bid. * ******************************************************************/ function _updateHighestBid( NFT memory _nft, uint256 _tokenAmount ) internal { address auctionERC20Token = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId ][_nft.nftSellerAddress].ERC20Token; if (_isERC20Auction(auctionERC20Token)) { IERC20(auctionERC20Token).transferFrom( msg.sender, address(this), _tokenAmount ); nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress] .nftHighestBid = _tokenAmount; } else { nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress] .nftHighestBid = msg.value; } nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress] .nftHighestBidder = msg.sender; } function _reverseAndResetPreviousBid( NFT memory _nft ) internal { address nftHighestBidder = nftContractAuctions[_nft.nftContractAddress][ _nft.tokenId ][_nft.nftSellerAddress].nftHighestBidder; uint256 nftHighestBid = nftContractAuctions[_nft.nftContractAddress][ _nft.tokenId ][_nft.nftSellerAddress].nftHighestBid; _resetBids(_nft); _payout(_nft, nftHighestBidder, nftHighestBid); } function _reversePreviousBidAndUpdateHighestBid( NFT memory _nft, uint256 _tokenAmount ) internal { address prevNftHighestBidder = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId ][_nft.nftSellerAddress].nftHighestBidder; uint256 prevNftHighestBid = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId ][_nft.nftSellerAddress].nftHighestBid; _updateHighestBid(_nft, _tokenAmount); if (prevNftHighestBidder != address(0)) { _payout( _nft, prevNftHighestBidder, prevNftHighestBid ); } } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ UPDATE BIDS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ TRANSFER NFT & PAY SELLER ║ ╚══════════════════════════════╝*/ function _transferNftAndPaySeller( NFT memory _nft ) internal { address _nftSeller = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress] .nftSeller; address _nftHighestBidder = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId ][_nft.nftSellerAddress].nftHighestBidder; address _nftRecipient = _getNftRecipient(NFT(_nft.nftContractAddress, _nft.tokenId, _nft.nftSellerAddress)); uint256 _nftHighestBid = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].nftHighestBid; _resetBids(_nft); _payFeesAndSeller( _nft, _nftSeller, _nftHighestBid ); //reset bid and transfer nft last to avoid reentrancy uint256[] memory batchTokenIds = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].batchTokenIds; uint256 numberOfTokens = batchTokenIds.length; if (numberOfTokens > 0) { uint256[] memory batchAmounts = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].batchAmounts; IERC1155(_nft.nftContractAddress).safeBatchTransferFrom( address(this), _nftRecipient, batchTokenIds, batchAmounts, "0x0" ); for (uint256 i = 0; i < numberOfTokens; i++) { nftOwner[_nft.nftContractAddress][batchTokenIds[i]][_nft.nftSellerAddress] = address(0); } } else { uint256 _amount = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].amount; IERC1155(_nft.nftContractAddress).safeTransferFrom( address(this), _nftRecipient, _nft.tokenId, _amount, "0x0" ); } _resetAuction(_nft); emit NFTTransferredAndSellerPaid( _nft.nftContractAddress, _nft.tokenId, _nft.nftSellerAddress, _nftSeller, _nftHighestBid, _nftHighestBidder, _nftRecipient ); } function _payFeesAndSeller( NFT memory _nft, address _nftSeller, uint256 _highestBid ) internal { uint256 feesPaid; for ( uint256 i = 0; i < nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].feeRecipients.length; i++ ) { uint256 fee = _getPortionOfBid( _highestBid, nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].feePercentages[i] ); feesPaid = feesPaid + fee; _payout( _nft, nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].feeRecipients[i], fee ); } _payout( _nft, _nftSeller, (_highestBid - feesPaid) ); } function _payout( NFT memory _nft, address _recipient, uint256 _amount ) internal { address auctionERC20Token = nftContractAuctions[_nft.nftContractAddress][_nft.tokenId][_nft.nftSellerAddress].ERC20Token; if (_isERC20Auction(auctionERC20Token)) { IERC20(auctionERC20Token).transfer(_recipient, _amount); } else { // attempt to send the funds to the recipient (bool success, ) = payable(_recipient).call{value: _amount}(""); // if it failed, update their credit balance so they can pull it later if (!success) { failedTransferCredits[_recipient] = failedTransferCredits[_recipient] + _amount; } } } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ TRANSFER NFT & PAY SELLER ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ SETTLE & WITHDRAW ║ ╚══════════════════════════════╝*/ function settleAuction(address _nftContractAddress, uint256 _tokenId,address _nftSellerAddress) external { _isAuctionOver(NFT(_nftContractAddress, _tokenId, _nftSellerAddress)); _transferNftAndPaySeller(NFT(_nftContractAddress, _tokenId , _nftSellerAddress)); emit AuctionSettled(_nftContractAddress, _tokenId,_nftSellerAddress, msg.sender); } function withdrawNft(address _nftContractAddress, uint256 _tokenId) external { NFT memory nft = NFT(_nftContractAddress, _tokenId , msg.sender); _onlyNftSeller(nft); require(!_isMinimumBidMade(nft), "The auction has a valid bid made" ); uint256[] memory batchTokenIds = nftContractAuctions[ _nftContractAddress ][_tokenId][msg.sender].batchTokenIds; uint256 numberOfTokens = batchTokenIds.length; if (numberOfTokens > 0) { uint256[] memory batchAmounts = nftContractAuctions[ _nftContractAddress ][_tokenId][msg.sender].batchAmounts; IERC1155(_nftContractAddress).safeBatchTransferFrom( address(this), nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].nftSeller, batchTokenIds, batchAmounts, "0x0" ); for (uint256 i = 0; i < numberOfTokens; i++) { nftOwner[_nftContractAddress][batchTokenIds[i]][msg.sender] = address(0); } } else { uint256 _amount = nftContractAuctions[ _nftContractAddress ][_tokenId][msg.sender].amount; IERC1155(_nftContractAddress).safeTransferFrom( address(this), nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].nftSeller, _tokenId, _amount, "0x0" ); } _resetAuction(nft); emit NFTWithdrawn(_nftContractAddress, _tokenId, msg.sender); } function withdrawBid(address _nftContractAddress, uint256 _tokenId,address _nftSellerAddress) external { NFT memory nft = NFT(_nftContractAddress, _tokenId , _nftSellerAddress); require(!_isMinimumBidMade(nft), "The auction has a valid bid made" ); address nftHighestBidder = nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].nftHighestBidder; require(msg.sender == nftHighestBidder, "Cannot withdraw funds"); uint256 nftHighestBid = nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].nftHighestBid; _resetBids(nft); _payout(nft, nftHighestBidder, nftHighestBid); emit BidWithdrawn(_nftContractAddress, _tokenId,msg.sender); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ SETTLE & WITHDRAW ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ function updateWhitelistedBuyer( address _nftContractAddress, uint256 _tokenId, address _newWhitelistedBuyer ) external { NFT memory nft = NFT(_nftContractAddress, _tokenId , msg.sender); _onlyNftSeller(nft); require(_isASale(nft), "Not a sale"); nftContractAuctions[_nftContractAddress][_tokenId][msg.sender] .whitelistedBuyer = _newWhitelistedBuyer; //if an underbid is by a non whitelisted buyer,reverse that bid address nftHighestBidder = nftContractAuctions[_nftContractAddress][ _tokenId][msg.sender].nftHighestBidder; uint256 nftHighestBid = nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].nftHighestBid; if (nftHighestBid > 0 && !(nftHighestBidder == _newWhitelistedBuyer)) { //we only revert the underbid if the seller specifies a different //whitelisted buyer to the highest bider _resetBids(nft); _payout(nft,nftHighestBidder,nftHighestBid ); } emit WhitelistedBuyerUpdated( _nftContractAddress, _tokenId, msg.sender, _newWhitelistedBuyer ); } function updateMinimumPrice( address _nftContractAddress, uint256 _tokenId, uint256 _newMinPrice ) external priceGreaterThanZero(_newMinPrice) minPriceDoesNotExceedLimit( nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].buyNowPrice, _newMinPrice ) { NFT memory nft = NFT(_nftContractAddress, _tokenId , msg.sender); _onlyNftSeller(nft); require(!_isMinimumBidMade(nft), "The auction has a valid bid made" ); require(!_isASale(nft), "Not applicable for a sale"); nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].minPrice = _newMinPrice; emit MinimumPriceUpdated(_nftContractAddress, _tokenId,msg.sender, _newMinPrice); if (_isMinimumBidMade(nft)) { _updateAuctionEnd(nft); } } function updateBuyNowPrice( address _nftContractAddress, uint256 _tokenId, uint256 _newBuyNowPrice ) external priceGreaterThanZero(_newBuyNowPrice) minPriceDoesNotExceedLimit( _newBuyNowPrice, nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].minPrice ) { NFT memory nft = NFT(_nftContractAddress, _tokenId , msg.sender); _onlyNftSeller(nft); nftContractAuctions[_nftContractAddress][_tokenId][msg.sender].buyNowPrice = _newBuyNowPrice; emit BuyNowPriceUpdated(_nftContractAddress, _tokenId,msg.sender, _newBuyNowPrice); if (_isBuyNowPriceMet(nft)) { _transferNftAndPaySeller(nft); } } /* * The NFT seller can opt to end an auction by taking the current highest bid. */ function takeHighestBid(address _nftContractAddress, uint256 _tokenId) external { NFT memory nft = NFT(_nftContractAddress, _tokenId , msg.sender); _onlyNftSeller(nft); require( _isABidMade(nft), "cannot payout 0 bid" ); _transferNftAndPaySeller(nft); emit HighestBidTaken(_nftContractAddress, _tokenId,msg.sender); } /* * Query the owner of an NFT deposited for auction */ function ownerOfNFT(address _nftContractAddress, uint256 _tokenId,address _nftSellerAddress) external view returns (address) { address nftSeller = nftContractAuctions[_nftContractAddress][_tokenId][_nftSellerAddress].nftSeller; if (nftSeller != address(0)) { return nftSeller; } address ownerAddr = nftOwner[_nftContractAddress][_tokenId][_nftSellerAddress]; require(ownerAddr != address(0), "NFT not deposited"); return ownerAddr; } /* * If the transfer of a bid has failed, allow the recipient to reclaim their amount later. */ function withdrawAllFailedCredits() external { uint256 amount = failedTransferCredits[msg.sender]; require(amount != 0, "no credits to withdraw"); failedTransferCredits[msg.sender] = 0; (bool successfulWithdraw, ) = msg.sender.call{value: amount}(""); require(successfulWithdraw, "withdraw failed"); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ /**********************************/ function getPayTokens() external view returns (address[] memory) { return payTokens; } function setMarketState(uint256 _marketState) onlyOwner external { marketState = _marketState ; } function setFee(address[] memory _feeRecipients,uint32[] memory _feePercentages) onlyOwner external { if(_feeRecipients.length!=0) feeRecipients = _feeRecipients; if(_feePercentages.length!=0) feePercentages = _feePercentages; } function setPayTokens(address[] memory _payTokens) onlyOwner external { if(_payTokens.length!=0) payTokens = _payTokens; } receive() external payable {} function _transferEth(address _to, uint256 _amount) internal { (bool success, ) = _to.call{value: _amount}(''); require(success, "_transferEth: Eth transfer failed"); } // Emergency function: In case any ETH get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueETH(address recipient) onlyOwner external { _transferEth(recipient, address(this).balance); } // Emergency function: In case any ERC20 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC20(address asset, address recipient) onlyOwner external { IERC20(asset).transfer(recipient, IERC20(asset).balanceOf(address(this))); } // Emergency function: In case any ERC721 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC721(address asset, uint256[] calldata ids, address recipient) onlyOwner external { for (uint256 i = 0; i < ids.length; i++) { IERC721(asset).transferFrom(address(this), recipient, ids[i]); } } // Emergency function: In case any ERC1155 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC1155(address asset, uint256[] calldata ids, uint256[] calldata amounts, address recipient) onlyOwner external { for (uint256 i = 0; i < ids.length; i++) { IERC1155(asset).safeTransferFrom(address(this), recipient, ids[i], amounts[i], ""); } } }
The NFT seller can opt to end an auction by taking the current highest bid./
function takeHighestBid(address _nftContractAddress, uint256 _tokenId) external { NFT memory nft = NFT(_nftContractAddress, _tokenId , msg.sender); _onlyNftSeller(nft); require( _isABidMade(nft), "cannot payout 0 bid" ); _transferNftAndPaySeller(nft); emit HighestBidTaken(_nftContractAddress, _tokenId,msg.sender); }
7,328,313
./full_match/11155111/0xC87F732C1FfCEf4A2985c1b4Cc3d00F6f163F012/sources/contracts/Contract.sol
Emergency withdrawal of staked rewards when contract is paused. return Amount of staked rewards withdrawn./
function emergencyWithdraw() external whenPaused nonReentrant returns (uint256) { require(stakedRewards[msg.sender] > 0, "No staked rewards to withdraw"); uint256 amount = stakedRewards[msg.sender]; stakedRewards[msg.sender] = 0; rewardToken.transfer(msg.sender, amount); return amount; }
3,788,330
/* 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. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IERC20 } from "../protocol/interfaces/IERC20.sol"; import { Math } from "../protocol/lib/Math.sol"; /** * @title TestOasisDex * @author dYdX * * Contract for testing stuff against OasisDex. Removes some functionality like auth, note, and * non-reentrancy protection. */ contract TestOasisDex { // ============ Constants ============ uint256 constant WAD = 10 ** 18; uint256 constant RAY = 10 ** 27; // ============ Events ============ event LogItemUpdate(uint256 id); event LogTrade( uint256 pay_amt, address indexed pay_gem, uint256 buy_amt, address indexed buy_gem ); event LogMake( bytes32 indexed id, bytes32 indexed pair, address indexed maker, address pay_gem, address buy_gem, uint128 pay_amt, uint128 buy_amt, uint64 timestamp ); event LogBump( bytes32 indexed id, bytes32 indexed pair, address indexed maker, address pay_gem, address buy_gem, uint128 pay_amt, uint128 buy_amt, uint64 timestamp ); event LogTake( bytes32 id, bytes32 indexed pair, address indexed maker, address pay_gem, address buy_gem, address indexed taker, uint128 take_amt, uint128 give_amt, uint64 timestamp ); event LogKill( bytes32 indexed id, bytes32 indexed pair, address indexed maker, address pay_gem, address buy_gem, uint128 pay_amt, uint128 buy_amt, uint64 timestamp ); event LogBuyEnabled(bool isEnabled); event LogMinSell(address pay_gem, uint256 min_amount); event LogMatchingEnabled(bool isEnabled); event LogUnsortedOffer(uint256 id); event LogSortedOffer(uint256 id); event LogAddTokenPairWhitelist(address baseToken, address quoteToken); event LogRemTokenPairWhitelist(address baseToken, address quoteToken); event LogInsert(address keeper, uint256 id); event LogDelete(address keeper, uint256 id); // ============ Structs ============ struct OfferInfo { uint256 pay_amt; address pay_gem; uint256 buy_amt; address buy_gem; address owner; uint64 timestamp; } struct sortInfo { uint256 next; //points to id of next higher offer uint256 prev; //points to id of previous lower offer uint256 delb; //the blocknumber where this entry was marked for delete } // ============ Storage ============ bool public stopped; bool public buyEnabled = true; bool public matchingEnabled = true; mapping(uint256 => sortInfo) public _rank; mapping(address => mapping(address => uint256)) public _best; mapping(address => mapping(address => uint256)) public _span; mapping(address => uint256) public _dust; mapping(uint256 => uint256) public _near; uint256 _head; uint256 public dustId; uint256 public last_offer_id; mapping (uint256 => OfferInfo) public offers; // ============ Modifiers ============ modifier can_offer { require(!isClosed()); _; } modifier can_buy(uint256 id) { require(isActive(id)); require(!isClosed()); _; } modifier can_cancel(uint256 id) { require(isActive(id), "Offer was deleted or taken, or never existed."); require( isClosed() || msg.sender == getOwner(id) || id == dustId, "Offer can not be cancelled because user is not owner, and market is open, and offer sells required amount of tokens." ); _; } // ============ Functions ============ function isClosed() public view returns (bool closed) { return stopped; } function getTime() public view returns (uint64) { return uint64(now); } function stop() public { stopped = true; } function isActive(uint256 id) public view returns (bool active) { return offers[id].timestamp > 0; } function getOwner(uint256 id) public view returns (address owner) { return offers[id].owner; } function getOffer(uint256 id) public view returns (uint256, address, uint256, address) { OfferInfo memory _offer = offers[id]; return (_offer.pay_amt, _offer.pay_gem, _offer.buy_amt, _offer.buy_gem); } function bump(bytes32 id_) public can_buy(uint256(id_)) { uint256 id = uint256(id_); emit LogBump( id_, keccak256(abi.encodePacked(offers[id].pay_gem, offers[id].buy_gem)), offers[id].owner, offers[id].pay_gem, offers[id].buy_gem, uint128(offers[id].pay_amt), uint128(offers[id].buy_amt), offers[id].timestamp ); } function make( address pay_gem, address buy_gem, uint128 pay_amt, uint128 buy_amt ) public returns (bytes32) { return bytes32(offer(pay_amt, pay_gem, buy_amt, buy_gem)); } function take(bytes32 id, uint128 maxTakeAmount) public { require(buy(uint256(id), maxTakeAmount)); } function kill(bytes32 id) public { require(cancel(uint256(id))); } // Make a new offer. Takes funds from the caller into market escrow. // // If matching is enabled: // * creates new offer without putting it in // the sorted list. // * available to authorized contracts only! // * keepers should call insert(id,pos) // to put offer in the sorted list. // // If matching is disabled: // * calls expiring market's offer(). // * available to everyone without authorization. // * no sorting is done. // function offer( uint256 pay_amt, //maker (ask) sell how much address pay_gem, //maker (ask) sell which token uint256 buy_amt, //taker (ask) buy how much address buy_gem //taker (ask) buy which token ) public can_offer returns (uint256) { return _offeru(pay_amt, pay_gem, buy_amt, buy_gem); } // Make a new offer. Takes funds from the caller into market escrow. function offer( uint256 pay_amt, //maker (ask) sell how much address pay_gem, //maker (ask) sell which token uint256 buy_amt, //maker (ask) buy how much address buy_gem, //maker (ask) buy which token uint256 pos //position to insert offer, 0 should be used if unknown ) public can_offer returns (uint256) { return offer(pay_amt, pay_gem, buy_amt, buy_gem, pos, true); } function offer( uint256 pay_amt, //maker (ask) sell how much address pay_gem, //maker (ask) sell which token uint256 buy_amt, //maker (ask) buy how much address buy_gem, //maker (ask) buy which token uint256 pos, //position to insert offer, 0 should be used if unknown bool rounding //match "close enough" orders? ) public can_offer returns (uint256) { require(_dust[pay_gem] <= pay_amt); return _matcho(pay_amt, pay_gem, buy_amt, buy_gem, pos, rounding); } //Transfers funds from caller to offer maker, and from market to caller. function buy(uint256 id, uint256 amount) public can_buy(id) returns (bool) { return _buys(id, amount); } // Cancel an offer. Refunds offer maker. function cancel(uint256 id) public can_cancel(id) returns (bool success) { if (isOfferSorted(id)) { require(_unsort(id)); } else { require(_hide(id)); } // read-only offer. Modify an offer by directly accessing offers[id] OfferInfo memory _offer = offers[id]; delete offers[id]; IERC20(_offer.pay_gem).transfer(_offer.owner, _offer.pay_amt); emit LogItemUpdate(id); emit LogKill( bytes32(id), keccak256(abi.encodePacked(_offer.pay_gem, _offer.buy_gem)), _offer.owner, _offer.pay_gem, _offer.buy_gem, uint128(_offer.pay_amt), uint128(_offer.buy_amt), uint64(now) ); success = true; } //insert offer into the sorted list //keepers need to use this function function insert( uint256 id, //maker (ask) id uint256 pos //position to insert into ) public returns (bool) { require(!isOfferSorted(id)); //make sure offers[id] is not yet sorted require(isActive(id)); //make sure offers[id] is active _hide(id); //remove offer from unsorted offers list _sort(id, pos); //put offer into the sorted offers list emit LogInsert(msg.sender, id); return true; } //deletes _rank [id] // Function should be called by keepers. function del_rank(uint256 id) public returns (bool) { require(!isActive(id) && _rank[id].delb != 0 && _rank[id].delb < block.number - 10); delete _rank[id]; emit LogDelete(msg.sender, id); return true; } //set the minimum sell amount for a token // Function is used to avoid "dust offers" that have // very small amount of tokens to sell, and it would // cost more gas to accept the offer, than the value // of tokens received. function setMinSell( address pay_gem, //token to assign minimum sell amount to uint256 dust //maker (ask) minimum sell amount ) public returns (bool) { _dust[pay_gem] = dust; emit LogMinSell(pay_gem, dust); return true; } //returns the minimum sell amount for an offer function getMinSell( address pay_gem //token for which minimum sell amount is queried ) public view returns (uint256) { return _dust[pay_gem]; } //set buy functionality enabled/disabled function setBuyEnabled(bool buyEnabled_) public returns (bool) { buyEnabled = buyEnabled_; emit LogBuyEnabled(buyEnabled); return true; } //set matching enabled/disabled // If matchingEnabled true(default), then inserted offers are matched. // Except the ones inserted by contracts, because those end up // in the unsorted list of offers, that must be later sorted by // keepers using insert(). // If matchingEnabled is false then MatchingMarket is reverted to ExpiringMarket, // and matching is not done, and sorted lists are disabled. function setMatchingEnabled(bool matchingEnabled_) public returns (bool) { matchingEnabled = matchingEnabled_; emit LogMatchingEnabled(matchingEnabled); return true; } //return the best offer for a token pair // the best offer is the lowest one if it's an ask, // and highest one if it's a bid offer function getBestOffer(address sell_gem, address buy_gem) public view returns(uint256) { return _best[sell_gem][buy_gem]; } //return the next worse offer in the sorted list // the worse offer is the higher one if its an ask, // a lower one if its a bid offer, // and in both cases the newer one if they're equal. function getWorseOffer(uint256 id) public view returns(uint256) { return _rank[id].prev; } //return the next better offer in the sorted list // the better offer is in the lower priced one if its an ask, // the next higher priced one if its a bid offer // and in both cases the older one if they're equal. function getBetterOffer(uint256 id) public view returns(uint256) { return _rank[id].next; } //return the amount of better offers for a token pair function getOfferCount(address sell_gem, address buy_gem) public view returns(uint256) { return _span[sell_gem][buy_gem]; } //get the first unsorted offer that was inserted by a contract // Contracts can't calculate the insertion position of their offer because it is not an O(1) operation. // Their offers get put in the unsorted list of offers. // Keepers can calculate the insertion position offchain and pass it to the insert() function to insert // the unsorted offer into the sorted list. Unsorted offers will not be matched, but can be bought with buy(). function getFirstUnsortedOffer() public view returns(uint256) { return _head; } //get the next unsorted offer // Can be used to cycle through all the unsorted offers. function getNextUnsortedOffer(uint256 id) public view returns(uint256) { return _near[id]; } function isOfferSorted(uint256 id) public view returns(bool) { return _rank[id].next != 0 || _rank[id].prev != 0 || _best[offers[id].pay_gem][offers[id].buy_gem] == id; } function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public returns (uint256 fill_amt) { uint256 offerId; while (pay_amt > 0) { //while there is amount to sell offerId = getBestOffer(buy_gem, pay_gem); //Get the best offer for the token pair require(offerId != 0); //Fails if there are not more offers // There is a chance that pay_amt is smaller than 1 wei of the other token if (pay_amt * 1 ether < wdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) { break; //We consider that all amount is sold } if (pay_amt >= offers[offerId].buy_amt) { //If amount to sell is higher or equal than current offer amount to buy fill_amt = SafeMath.add(fill_amt, offers[offerId].pay_amt); //Add amount bought to acumulator pay_amt = SafeMath.sub(pay_amt, offers[offerId].buy_amt); //Decrease amount to sell take(bytes32(offerId), uint128(offers[offerId].pay_amt)); //We take the whole offer } else { // if lower uint256 baux = rmul(pay_amt * 10 ** 9, rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) / 10 ** 9; fill_amt = SafeMath.add(fill_amt, baux); //Add amount bought to acumulator take(bytes32(offerId), uint128(baux)); //We take the portion of the offer that we need pay_amt = 0; //All amount is sold } } require(fill_amt >= min_fill_amount); } function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public returns (uint256 fill_amt) { uint256 offerId; while (buy_amt > 0) { //Meanwhile there is amount to buy offerId = getBestOffer(buy_gem, pay_gem); //Get the best offer for the token pair require(offerId != 0); // There is a chance that buy_amt is smaller than 1 wei of the other token if (buy_amt * 1 ether < wdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) { break; //We consider that all amount is sold } if (buy_amt >= offers[offerId].pay_amt) { //If amount to buy is higher or equal than current offer amount to sell fill_amt = SafeMath.add(fill_amt, offers[offerId].buy_amt); //Add amount sold to acumulator buy_amt = SafeMath.sub(buy_amt, offers[offerId].pay_amt); //Decrease amount to buy take(bytes32(offerId), uint128(offers[offerId].pay_amt)); //We take the whole offer } else { //if lower fill_amt = SafeMath.add(fill_amt, rmul(buy_amt * 10 ** 9, rdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) / 10 ** 9); //Add amount sold to acumulator take(bytes32(offerId), uint128(buy_amt)); //We take the portion of the offer that we need buy_amt = 0; //All amount is bought } } require(fill_amt <= max_fill_amount); } function getBuyAmount(address buy_gem, address pay_gem, uint256 pay_amt) public view returns (uint256 fill_amt) { uint256 offerId = getBestOffer(buy_gem, pay_gem); //Get best offer for the token pair while (pay_amt > offers[offerId].buy_amt) { fill_amt = SafeMath.add(fill_amt, offers[offerId].pay_amt); //Add amount to buy accumulator pay_amt = SafeMath.sub(pay_amt, offers[offerId].buy_amt); //Decrease amount to pay if (pay_amt > 0) { //If we still need more offers offerId = getWorseOffer(offerId); //We look for the next best offer require(offerId != 0); //Fails if there are not enough offers to complete } } fill_amt = SafeMath.add(fill_amt, rmul(pay_amt * 10 ** 9, rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) / 10 ** 9); //Add proportional amount of last offer to buy accumulator } function getPayAmount(address pay_gem, address buy_gem, uint256 buy_amt) public view returns (uint256 fill_amt) { uint256 offerId = getBestOffer(buy_gem, pay_gem); //Get best offer for the token pair while (buy_amt > offers[offerId].pay_amt) { fill_amt = SafeMath.add(fill_amt, offers[offerId].buy_amt); //Add amount to pay accumulator buy_amt = SafeMath.sub(buy_amt, offers[offerId].pay_amt); //Decrease amount to buy if (buy_amt > 0) { //If we still need more offers offerId = getWorseOffer(offerId); //We look for the next best offer require(offerId != 0); //Fails if there are not enough offers to complete } } fill_amt = SafeMath.add(fill_amt, rmul(buy_amt * 10 ** 9, rdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) / 10 ** 9); //Add proportional amount of last offer to pay accumulator } // ============ Internal Functions ============ function _next_id() internal returns (uint256) { last_offer_id++; return last_offer_id; } function _buys(uint256 id, uint256 amount) internal returns (bool) { require(buyEnabled); if (amount == offers[id].pay_amt) { if (isOfferSorted(id)) { //offers[id] must be removed from sorted list because all of it is bought _unsort(id); }else{ _hide(id); } } require(super_buy(id, amount)); // If offer has become dust during buy, we cancel it if (isActive(id) && offers[id].pay_amt < _dust[offers[id].pay_gem]) { dustId = id; //enable current msg.sender to call cancel(id) cancel(id); } return true; } //find the id of the next higher offer after offers[id] function _find(uint256 id) internal view returns (uint256) { require(id > 0); address buy_gem = offers[id].buy_gem; address pay_gem = offers[id].pay_gem; uint256 top = _best[pay_gem][buy_gem]; uint256 old_top = 0; // Find the larger-than-id order whose successor is less-than-id. while (top != 0 && _isPricedLtOrEq(id, top)) { old_top = top; top = _rank[top].prev; } return old_top; } //find the id of the next higher offer after offers[id] function _findpos(uint256 id, uint256 pos) internal view returns (uint256) { require(id > 0); // Look for an active order. while (pos != 0 && !isActive(pos)) { pos = _rank[pos].prev; } if (pos == 0) { //if we got to the end of list without a single active offer return _find(id); } else { // if we did find a nearby active offer // Walk the order book down from there... if(_isPricedLtOrEq(id, pos)) { uint256 old_pos; // Guaranteed to run at least once because of // the prior if statements. while (pos != 0 && _isPricedLtOrEq(id, pos)) { old_pos = pos; pos = _rank[pos].prev; } return old_pos; // ...or walk it up. } else { while (pos != 0 && !_isPricedLtOrEq(id, pos)) { pos = _rank[pos].next; } return pos; } } } //return true if offers[low] priced less than or equal to offers[high] function _isPricedLtOrEq( uint256 low, //lower priced offer's id uint256 high //higher priced offer's id ) internal view returns (bool) { return SafeMath.mul(offers[low].buy_amt, offers[high].pay_amt) >= SafeMath.mul(offers[high].buy_amt, offers[low].pay_amt); } //these variables are global only because of solidity local variable limit //match offers with taker offer, and execute token transactions function _matcho( uint256 t_pay_amt, //taker sell how much address t_pay_gem, //taker sell which token uint256 t_buy_amt, //taker buy how much address t_buy_gem, //taker buy which token uint256 pos, //position id bool rounding //match "close enough" orders? ) internal returns (uint256 id) { uint256 best_maker_id; //highest maker id uint256 t_buy_amt_old; //taker buy how much saved uint256 m_buy_amt; //maker offer wants to buy this much token uint256 m_pay_amt; //maker offer wants to sell this much token // there is at least one offer stored for token pair while (_best[t_buy_gem][t_pay_gem] > 0) { best_maker_id = _best[t_buy_gem][t_pay_gem]; m_buy_amt = offers[best_maker_id].buy_amt; m_pay_amt = offers[best_maker_id].pay_amt; // Ugly hack to work around rounding errors. Based on the idea that // the furthest the amounts can stray from their "true" values is 1. // Ergo the worst case has t_pay_amt and m_pay_amt at +1 away from // their "correct" values and m_buy_amt and t_buy_amt at -1. // Since (c - 1) * (d - 1) > (a + 1) * (b + 1) is equivalent to // c * d > a * b + a + b + c + d, we write... if (SafeMath.mul(m_buy_amt, t_buy_amt) > SafeMath.mul(t_pay_amt, m_pay_amt) + (rounding ? m_buy_amt + t_buy_amt + t_pay_amt + m_pay_amt : 0)) { break; } // ^ The `rounding` parameter is a compromise borne of a couple days // of discussion. buy(best_maker_id, Math.min(m_pay_amt, t_buy_amt)); t_buy_amt_old = t_buy_amt; t_buy_amt = SafeMath.sub(t_buy_amt, Math.min(m_pay_amt, t_buy_amt)); t_pay_amt = SafeMath.mul(t_buy_amt, t_pay_amt) / t_buy_amt_old; if (t_pay_amt == 0 || t_buy_amt == 0) { break; } } if (t_buy_amt > 0 && t_pay_amt > 0 && t_pay_amt >= _dust[t_pay_gem]) { //new offer should be created id = super_offer(t_pay_amt, t_pay_gem, t_buy_amt, t_buy_gem); //insert offer into the sorted list _sort(id, pos); } } // Make a new offer without putting it in the sorted list. // Takes funds from the caller into market escrow. // ****Available to authorized contracts only!********** // Keepers should call insert(id,pos) to put offer in the sorted list. function _offeru( uint256 pay_amt, //maker (ask) sell how much address pay_gem, //maker (ask) sell which token uint256 buy_amt, //maker (ask) buy how much address buy_gem //maker (ask) buy which token ) internal returns (uint256 id) { require(_dust[pay_gem] <= pay_amt); id = super_offer(pay_amt, pay_gem, buy_amt, buy_gem); _near[id] = _head; _head = id; emit LogUnsortedOffer(id); } //put offer into the sorted list function _sort( uint256 id, //maker (ask) id uint256 pos //position to insert into ) internal { require(isActive(id)); address buy_gem = offers[id].buy_gem; address pay_gem = offers[id].pay_gem; uint256 prev_id; //maker (ask) id pos = pos == 0 || offers[pos].pay_gem != pay_gem || offers[pos].buy_gem != buy_gem || !isOfferSorted(pos) ? _find(id) : _findpos(id, pos); if (pos != 0) { //offers[id] is not the highest offer //requirement below is satisfied by statements above //require(_isPricedLtOrEq(id, pos)); prev_id = _rank[pos].prev; _rank[pos].prev = id; _rank[id].next = pos; } else { //offers[id] is the highest offer prev_id = _best[pay_gem][buy_gem]; _best[pay_gem][buy_gem] = id; } if (prev_id != 0) { //if lower offer does exist //requirement below is satisfied by statements above //require(!_isPricedLtOrEq(id, prev_id)); _rank[prev_id].next = id; _rank[id].prev = prev_id; } _span[pay_gem][buy_gem]++; emit LogSortedOffer(id); } // Remove offer from the sorted list (does not cancel offer) function _unsort( uint256 id //id of maker (ask) offer to remove from sorted list ) internal returns (bool) { address buy_gem = offers[id].buy_gem; address pay_gem = offers[id].pay_gem; require(_span[pay_gem][buy_gem] > 0); require(_rank[id].delb == 0 && //assert id is in the sorted list isOfferSorted(id)); if (id != _best[pay_gem][buy_gem]) { // offers[id] is not the highest offer require(_rank[_rank[id].next].prev == id); _rank[_rank[id].next].prev = _rank[id].prev; } else { //offers[id] is the highest offer _best[pay_gem][buy_gem] = _rank[id].prev; } if (_rank[id].prev != 0) { //offers[id] is not the lowest offer require(_rank[_rank[id].prev].next == id); _rank[_rank[id].prev].next = _rank[id].next; } _span[pay_gem][buy_gem]--; _rank[id].delb = block.number; //mark _rank[id] for deletion return true; } //Hide offer from the unsorted order book (does not cancel offer) function _hide( uint256 id //id of maker offer to remove from unsorted list ) internal returns (bool) { uint256 uid = _head; //id of an offer in unsorted offers list uint256 pre = uid; //id of previous offer in unsorted offers list require(!isOfferSorted(id)); //make sure offer id is not in sorted offers list if (_head == id) { //check if offer is first offer in unsorted offers list _head = _near[id]; //set head to new first unsorted offer _near[id] = 0; //delete order from unsorted order list return true; } while (uid > 0 && uid != id) { //find offer in unsorted order list pre = uid; uid = _near[uid]; } if (uid != id) { //did not find offer id in unsorted offers list return false; } _near[pre] = _near[id]; //set previous unsorted offer to point to offer after offer id _near[id] = 0; //delete order from unsorted order list return true; } // Accept given `quantity` of an offer. Transfers funds from caller to // offer maker, and from market to caller. function super_buy(uint256 id, uint256 quantity) internal returns (bool) { OfferInfo memory _offer = offers[id]; uint256 spend = SafeMath.mul(quantity, _offer.buy_amt) / _offer.pay_amt; require(uint128(spend) == spend); require(uint128(quantity) == quantity); // For backwards semantic compatibility. if (quantity == 0 || spend == 0 || quantity > _offer.pay_amt || spend > _offer.buy_amt) { return false; } offers[id].pay_amt = SafeMath.sub(_offer.pay_amt, quantity); offers[id].buy_amt = SafeMath.sub(_offer.buy_amt, spend); IERC20(_offer.buy_gem).transferFrom(msg.sender, _offer.owner, spend); IERC20(_offer.pay_gem).transfer(msg.sender, quantity); emit LogItemUpdate(id); emit LogTake( bytes32(id), keccak256(abi.encodePacked(_offer.pay_gem, _offer.buy_gem)), _offer.owner, _offer.pay_gem, _offer.buy_gem, msg.sender, uint128(quantity), uint128(spend), uint64(now) ); emit LogTrade(quantity, _offer.pay_gem, spend, _offer.buy_gem); if (offers[id].pay_amt == 0) { delete offers[id]; } return true; } // Make a new offer. Takes funds from the caller into market escrow. function super_offer(uint256 pay_amt, address pay_gem, uint256 buy_amt, address buy_gem) internal returns (uint256 id) { require(uint128(pay_amt) == pay_amt); require(uint128(buy_amt) == buy_amt); require(pay_amt > 0); require(pay_gem != address(0x0)); require(buy_amt > 0); require(buy_gem != address(0x0)); require(pay_gem != buy_gem); OfferInfo memory info; info.pay_amt = pay_amt; info.pay_gem = pay_gem; info.buy_amt = buy_amt; info.buy_gem = buy_gem; info.owner = msg.sender; info.timestamp = uint64(now); id = _next_id(); offers[id] = info; IERC20(pay_gem).transferFrom(msg.sender, address(this), pay_amt); emit LogItemUpdate(id); emit LogMake( bytes32(id), keccak256(abi.encodePacked(pay_gem, buy_gem)), msg.sender, pay_gem, buy_gem, uint128(pay_amt), uint128(buy_amt), uint64(now) ); } // ============ Math Functions ============ function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = SafeMath.add(SafeMath.mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = SafeMath.add(SafeMath.mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = SafeMath.add(SafeMath.mul(x, RAY), y / 2) / y; } }
return the next better offer in the sorted list the better offer is in the lower priced one if its an ask, the next higher priced one if its a bid offer and in both cases the older one if they're equal.
function getBetterOffer(uint256 id) public view returns(uint256) { return _rank[id].next; }
13,000,204
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (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: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // 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 ); } // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require( fromBalance >= amount, "ERC20: transfer amount exceeds balance" ); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require( currentAllowance >= amount, "ERC20: insufficient allowance" ); unchecked { _approve(owner, spender, currentAllowance - 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 {} } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } pragma solidity 0.8.11; interface ICryptoBearWatchClub { function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; } pragma solidity 0.8.11; contract Arkouda is ERC20, Ownable, IERC721Receiver { ICryptoBearWatchClub public CryptoBearWatchClub; enum TX_TYPE { UNSTAKE, CLAIM } bool public stakingLive; uint256 public constant tier1Reward = 30 ether; uint256 public constant tier2Reward = 9 ether; uint256 public constant tier3Reward = 3 ether; // Stores tier of a CBWC NFT. // 0 represents tier 3 mapping(uint256 => uint256) public tokenIdTier; // Stores token id staker address mapping(uint256 => address) public tokenOwner; // To store when was the last time user staked or claimed the reward of the token Id mapping(address => mapping(uint256 => uint256)) public lastUpdate; // To store addresses that can burn their Arkouda token mapping(address => bool) public allowedAddresses; event Staked(address indexed staker, uint256[] tokenIds, uint256 stakeTime); event Unstaked(address indexed unstaker, uint256[] tokenIds); event RewardsPaid( address indexed claimer, uint256[] tokenIds, uint256 _tier1Rewards, uint256 _tier2Rewards, uint256 _tier3Rewards ); constructor(ICryptoBearWatchClub _cryptoBearWatchClub) ERC20("Arkouda", "$ark") { CryptoBearWatchClub = _cryptoBearWatchClub; } modifier isTokenOwner(uint256[] memory _tokenIds) { for (uint256 i = 0; i < _tokenIds.length; i++) { require( tokenOwner[_tokenIds[i]] == _msgSender(), "CALLER_IS_NOT_STAKER" ); } _; } modifier isStakingLive() { require(stakingLive, "STAKING_IS_NOT_LIVE_YET"); _; } modifier checkInputLength(uint256[] memory _tokenIds) { require(_tokenIds.length > 0, "INVALID_INPUT_LENGTH"); _; } // To start staking/ reward generation function startStaking() external onlyOwner { require(!stakingLive, "STAKING_IS_ALREADY_LIVE"); stakingLive = true; } // To grant/revoke burn access function setAllowedAddresses(address _address, bool _access) external onlyOwner { allowedAddresses[_address] = _access; } // Sets the tier of CBWC NFTs function setCBWCNFTTier(uint256[] calldata _tokenIds, uint256 _tier) external onlyOwner { require(_tier == 1 || _tier == 2, "INVALID_TIER"); for (uint256 i = 0; i < _tokenIds.length; i++) { require(tokenIdTier[_tokenIds[i]] == 0, "TIER_ALREADY_SET"); tokenIdTier[_tokenIds[i]] = _tier; } } function onERC721Received( address, address, uint256, bytes memory ) external pure override returns (bytes4) { return this.onERC721Received.selector; } function burn(uint256 amount) external { require( allowedAddresses[_msgSender()], "ADDRESS_DOES_NOT_HAVE_PERMISSION_TO_BURN" ); _burn(_msgSender(), amount); } // Stakes CBWC NFTs function stakeCBWC(uint256[] calldata _tokenIds) external isStakingLive checkInputLength(_tokenIds) { for (uint256 i = 0; i < _tokenIds.length; i++) { require( CryptoBearWatchClub.ownerOf(_tokenIds[i]) == _msgSender(), "CBWC_NFT_IS_NOT_YOURS" ); // Transferring NFT from staker to the contract CryptoBearWatchClub.safeTransferFrom( _msgSender(), address(this), _tokenIds[i] ); // Keeping track of token id staker address tokenOwner[_tokenIds[i]] = _msgSender(); lastUpdate[_msgSender()][_tokenIds[i]] = block.timestamp; } emit Staked(_msgSender(), _tokenIds, block.timestamp); } // Unstakes CBWC NFTs function unStakeCBWC(uint256[] calldata _tokenIds) external isStakingLive isTokenOwner(_tokenIds) checkInputLength(_tokenIds) { claimOrUnstake(_tokenIds, TX_TYPE.UNSTAKE); emit Unstaked(_msgSender(), _tokenIds); } // To claim reward for staking CBWC NFTs function claimRewards(uint256[] calldata _tokenIds) external isStakingLive isTokenOwner(_tokenIds) checkInputLength(_tokenIds) { claimOrUnstake(_tokenIds, TX_TYPE.CLAIM); } function claimOrUnstake(uint256[] memory _tokenIds, TX_TYPE txType) private { uint256 rewards; uint256 _tier1Rewards; uint256 _tier2Rewards; uint256 _tier3Rewards; uint256 tier; for (uint256 i = 0; i < _tokenIds.length; i++) { (rewards, tier) = getPendingRewardAndTier(_tokenIds[i]); if (tier == 1) { _tier1Rewards += rewards; } else if (tier == 2) { _tier2Rewards += rewards; } else { _tier3Rewards += rewards; } if (txType == TX_TYPE.UNSTAKE) { // Transferring NFT back to the staker CryptoBearWatchClub.safeTransferFrom( address(this), _msgSender(), _tokenIds[i] ); // Resetting token id staker address tokenOwner[_tokenIds[i]] = address(0); // Resetting last update timer of token id // Resetting it so that 'getPendingReward' function returns 0 if you check pending reward of unstaked NFT lastUpdate[_msgSender()][_tokenIds[i]] = 0; } else { // Updating last claim time lastUpdate[_msgSender()][_tokenIds[i]] = block.timestamp; } } _mint(_msgSender(), (_tier1Rewards + _tier2Rewards + _tier3Rewards)); emit RewardsPaid( _msgSender(), _tokenIds, _tier1Rewards, _tier2Rewards, _tier3Rewards ); } // Returns total pending rewards of all input token ids function getTotalClaimable(uint256[] memory _tokenIds) external view returns (uint256 totalRewards) { for (uint256 i = 0; i < _tokenIds.length; i++) { totalRewards += getPendingReward(_tokenIds[i]); } } // Returns pending accumulated reward of the token id function getPendingReward(uint256 _tokenId) public view returns (uint256 reward) { if (lastUpdate[_msgSender()][_tokenId] == 0) { return 0; } (reward, ) = getPendingRewardAndTier(_tokenId); } // Returns pending accumulated reward of the token id along with token id tier function getPendingRewardAndTier(uint256 _tokenId) private view returns (uint256 rewards, uint256 tier) { uint256 secondsHeld = block.timestamp - lastUpdate[_msgSender()][_tokenId]; if (tokenIdTier[_tokenId] == 1) { return (((tier1Reward * secondsHeld) / 86400), 1); } else if (tokenIdTier[_tokenId] == 2) { return (((tier2Reward * secondsHeld) / 86400), 2); } else { return (((tier3Reward * secondsHeld) / 86400), 3); } } }
To grant/revoke burn access
function setAllowedAddresses(address _address, bool _access) external onlyOwner { allowedAddresses[_address] = _access; }
96,513
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.6; import {ILiquidationPriceOracleBase} from '../../interfaces/liquidation/ILiquidationPriceOracleBase.sol'; import {IChainLinkAggregatorProxy} from '../../interfaces/liquidation/thirdParty/IChainLinkAggregatorProxy.sol'; import {IDMMPool} from '../../interfaces/liquidation/thirdParty/IDMMPool.sol'; import {PermissionAdmin, PermissionOperators} from '@kyber.network/utils-sc/contracts/PermissionOperators.sol'; import {Utils} from '@kyber.network/utils-sc/contracts/Utils.sol'; import {IERC20Ext} from '@kyber.network/utils-sc/contracts/IERC20Ext.sol'; import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; import {EnumerableSet} from '@openzeppelin/contracts/utils/EnumerableSet.sol'; /** * @dev Contract to calculate expected return amounts for a liquidation call * Also work with Kyber Dmm LP tokens * Can use hint to: * 2. Calculate price of a LP token to a dest token * 3. Calculate price of a normal token to a dest token * It may not work for LPs of token with fees */ contract KyberDmmChainLinkPriceOracle is ILiquidationPriceOracleBase, PermissionOperators, Utils { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; // LIQUIDATE_LP: liquidate list of LP tokens to a single token // LIQUIDATE_TOKEN: liquidate list of tokens to a single token enum LiquidationType { LIQUIDATE_LP, LIQUIDATE_TOKEN } uint64 constant public MAX_PREMIUM_BPS = 2000; // 20% // min duration to consider the chainlink rate as a valid data uint64 constant public MIN_DURATION_VALID_CHAINLINK_RATE = 30 minutes; address public immutable weth; struct AggregatorProxyData { address quoteEthProxy; uint8 quoteEthProxyDecimals; address quoteUsdProxy; uint8 quoteUsdProxyDecimals; } mapping (address => AggregatorProxyData) internal _tokenData; struct Config { uint64 liquidateLpBps; // default liquidate lp bps uint64 liquidateTokenBps; // default liquidate token bps uint64 minValidDurationInSeconds; // min valid duration in seconds for chainlink uint64 lpDiffThreshold; // different threshold for price of 2 tokens in the LP } Config internal _config; struct PremiumData { uint64 liquidateLpBps; uint64 liquidateTokenBps; } mapping (address => PremiumData) internal _groupPremiumData; // list of tokens that can be liquidate to EnumerableSet.AddressSet private _whitelistedTokens; event DefaultPremiumDataSet( uint64 liquidateLpBps, uint64 liquidateTokenBps ); event UpdateGroupPremiumData( address indexed liquidator, uint64 liquidateLpBps, uint64 liquidateTokenBps ); event UpdateAggregatorProxyData( address indexed token, address indexed quoteEthProxy, address indexed quoteUsdProxy ); event WhitelistedTokenUpdated(address indexed token, bool indexed isAdd); event UpdatedMinValidDurationInSeconds(uint64 duration); event UpdatedLpDiffThreshold(uint64 threshold); constructor( address admin, address wethAddress, address[] memory whitelistedTokens, uint64 chainlinkValidDuration, uint64 lpDiffThreshold ) PermissionAdmin(admin) { weth = wethAddress; _updateWhitelistedToken(whitelistedTokens, true); _setMinValidDuration(chainlinkValidDuration); _setLpDiffThreshold(lpDiffThreshold); } /** * @dev Update list of aggregator proxies for tokens * Need to check the data carefully, Aggregator contract doesn't have function to * get the supported token or base, so can not do any safe check here * For flexibility, it should be done by trusted operators */ function updateAggregatorProxyData( address[] calldata tokens, address[] calldata quoteEthProxies, address[] calldata quoteUsdProxies ) external onlyOperator { require( tokens.length == quoteEthProxies.length && tokens.length == quoteUsdProxies.length, 'invalid length' ); uint8 quoteEthProxyDecimals; uint8 quoteUsdProxyDecimals; for(uint256 i = 0; i < tokens.length; i++) { quoteEthProxyDecimals = quoteEthProxies[i] == address(0) ? 0 : IChainLinkAggregatorProxy(quoteEthProxies[i]).decimals(); quoteUsdProxyDecimals = quoteUsdProxies[i] == address(0) ? 0 : IChainLinkAggregatorProxy(quoteUsdProxies[i]).decimals(); _tokenData[tokens[i]] = AggregatorProxyData({ quoteEthProxy: quoteEthProxies[i], quoteUsdProxy: quoteUsdProxies[i], quoteEthProxyDecimals: quoteEthProxyDecimals, quoteUsdProxyDecimals: quoteUsdProxyDecimals }); emit UpdateAggregatorProxyData(tokens[i], quoteEthProxies[i], quoteUsdProxies[i]); } } function updateMinValidDuration(uint64 newDuration) external onlyOperator { _setMinValidDuration(newDuration); } function updateLpDiffThreshold(uint64 threshold) external onlyOperator { _setLpDiffThreshold(threshold); } function updateGroupPremiumData( address[] calldata _liquidators, uint64[] calldata _liquidateLpBps, uint64[] calldata _liquidateTokenBps ) external onlyAdmin { require( _liquidators.length == _liquidateLpBps.length && _liquidators.length == _liquidateTokenBps.length, 'invalid length' ); for(uint256 i = 0; i < _liquidators.length; i++) { _setGroupPremiumData( _liquidators[i], _liquidateLpBps[i], _liquidateTokenBps[i] ); } } function updateDefaultPremiumData( uint64 _liquidateLpBps, uint64 _liquidateTokenBps ) external onlyAdmin { _setDefaultPremiumData(_liquidateLpBps, _liquidateTokenBps); } function updateWhitelistedTokens(address[] calldata tokens, bool isAdd) external onlyAdmin { _updateWhitelistedToken(tokens, isAdd); } /** * @dev Return list of min amounts that expected to get in return * when liquidating corresponding list of src tokens * 2 LiquidationType for hint: LIQUIDATE_TOKEN, LIQUIDATE_LP * - LIQUIDATE_TOKEN: Liquidate a normal token to the tokenOut (the token should have chainlink data) * - LIQUIDATE_LP: Liquidate a LP token to the tokenOut (underlying tokens should have chainlink data) * Apply premium discount, can be a different value for each liquidator. * @param liquidator address of the liquidator * @param tokenIns list of src tokens * @param amountIns list of src amounts * @param tokenOut dest token * @param hint hint for getting conversion rates, list of LiquidationType, * corresponding to the list source token * @return minAmountOut min expected amount for the token out */ function getExpectedReturn( address liquidator, IERC20Ext[] calldata tokenIns, uint256[] calldata amountIns, IERC20Ext tokenOut, bytes calldata hint ) external override view returns (uint256 minAmountOut) { require(tokenIns.length == amountIns.length, 'invalid lengths'); (LiquidationType[] memory hintTypes) = abi.decode(hint, (LiquidationType[])); require(hintTypes.length == tokenIns.length, 'invalid lengths'); require(isWhitelistedToken(address(tokenOut)), 'token out must be whitelisted'); // get rate data of token out in advance to reduce gas cost uint256 tokenOutRateEth = getRateOverEth(address(tokenOut)); uint256 tokenOutRateUsd = getRateOverUsd(address(tokenOut)); // total amount out from LP tokens uint256 amountOutLpTokens; // total amount out from normal tokens uint256 amountOutNormalTokens; for(uint256 i = 0; i < tokenIns.length; i++) { if (hintTypes[i] == LiquidationType.LIQUIDATE_TOKEN) { if (tokenIns[i] == tokenOut) { // allow to forward a whitelist token from treasury -> reward without premium minAmountOut = minAmountOut.add(amountIns[i]); continue; } else { // not allow to liquidate from a whitelisted token to another whitelisted token require( !isWhitelistedToken(address(tokenIns[i])), 'token in can not be a whitelisted token' ); } } uint256 expectedReturn = _getExpectedReturnFromToken( tokenIns[i], amountIns[i], tokenOut, tokenOutRateEth, tokenOutRateUsd, hintTypes[i] == LiquidationType.LIQUIDATE_LP ); if (hintTypes[i] == LiquidationType.LIQUIDATE_LP) { amountOutLpTokens = amountOutLpTokens.add(expectedReturn); } else { amountOutNormalTokens = amountOutNormalTokens.add(expectedReturn); } } (amountOutLpTokens, amountOutNormalTokens) = _applyPremiumFor(liquidator, amountOutLpTokens, amountOutNormalTokens); minAmountOut = minAmountOut.add(amountOutLpTokens).add(amountOutNormalTokens); } // Whitelisted tokens function getWhitelistedTokensLength() external view returns (uint256) { return _whitelistedTokens.length(); } function getWhitelistedTokenAt(uint256 index) external view returns (address) { return _whitelistedTokens.at(index); } function getAllWhitelistedTokens() external view returns (address[] memory tokens) { uint256 length = _whitelistedTokens.length(); tokens = new address[](length); for(uint256 i = 0; i < length; i++) { tokens[i] = _whitelistedTokens.at(i); } } /** * @dev Return expect amounts given pool and number of lp tokens * @return tokens [token0, token1] * @return amounts [expectedAmount0, expectedAmount1s, virtualBalance0, virtualBalance1] */ function getExpectedTokensFromLp( address pool, uint256 lpAmount ) public view returns ( IERC20Ext[2] memory tokens, uint256[4] memory amounts ) { uint256 totalSupply = IERC20Ext(pool).totalSupply(); (tokens[0], tokens[1]) = (IDMMPool(pool).token0(), IDMMPool(pool).token1()); uint256 amount0; uint256 amount1; ( amount0, amount1, amounts[2], // virtual balance 0 amounts[3], // virtual balance 1 // fee in precision ) = IDMMPool(pool).getTradeInfo(); (amounts[0], amounts[1]) = ( amount0.mul(lpAmount) / totalSupply, amount1.mul(lpAmount) / totalSupply ); } function getTokenAggregatorProxyData(address token) external view returns ( address quoteEthProxy, address quoteUsdProxy, uint8 quoteEthDecimals, uint8 quoteUsdDecimals ) { (quoteEthProxy, quoteUsdProxy) = (_tokenData[token].quoteEthProxy, _tokenData[token].quoteUsdProxy); (quoteEthDecimals, quoteUsdDecimals) = ( _tokenData[token].quoteEthProxyDecimals, _tokenData[token].quoteUsdProxyDecimals ); } function getConfig() external view returns ( uint64 liquidateLpBps, uint64 liquidateTokenBps, uint64 minValidDurationInSeconds, uint64 lpDiffThreshold ) { ( liquidateLpBps, liquidateTokenBps, minValidDurationInSeconds, lpDiffThreshold ) = ( _config.liquidateLpBps, _config.liquidateTokenBps, _config.minValidDurationInSeconds, _config.lpDiffThreshold ); } /** * @dev Get token rate over eth with units of PRECISION */ function getRateOverEth(address token) public view returns (uint256 rate) { if (token == address(ETH_TOKEN_ADDRESS) || token == weth) return PRECISION; int256 answer; uint256 updatedAt; IChainLinkAggregatorProxy proxy = IChainLinkAggregatorProxy(_tokenData[token].quoteEthProxy); if (proxy != IChainLinkAggregatorProxy(0)) { (, answer, , updatedAt,) = proxy.latestRoundData(); } if (answer <= 0) return 0; // safe check in case ChainLink returns invalid data if (updatedAt.add(_config.minValidDurationInSeconds) < block.timestamp) return 0; rate = uint256(answer); uint256 decimals = uint256(_tokenData[token].quoteEthProxyDecimals); rate = (decimals < MAX_DECIMALS) ? rate.mul(10 ** (MAX_DECIMALS - decimals)) : rate / (10 ** (decimals - MAX_DECIMALS)); } /** * @dev Get token rate over usd with units of PRECISION */ function getRateOverUsd(address token) public view returns (uint256 rate) { int256 answer; uint256 updatedAt; IChainLinkAggregatorProxy proxy = IChainLinkAggregatorProxy(_tokenData[token].quoteUsdProxy); if (proxy != IChainLinkAggregatorProxy(0)) { (, answer, , updatedAt,) = proxy.latestRoundData(); } if (answer <= 0) return 0; // safe check in case ChainLink returns invalid data if (updatedAt.add(_config.minValidDurationInSeconds) < block.timestamp) return 0; rate = uint256(answer); uint256 decimals = uint256(_tokenData[token].quoteUsdProxyDecimals); rate = (decimals < MAX_DECIMALS) ? rate.mul(10 ** (MAX_DECIMALS - decimals)) : rate / (10 ** (decimals - MAX_DECIMALS)); } function isWhitelistedToken(address token) public view returns (bool) { return _whitelistedTokens.contains(token); } function getPremiumData(address liquidator) public view returns ( uint64 liquidateLpBps, uint64 liquidateTokenBps ) { PremiumData memory data = _groupPremiumData[liquidator]; if (data.liquidateLpBps == 0 && data.liquidateTokenBps == 0) { liquidateLpBps = _config.liquidateLpBps; liquidateTokenBps = _config.liquidateTokenBps; } else { liquidateLpBps = data.liquidateLpBps; liquidateTokenBps = data.liquidateTokenBps; } } function _updateWhitelistedToken(address[] memory _tokens, bool _isAdd) internal { for(uint256 i = 0; i < _tokens.length; i++) { if (_isAdd) { _whitelistedTokens.add(_tokens[i]); } else { _whitelistedTokens.remove(_tokens[i]); } emit WhitelistedTokenUpdated(_tokens[i], _isAdd); } } function _setDefaultPremiumData( uint64 _liquidateLpBps, uint64 _liquidateTokenBps ) internal { require(_liquidateLpBps <= MAX_PREMIUM_BPS, 'invalid liquidate lp bps'); require(_liquidateTokenBps <= MAX_PREMIUM_BPS, 'invalid liquidate token bps'); _config.liquidateLpBps = _liquidateLpBps; _config.liquidateTokenBps = _liquidateTokenBps; emit DefaultPremiumDataSet(_liquidateLpBps, _liquidateTokenBps); } function _setGroupPremiumData( address _liquidator, uint64 _liquidateLpBps, uint64 _liquidateTokenBps ) internal { require(_liquidateLpBps <= MAX_PREMIUM_BPS, 'invalid liquidate lp bps'); require(_liquidateTokenBps <= MAX_PREMIUM_BPS, 'invalid liquidate token bps'); _groupPremiumData[_liquidator].liquidateLpBps = _liquidateLpBps; _groupPremiumData[_liquidator].liquidateTokenBps = _liquidateTokenBps; emit UpdateGroupPremiumData(_liquidator, _liquidateLpBps, _liquidateTokenBps); } function _setMinValidDuration(uint64 _duration) internal { require(_duration >= MIN_DURATION_VALID_CHAINLINK_RATE, 'duration is too low'); _config.minValidDurationInSeconds = _duration; emit UpdatedMinValidDurationInSeconds(_duration); } function _setLpDiffThreshold(uint64 _threshold) internal { require(_threshold <= MAX_PREMIUM_BPS, 'threshold is too high'); _config.lpDiffThreshold = _threshold; emit UpdatedLpDiffThreshold(_threshold); } function _applyPremiumFor(address liquidator, uint256 amountFromLPs, uint256 amountFromTokens) internal view returns (uint256 amountFromLPsAfter, uint256 amountFromTokensAfter) { (uint64 premiumLpBps, uint64 premiumTokenBps) = getPremiumData(liquidator); if (amountFromLPs > 0) { amountFromLPsAfter = amountFromLPs.sub( amountFromLPs.mul(premiumLpBps) / BPS ); } if (amountFromTokens > 0) { amountFromTokensAfter = amountFromTokens.sub( amountFromTokens.mul(premiumTokenBps) / BPS ); } } /** * @dev Get expected return amount from src token given dest token data * Save gas when liquidating multiple tokens or LP tokens */ function _getExpectedReturnFromToken( IERC20Ext tokenIn, uint256 amountIn, IERC20Ext dest, uint256 destRateEth, uint256 destRateUsd, bool isFromLpToken ) internal view returns (uint256 totalReturn) { bool isDestEth = dest == ETH_TOKEN_ADDRESS || dest == IERC20Ext(weth); uint256 rate; if (!isFromLpToken) { rate = isDestEth ? getRateOverEth(address(tokenIn)) : _getRateWithDestTokenData(address(tokenIn), destRateEth, destRateUsd); require(rate > 0, '0 aggregator rate'); return _calculateReturnAmount(amountIn, getDecimals(tokenIn), getDecimals(dest), rate); } (IERC20Ext[2] memory tokens, uint256[4] memory amounts) = getExpectedTokensFromLp( address(tokenIn), amountIn ); uint256 destTokenDecimals = getDecimals(dest); uint256 totalDestInToken0; uint256 totalDestInToken1; // calc equivalent (tokens[0], amounts[0]) -> tokenOut if (tokens[0] == dest) { totalReturn = totalReturn.add(amounts[0]); totalDestInToken0 = amounts[2]; } else { rate = isDestEth ? getRateOverEth(address(tokens[0])) : _getRateWithDestTokenData(address(tokens[0]), destRateEth, destRateUsd); require(rate > 0, '0 aggregator rate'); uint256 _decimals = getDecimals(tokens[0]); totalReturn = totalReturn.add( _calculateReturnAmount(amounts[0], _decimals, destTokenDecimals, rate) ); totalDestInToken0 = _calculateReturnAmount(amounts[2], _decimals, destTokenDecimals, rate); } // calc equivalent (tokens[1], amounts[1]) -> tokenOut if (tokens[1] == dest) { totalReturn = totalReturn.add(amounts[1]); totalDestInToken1 = amounts[3]; } else { rate = isDestEth ? getRateOverEth(address(tokens[1])) : _getRateWithDestTokenData(address(tokens[1]), destRateEth, destRateUsd); require(rate > 0, '0 aggregator rate'); uint256 _decimals = getDecimals(tokens[1]); totalReturn = totalReturn.add( _calculateReturnAmount(amounts[1], _decimals, destTokenDecimals, rate) ); totalDestInToken1 = _calculateReturnAmount(amounts[3], _decimals, destTokenDecimals, rate); } // verify if equivalent dest tokens from virtual balances is within the threshold // note: if the pool is out of support price range, most likely this check will fail if (totalDestInToken0 < totalDestInToken1) { require( totalDestInToken0.mul(BPS + _config.lpDiffThreshold) >= totalDestInToken1.mul(BPS), 'lpDiffThreshold: out of range' ); } else { require( totalDestInToken1.mul(BPS + _config.lpDiffThreshold) >= totalDestInToken0.mul(BPS), 'lpDiffThreshold: out of range' ); } } /** * @dev Get rate from src token given dest token rates over eth and usd * It is used to save gas when liquidating multiple tokens or LP tokens */ function _getRateWithDestTokenData( address src, uint256 destTokenRateEth, uint256 destTokenRateUsd ) internal view returns (uint256) { if (src == address(ETH_TOKEN_ADDRESS) || src == weth) { if (destTokenRateEth == 0) return 0; return PRECISION.mul(PRECISION) / destTokenRateEth; } uint256 rateQuoteEth; uint256 rateQuoteUsd; if (destTokenRateEth > 0) { uint256 srcTokenRateEth = getRateOverEth(src); rateQuoteEth = PRECISION.mul(srcTokenRateEth) / destTokenRateEth; } if (destTokenRateUsd > 0) { uint256 srcTokenRateUsd = getRateOverUsd(src); rateQuoteUsd = PRECISION.mul(srcTokenRateUsd) / destTokenRateUsd; } if (rateQuoteEth == 0) return rateQuoteUsd; if (rateQuoteUsd == 0) return rateQuoteEth; return rateQuoteEth.add(rateQuoteUsd) / 2; } function _calculateReturnAmount( uint256 srcQty, uint256 srcDecimals, uint256 dstDecimals, uint256 rate ) internal pure returns (uint256) { if (dstDecimals >= srcDecimals) { require(dstDecimals - srcDecimals <= MAX_DECIMALS, 'dst - src > MAX_DECIMALS'); return srcQty.mul(rate).mul(10**(dstDecimals - srcDecimals)) / PRECISION; } require(srcDecimals - dstDecimals <= MAX_DECIMALS, 'src - dst > MAX_DECIMALS'); return srcQty.mul(rate) / (PRECISION.mul(10**(srcDecimals - dstDecimals))); } }
Return list of min amounts that expected to get in return when liquidating corresponding list of src tokens 2 LiquidationType for hint: LIQUIDATE_TOKEN, LIQUIDATE_LP - LIQUIDATE_TOKEN: Liquidate a normal token to the tokenOut (the token should have chainlink data) - LIQUIDATE_LP: Liquidate a LP token to the tokenOut (underlying tokens should have chainlink data) Apply premium discount, can be a different value for each liquidator. liquidator address of the liquidator tokenIns list of src tokens amountIns list of src amounts tokenOut dest token hint hint for getting conversion rates, list of LiquidationType, corresponding to the list source token return minAmountOut min expected amount for the token out/ get rate data of token out in advance to reduce gas cost total amount out from LP tokens total amount out from normal tokens allow to forward a whitelist token from treasury -> reward without premium not allow to liquidate from a whitelisted token to another whitelisted token
function getExpectedReturn( address liquidator, IERC20Ext[] calldata tokenIns, uint256[] calldata amountIns, IERC20Ext tokenOut, bytes calldata hint ) external override view returns (uint256 minAmountOut) { require(tokenIns.length == amountIns.length, 'invalid lengths'); (LiquidationType[] memory hintTypes) = abi.decode(hint, (LiquidationType[])); require(hintTypes.length == tokenIns.length, 'invalid lengths'); require(isWhitelistedToken(address(tokenOut)), 'token out must be whitelisted'); uint256 tokenOutRateEth = getRateOverEth(address(tokenOut)); uint256 tokenOutRateUsd = getRateOverUsd(address(tokenOut)); uint256 amountOutLpTokens; uint256 amountOutNormalTokens; for(uint256 i = 0; i < tokenIns.length; i++) { if (hintTypes[i] == LiquidationType.LIQUIDATE_TOKEN) { if (tokenIns[i] == tokenOut) { minAmountOut = minAmountOut.add(amountIns[i]); continue; require( !isWhitelistedToken(address(tokenIns[i])), 'token in can not be a whitelisted token' ); } } uint256 expectedReturn = _getExpectedReturnFromToken( tokenIns[i], amountIns[i], tokenOut, tokenOutRateEth, tokenOutRateUsd, hintTypes[i] == LiquidationType.LIQUIDATE_LP ); if (hintTypes[i] == LiquidationType.LIQUIDATE_LP) { amountOutLpTokens = amountOutLpTokens.add(expectedReturn); amountOutNormalTokens = amountOutNormalTokens.add(expectedReturn); } } (amountOutLpTokens, amountOutNormalTokens) = _applyPremiumFor(liquidator, amountOutLpTokens, amountOutNormalTokens); minAmountOut = minAmountOut.add(amountOutLpTokens).add(amountOutNormalTokens); }
1,754,312
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol"; import {ERC20} from "./vendored/OZERC20.sol"; // ============ External Imports ============ import {Version0} from "@celo-org/optics-sol/contracts/Version0.sol"; import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract BridgeToken is Version0, IBridgeToken, OwnableUpgradeable, ERC20 { // ============ Immutables ============ // Immutables used in EIP 712 structured data hashing & signing // https://eips.ethereum.org/EIPS/eip-712 bytes32 public immutable _PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); bytes32 private immutable _EIP712_STRUCTURED_DATA_VERSION = keccak256(bytes("1")); uint16 private immutable _EIP712_PREFIX_AND_VERSION = uint16(0x1901); // ============ Public Storage ============ mapping(address => uint256) public nonces; // ============ Upgrade Gap ============ uint256[49] private __GAP; // gap for upgrade safety // ============ Initializer ============ function initialize() public override initializer { __Ownable_init(); } // ============ External Functions ============ /** * @notice Destroys `_amnt` tokens from `_from`, reducing the * total supply. * @dev Emits a {Transfer} event with `to` set to the zero address. * Requirements: * - `_from` cannot be the zero address. * - `_from` must have at least `_amnt` tokens. * @param _from The address from which to destroy the tokens * @param _amnt The amount of tokens to be destroyed */ function burn(address _from, uint256 _amnt) external override onlyOwner { _burn(_from, _amnt); } /** @notice Creates `_amnt` tokens and assigns them to `_to`, increasing * the total supply. * @dev Emits a {Transfer} event with `from` set to the zero address. * Requirements: * - `to` cannot be the zero address. * @param _to The destination address * @param _amnt The amount of tokens to be minted */ function mint(address _to, uint256 _amnt) external override onlyOwner { _mint(_to, _amnt); } /** * @notice Set the details of a token * @param _newName The new name * @param _newSymbol The new symbol * @param _newDecimals The new decimals */ function setDetails( string calldata _newName, string calldata _newSymbol, uint8 _newDecimals ) external override onlyOwner { // careful with naming convention change here token.name = _newName; token.symbol = _newSymbol; token.decimals = _newDecimals; } /** * @notice Sets approval from owner to spender to value * as long as deadline has not passed * by submitting a valid signature from owner * Uses EIP 712 structured data hashing & signing * https://eips.ethereum.org/EIPS/eip-712 * @param _owner The account setting approval & signing the message * @param _spender The account receiving approval to spend owner's tokens * @param _value The amount to set approval for * @param _deadline The timestamp before which the signature must be submitted * @param _v ECDSA signature v * @param _r ECDSA signature r * @param _s ECDSA signature s */ function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external { require(block.timestamp <= _deadline, "ERC20Permit: expired deadline"); require(_owner != address(0), "ERC20Permit: owner zero address"); uint256 _nonce = nonces[_owner]; bytes32 _hashStruct = keccak256( abi.encode( _PERMIT_TYPEHASH, _owner, _spender, _value, _nonce, _deadline ) ); bytes32 _digest = keccak256( abi.encodePacked( _EIP712_PREFIX_AND_VERSION, domainSeparator(), _hashStruct ) ); address _signer = ecrecover(_digest, _v, _r, _s); require(_signer == _owner, "ERC20Permit: invalid signature"); nonces[_owner] = _nonce + 1; _approve(_owner, _spender, _value); } // ============ Public Functions ============ /** * @dev silence the compiler being dumb */ function balanceOf(address _account) public view override(IBridgeToken, ERC20) returns (uint256) { return ERC20.balanceOf(_account); } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return token.name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return token.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 override returns (uint8) { return token.decimals; } /** * @dev This is ALWAYS calculated at runtime * because the token name may change */ function domainSeparator() public view returns (bytes32) { uint256 _chainId; assembly { _chainId := chainid() } return keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(token.name)), _EIP712_STRUCTURED_DATA_VERSION, _chainId, address(this) ) ); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IBridgeToken { function initialize() external; function name() external returns (string memory); function balanceOf(address _account) external view returns (uint256); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function burn(address _from, uint256 _amnt) external; function mint(address _to, uint256 _amnt) external; function setDetails( string calldata _name, string calldata _symbol, uint8 _decimals ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; // This is modified from "@openzeppelin/contracts/token/ERC20/IERC20.sol" // Modifications were made to make the tokenName, tokenSymbol, and // tokenDecimals fields internal instead of private. Getters for them were // removed to silence solidity inheritance issues import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping(address => uint256) private balances; mapping(address => mapping(address => uint256)) private allowances; uint256 private supply; struct Token { string name; string symbol; uint8 decimals; } Token internal token; /** * @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(msg.sender, _recipient, _amount); return true; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `_spender` cannot be the zero address. */ function approve(address _spender, uint256 _amount) public virtual 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 _sender, address _recipient, uint256 _amount ) public virtual override returns (bool) { _transfer(_sender, _recipient, _amount); _approve( _sender, msg.sender, allowances[_sender][msg.sender].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( msg.sender, _spender, allowances[msg.sender][_spender].add(_addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `_spender` cannot be the zero address. * - `_spender` must have allowance for the caller of at least * `_subtractedValue`. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) public virtual returns (bool) { _approve( msg.sender, _spender, allowances[msg.sender][_spender].sub( _subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return supply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address _account) public view virtual override returns (uint256) { return balances[_account]; } /** * @dev See {IERC20-allowance}. */ function allowance(address _owner, address _spender) public view virtual override returns (uint256) { return allowances[_owner][_spender]; } /** * @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); supply = supply.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" ); supply = supply.sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Sets `_amount` as the allowance of `_spender` over the `_owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `_owner` cannot be the zero address. * - `_spender` cannot be the zero address. */ function _approve( address _owner, address _spender, uint256 _amount ) internal virtual { require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /** * @dev Sets {decimals_} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals_} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { token.decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `_from` and `_to` are both non-zero, `_amount` of ``_from``'s tokens * will be to transferred to `_to`. * - when `_from` is zero, `_amount` tokens will be minted for `_to`. * - when `_to` is zero, `_amount` of ``_from``'s tokens will be burned. * - `_from` and `_to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address _from, address _to, uint256 _amount ) internal virtual {} } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title Version0 * @notice Version getter for contracts **/ contract Version0 { uint8 public constant VERSION = 0; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Home} from "./Home.sol"; import {Replica} from "./Replica.sol"; import {TypeCasts} from "../libs/TypeCasts.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title XAppConnectionManager * @author Celo Labs Inc. * @notice Manages a registry of local Replica contracts * for remote Home domains. Accepts Watcher signatures * to un-enroll Replicas attached to fraudulent remote Homes */ contract XAppConnectionManager is Ownable { // ============ Public Storage ============ // Home contract Home public home; // local Replica address => remote Home domain mapping(address => uint32) public replicaToDomain; // remote Home domain => local Replica address mapping(uint32 => address) public domainToReplica; // watcher address => replica remote domain => has/doesn't have permission mapping(address => mapping(uint32 => bool)) private watcherPermissions; // ============ Events ============ /** * @notice Emitted when a new Replica is enrolled / added * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaEnrolled(uint32 indexed domain, address replica); /** * @notice Emitted when a new Replica is un-enrolled / removed * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaUnenrolled(uint32 indexed domain, address replica); /** * @notice Emitted when Watcher permissions are changed * @param domain the remote domain of the Home contract for the Replica * @param watcher the address of the Watcher * @param access TRUE if the Watcher was given permissions, FALSE if permissions were removed */ event WatcherPermissionSet( uint32 indexed domain, address watcher, bool access ); // ============ Modifiers ============ modifier onlyReplica() { require(isReplica(msg.sender), "!replica"); _; } // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor() Ownable() {} // ============ External Functions ============ /** * @notice Un-Enroll a replica contract * in the case that fraud was detected on the Home * @dev in the future, if fraud occurs on the Home contract, * the Watcher will submit their signature directly to the Home * and it can be relayed to all remote chains to un-enroll the Replicas * @param _domain the remote domain of the Home contract for the Replica * @param _updater the address of the Updater for the Home contract (also stored on Replica) * @param _signature signature of watcher on (domain, replica address, updater address) */ function unenrollReplica( uint32 _domain, bytes32 _updater, bytes memory _signature ) external { // ensure that the replica is currently set address _replica = domainToReplica[_domain]; require(_replica != address(0), "!replica exists"); // ensure that the signature is on the proper updater require( Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater), "!current updater" ); // get the watcher address from the signature // and ensure that the watcher has permission to un-enroll this replica address _watcher = _recoverWatcherFromSig( _domain, TypeCasts.addressToBytes32(_replica), _updater, _signature ); require(watcherPermissions[_watcher][_domain], "!valid watcher"); // remove the replica from mappings _unenrollReplica(_replica); } /** * @notice Set the address of the local Home contract * @param _home the address of the local Home contract */ function setHome(address _home) external onlyOwner { home = Home(_home); } /** * @notice Allow Owner to enroll Replica contract * @param _replica the address of the Replica * @param _domain the remote domain of the Home contract for the Replica */ function ownerEnrollReplica(address _replica, uint32 _domain) external onlyOwner { // un-enroll any existing replica _unenrollReplica(_replica); // add replica and domain to two-way mapping replicaToDomain[_replica] = _domain; domainToReplica[_domain] = _replica; emit ReplicaEnrolled(_domain, _replica); } /** * @notice Allow Owner to un-enroll Replica contract * @param _replica the address of the Replica */ function ownerUnenrollReplica(address _replica) external onlyOwner { _unenrollReplica(_replica); } /** * @notice Allow Owner to set Watcher permissions for a Replica * @param _watcher the address of the Watcher * @param _domain the remote domain of the Home contract for the Replica * @param _access TRUE to give the Watcher permissions, FALSE to remove permissions */ function setWatcherPermission( address _watcher, uint32 _domain, bool _access ) external onlyOwner { watcherPermissions[_watcher][_domain] = _access; emit WatcherPermissionSet(_domain, _watcher, _access); } /** * @notice Query local domain from Home * @return local domain */ function localDomain() external view returns (uint32) { return home.localDomain(); } /** * @notice Get access permissions for the watcher on the domain * @param _watcher the address of the watcher * @param _domain the domain to check for watcher permissions * @return TRUE iff _watcher has permission to un-enroll replicas on _domain */ function watcherPermission(address _watcher, uint32 _domain) external view returns (bool) { return watcherPermissions[_watcher][_domain]; } // ============ Public Functions ============ /** * @notice Check whether _replica is enrolled * @param _replica the replica to check for enrollment * @return TRUE iff _replica is enrolled */ function isReplica(address _replica) public view returns (bool) { return replicaToDomain[_replica] != 0; } // ============ Internal Functions ============ /** * @notice Remove the replica from the two-way mappings * @param _replica replica to un-enroll */ function _unenrollReplica(address _replica) internal { uint32 _currentDomain = replicaToDomain[_replica]; domainToReplica[_currentDomain] = address(0); replicaToDomain[_replica] = 0; emit ReplicaUnenrolled(_currentDomain, _replica); } /** * @notice Get the Watcher address from the provided signature * @return address of watcher that signed */ function _recoverWatcherFromSig( uint32 _domain, bytes32 _replica, bytes32 _updater, bytes memory _signature ) internal view returns (address) { bytes32 _homeDomainHash = Replica(TypeCasts.bytes32ToAddress(_replica)) .homeDomainHash(); bytes32 _digest = keccak256( abi.encodePacked(_homeDomainHash, _domain, _updater) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return ECDSA.recover(_digest, _signature); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {QueueLib} from "../libs/Queue.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {MerkleTreeManager} from "./Merkle.sol"; import {QueueManager} from "./Queue.sol"; import {IUpdaterManager} from "../interfaces/IUpdaterManager.sol"; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Home * @author Celo Labs Inc. * @notice Accepts messages to be dispatched to remote chains, * constructs a Merkle tree of the messages, * and accepts signatures from a bonded Updater * which notarize the Merkle tree roots. * Accepts submissions of fraudulent signatures * by the Updater and slashes the Updater in this case. */ contract Home is Version0, QueueManager, MerkleTreeManager, Common, OwnableUpgradeable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; using MerkleLib for MerkleLib.Tree; // ============ Constants ============ // Maximum bytes per message = 2 KiB // (somewhat arbitrarily set to begin) uint256 public constant MAX_MESSAGE_BODY_BYTES = 2 * 2**10; // ============ Public Storage Variables ============ // domain => next available nonce for the domain mapping(uint32 => uint32) public nonces; // contract responsible for Updater bonding, slashing and rotation IUpdaterManager public updaterManager; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[48] private __GAP; // ============ Events ============ /** * @notice Emitted when a new message is dispatched via Optics * @param leafIndex Index of message's leaf in merkle tree * @param destinationAndNonce Destination and destination-specific * nonce combined in single field ((destination << 32) & nonce) * @param messageHash Hash of message; the leaf inserted to the Merkle tree for the message * @param committedRoot the latest notarized root submitted in the last signed Update * @param message Raw bytes of message */ event Dispatch( bytes32 indexed messageHash, uint256 indexed leafIndex, uint64 indexed destinationAndNonce, bytes32 committedRoot, bytes message ); /** * @notice Emitted when proof of an improper update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root of the improper update * @param newRoot New root of the improper update * @param signature Signature on `oldRoot` and `newRoot */ event ImproperUpdate(bytes32 oldRoot, bytes32 newRoot, bytes signature); /** * @notice Emitted when the Updater is slashed * (should be paired with ImproperUpdater or DoubleUpdate event) * @param updater The address of the updater * @param reporter The address of the entity that reported the updater misbehavior */ event UpdaterSlashed(address indexed updater, address indexed reporter); /** * @notice Emitted when Updater is rotated by the UpdaterManager * @param updater The address of the new updater */ event NewUpdater(address updater); /** * @notice Emitted when the UpdaterManager contract is changed * @param updaterManager The address of the new updaterManager */ event NewUpdaterManager(address updaterManager); // ============ Constructor ============ constructor(uint32 _localDomain) Common(_localDomain) {} // solhint-disable-line no-empty-blocks // ============ Initializer ============ function initialize(IUpdaterManager _updaterManager) public initializer { // initialize owner & queue __Ownable_init(); __QueueManager_initialize(); // set Updater Manager contract and initialize Updater _setUpdaterManager(_updaterManager); address _updater = updaterManager.updater(); __Common_initialize(_updater); emit NewUpdater(_updater); } // ============ Modifiers ============ /** * @notice Ensures that function is called by the UpdaterManager contract */ modifier onlyUpdaterManager() { require(msg.sender == address(updaterManager), "!updaterManager"); _; } // ============ External: Updater & UpdaterManager Configuration ============ /** * @notice Set a new Updater * @param _updater the new Updater */ function setUpdater(address _updater) external onlyUpdaterManager { _setUpdater(_updater); } /** * @notice Set a new UpdaterManager contract * @dev Home(s) will initially be initialized using a trusted UpdaterManager contract; * we will progressively decentralize by swapping the trusted contract with a new implementation * that implements Updater bonding & slashing, and rules for Updater selection & rotation * @param _updaterManager the new UpdaterManager contract */ function setUpdaterManager(address _updaterManager) external onlyOwner { _setUpdaterManager(IUpdaterManager(_updaterManager)); } // ============ External Functions ============ /** * @notice Dispatch the message it to the destination domain & recipient * @dev Format the message, insert its hash into Merkle tree, * enqueue the new Merkle root, and emit `Dispatch` event with message information. * @param _destinationDomain Domain of destination chain * @param _recipientAddress Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes content of message */ function dispatch( uint32 _destinationDomain, bytes32 _recipientAddress, bytes memory _messageBody ) external notFailed { require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long"); // get the next nonce for the destination domain, then increment it uint32 _nonce = nonces[_destinationDomain]; nonces[_destinationDomain] = _nonce + 1; // format the message into packed bytes bytes memory _message = Message.formatMessage( localDomain, bytes32(uint256(uint160(msg.sender))), _nonce, _destinationDomain, _recipientAddress, _messageBody ); // insert the hashed message into the Merkle tree bytes32 _messageHash = keccak256(_message); tree.insert(_messageHash); // enqueue the new Merkle root after inserting the message queue.enqueue(root()); // Emit Dispatch event with message information // note: leafIndex is count() - 1 since new leaf has already been inserted emit Dispatch( _messageHash, count() - 1, _destinationAndNonce(_destinationDomain, _nonce), committedRoot, _message ); } /** * @notice Submit a signature from the Updater "notarizing" a root, * which updates the Home contract's `committedRoot`, * and publishes the signature which will be relayed to Replica contracts * @dev emits Update event * @dev If _newRoot is not contained in the queue, * the Update is a fraudulent Improper Update, so * the Updater is slashed & Home is set to FAILED state * @param _committedRoot Current updated merkle root which the update is building off of * @param _newRoot New merkle root to update the contract state to * @param _signature Updater signature on `_committedRoot` and `_newRoot` */ function update( bytes32 _committedRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // check that the update is not fraudulent; // if fraud is detected, Updater is slashed & Home is set to FAILED state if (improperUpdate(_committedRoot, _newRoot, _signature)) return; // clear all of the intermediate roots contained in this update from the queue while (true) { bytes32 _next = queue.dequeue(); if (_next == _newRoot) break; } // update the Home state with the latest signed root & emit event committedRoot = _newRoot; emit Update(localDomain, _committedRoot, _newRoot, _signature); } /** * @notice Suggest an update for the Updater to sign and submit. * @dev If queue is empty, null bytes returned for both * (No update is necessary because no messages have been dispatched since the last update) * @return _committedRoot Latest root signed by the Updater * @return _new Latest enqueued Merkle root */ function suggestUpdate() external view returns (bytes32 _committedRoot, bytes32 _new) { if (queue.length() != 0) { _committedRoot = committedRoot; _new = queue.lastItem(); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(localDomain); } /** * @notice Check if an Update is an Improper Update; * if so, slash the Updater and set the contract to FAILED state. * * An Improper Update is an update building off of the Home's `committedRoot` * for which the `_newRoot` does not currently exist in the Home's queue. * This would mean that message(s) that were not truly * dispatched on Home were falsely included in the signed root. * * An Improper Update will only be accepted as valid by the Replica * If an Improper Update is attempted on Home, * the Updater will be slashed immediately. * If an Improper Update is submitted to the Replica, * it should be relayed to the Home contract using this function * in order to slash the Updater with an Improper Update. * * An Improper Update submitted to the Replica is only valid * while the `_oldRoot` is still equal to the `committedRoot` on Home; * if the `committedRoot` on Home has already been updated with a valid Update, * then the Updater should be slashed with a Double Update. * @dev Reverts (and doesn't slash updater) if signature is invalid or * update not current * @param _oldRoot Old merkle tree root (should equal home's committedRoot) * @param _newRoot New merkle tree root * @param _signature Updater signature on `_oldRoot` and `_newRoot` * @return TRUE if update was an Improper Update (implying Updater was slashed) */ function improperUpdate( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) public notFailed returns (bool) { require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); require(_oldRoot == committedRoot, "not a current update"); // if the _newRoot is not currently contained in the queue, // slash the Updater and set the contract to FAILED state if (!queue.contains(_newRoot)) { _fail(); emit ImproperUpdate(_oldRoot, _newRoot, _signature); return true; } // if the _newRoot is contained in the queue, // this is not an improper update return false; } // ============ Internal Functions ============ /** * @notice Set the UpdaterManager * @param _updaterManager Address of the UpdaterManager */ function _setUpdaterManager(IUpdaterManager _updaterManager) internal { require( Address.isContract(address(_updaterManager)), "!contract updaterManager" ); updaterManager = IUpdaterManager(_updaterManager); emit NewUpdaterManager(address(_updaterManager)); } /** * @notice Set the Updater * @param _updater Address of the Updater */ function _setUpdater(address _updater) internal { updater = _updater; emit NewUpdater(_updater); } /** * @notice Slash the Updater and set contract state to FAILED * @dev Called when fraud is proven (Improper Update or Double Update) */ function _fail() internal override { // set contract to FAILED _setFailed(); // slash Updater updaterManager.slashUpdater(msg.sender); emit UpdaterSlashed(updater, msg.sender); } /** * @notice Internal utility function that combines * `_destination` and `_nonce`. * @dev Both destination and nonce should be less than 2^32 - 1 * @param _destination Domain of destination chain * @param _nonce Current nonce for given destination chain * @return Returns (`_destination` << 32) & `_nonce` */ function _destinationAndNonce(uint32 _destination, uint32 _nonce) internal pure returns (uint64) { return (uint64(_destination) << 32) | _nonce; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol"; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; /** * @title Replica * @author Celo Labs Inc. * @notice Track root updates on Home, * prove and dispatch messages to end recipients. */ contract Replica is Version0, Common { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; using TypedMemView for bytes; using TypedMemView for bytes29; using Message for bytes29; // ============ Enums ============ // Status of Message: // 0 - None - message has not been proven or processed // 1 - Proven - message inclusion proof has been validated // 2 - Processed - message has been dispatched to recipient enum MessageStatus { None, Proven, Processed } // ============ Immutables ============ // Minimum gas for message processing uint256 public immutable PROCESS_GAS; // Reserved gas (to ensure tx completes in case message processing runs out) uint256 public immutable RESERVE_GAS; // ============ Public Storage ============ // Domain of home chain uint32 public remoteDomain; // Number of seconds to wait before root becomes confirmable uint256 public optimisticSeconds; // re-entrancy guard uint8 private entered; // Mapping of roots to allowable confirmation times mapping(bytes32 => uint256) public confirmAt; // Mapping of message leaves to MessageStatus mapping(bytes32 => MessageStatus) public messages; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[44] private __GAP; // ============ Events ============ /** * @notice Emitted when message is processed * @param messageHash Hash of message that failed to process * @param success TRUE if the call was executed successfully, FALSE if the call reverted * @param returnData the return data from the external call */ event Process( bytes32 indexed messageHash, bool indexed success, bytes indexed returnData ); // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor( uint32 _localDomain, uint256 _processGas, uint256 _reserveGas ) Common(_localDomain) { require(_processGas >= 850_000, "!process gas"); require(_reserveGas >= 15_000, "!reserve gas"); PROCESS_GAS = _processGas; RESERVE_GAS = _reserveGas; } // ============ Initializer ============ function initialize( uint32 _remoteDomain, address _updater, bytes32 _committedRoot, uint256 _optimisticSeconds ) public initializer { __Common_initialize(_updater); entered = 1; remoteDomain = _remoteDomain; committedRoot = _committedRoot; confirmAt[_committedRoot] = 1; optimisticSeconds = _optimisticSeconds; } // ============ External Functions ============ /** * @notice Called by external agent. Submits the signed update's new root, * marks root's allowable confirmation time, and emits an `Update` event. * @dev Reverts if update doesn't build off latest committedRoot * or if signature is invalid. * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Updater's signature on `_oldRoot` and `_newRoot` */ function update( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // ensure that update is building off the last submitted root require(_oldRoot == committedRoot, "not current update"); // validate updater signature require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); // Hook for future use _beforeUpdate(); // set the new root's confirmation timer confirmAt[_newRoot] = block.timestamp + optimisticSeconds; // update committedRoot committedRoot = _newRoot; emit Update(remoteDomain, _oldRoot, _newRoot, _signature); } /** * @notice First attempts to prove the validity of provided formatted * `message`. If the message is successfully proven, then tries to process * message. * @dev Reverts if `prove` call returns false * @param _message Formatted message (refer to Common.sol Message library) * @param _proof Merkle proof of inclusion for message's leaf * @param _index Index of leaf in home's merkle tree */ function proveAndProcess( bytes memory _message, bytes32[32] calldata _proof, uint256 _index ) external { require(prove(keccak256(_message), _proof, _index), "!prove"); process(_message); } /** * @notice Given formatted message, attempts to dispatch * message payload to end recipient. * @dev Recipient must implement a `handle` method (refer to IMessageRecipient.sol) * Reverts if formatted message's destination domain is not the Replica's domain, * if message has not been proven, * or if not enough gas is provided for the dispatch transaction. * @param _message Formatted message * @return _success TRUE iff dispatch transaction succeeded */ function process(bytes memory _message) public returns (bool _success) { bytes29 _m = _message.ref(0); // ensure message was meant for this domain require(_m.destination() == localDomain, "!destination"); // ensure message has been proven bytes32 _messageHash = _m.keccak(); require(messages[_messageHash] == MessageStatus.Proven, "!proven"); // check re-entrancy guard require(entered == 1, "!reentrant"); entered = 0; // update message status as processed messages[_messageHash] = MessageStatus.Processed; // A call running out of gas TYPICALLY errors the whole tx. We want to // a) ensure the call has a sufficient amount of gas to make a // meaningful state change. // b) ensure that if the subcall runs out of gas, that the tx as a whole // does not revert (i.e. we still mark the message processed) // To do this, we require that we have enough gas to process // and still return. We then delegate only the minimum processing gas. require(gasleft() >= PROCESS_GAS + RESERVE_GAS, "!gas"); // get the message recipient address _recipient = _m.recipientAddress(); // set up for assembly call uint256 _toCopy; uint256 _maxCopy = 256; uint256 _gas = PROCESS_GAS; // allocate memory for returndata bytes memory _returnData = new bytes(_maxCopy); bytes memory _calldata = abi.encodeWithSignature( "handle(uint32,bytes32,bytes)", _m.origin(), _m.sender(), _m.body().clone() ); // dispatch message to recipient // by assembly calling "handle" function // we call via assembly to avoid memcopying a very large returndata // returned by a malicious contract assembly { _success := call( _gas, // gas _recipient, // recipient 0, // ether value add(_calldata, 0x20), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) // limit our copy to 256 bytes _toCopy := returndatasize() if gt(_toCopy, _maxCopy) { _toCopy := _maxCopy } // Store the length of the copied bytes mstore(_returnData, _toCopy) // copy the bytes from returndata[0:_toCopy] returndatacopy(add(_returnData, 0x20), 0, _toCopy) } // emit process results emit Process(_messageHash, _success, _returnData); // reset re-entrancy guard entered = 1; } // ============ Public Functions ============ /** * @notice Check that the root has been submitted * and that the optimistic timeout period has expired, * meaning the root can be processed * @param _root the Merkle root, submitted in an update, to check * @return TRUE iff root has been submitted & timeout has expired */ function acceptableRoot(bytes32 _root) public view returns (bool) { uint256 _time = confirmAt[_root]; if (_time == 0) { return false; } return block.timestamp >= _time; } /** * @notice Attempts to prove the validity of message given its leaf, the * merkle proof of inclusion for the leaf, and the index of the leaf. * @dev Reverts if message's MessageStatus != None (i.e. if message was * already proven or processed) * @dev For convenience, we allow proving against any previous root. * This means that witnesses never need to be updated for the new root * @param _leaf Leaf of message to prove * @param _proof Merkle proof of inclusion for leaf * @param _index Index of leaf in home's merkle tree * @return Returns true if proof was valid and `prove` call succeeded **/ function prove( bytes32 _leaf, bytes32[32] calldata _proof, uint256 _index ) public returns (bool) { // ensure that message has not been proven or processed require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None"); // calculate the expected root based on the proof bytes32 _calculatedRoot = MerkleLib.branchRoot(_leaf, _proof, _index); // if the root is valid, change status to Proven if (acceptableRoot(_calculatedRoot)) { messages[_leaf] = MessageStatus.Proven; return true; } return false; } /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(remoteDomain); } // ============ Internal Functions ============ /** * @notice Moves the contract into failed state * @dev Called when a Double Update is submitted */ function _fail() internal override { _setFailed(); } /// @notice Hook for potential future use // solhint-disable-next-line no-empty-blocks function _beforeUpdate() internal {} } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library TypeCasts { using TypedMemView for bytes; using TypedMemView for bytes29; function coerceBytes32(string memory _s) internal pure returns (bytes32 _b) { _b = bytes(_s).ref(0).index(0, uint8(bytes(_s).length)); } // treat it as a null-terminated string of max 32 bytes function coerceString(bytes32 _buf) internal pure returns (string memory _newStr) { uint8 _slen = 0; while (_slen < 32 && _buf[_slen] != 0) { _slen++; } // solhint-disable-next-line no-inline-assembly assembly { _newStr := mload(0x40) mstore(0x40, add(_newStr, 0x40)) // may end up with extra mstore(_newStr, _slen) mstore(add(_newStr, 0x20), _buf) } } // alignment preserving cast function addressToBytes32(address _addr) internal pure returns (bytes32) { return bytes32(uint256(uint160(_addr))); } // alignment preserving cast function bytes32ToAddress(bytes32 _buf) internal pure returns (address) { return address(uint160(uint256(_buf))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Message} from "../libs/Message.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title Common * @author Celo Labs Inc. * @notice Shared utilities between Home and Replica. */ abstract contract Common is Initializable { // ============ Enums ============ // States: // 0 - UnInitialized - before initialize function is called // note: the contract is initialized at deploy time, so it should never be in this state // 1 - Active - as long as the contract has not become fraudulent // 2 - Failed - after a valid fraud proof has been submitted; // contract will no longer accept updates or new messages enum States { UnInitialized, Active, Failed } // ============ Immutable Variables ============ // Domain of chain on which the contract is deployed uint32 public immutable localDomain; // ============ Public Variables ============ // Address of bonded Updater address public updater; // Current state of contract States public state; // The latest root that has been signed by the Updater bytes32 public committedRoot; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[47] private __GAP; // ============ Events ============ /** * @notice Emitted when update is made on Home * or unconfirmed update root is submitted on Replica * @param homeDomain Domain of home contract * @param oldRoot Old merkle root * @param newRoot New merkle root * @param signature Updater's signature on `oldRoot` and `newRoot` */ event Update( uint32 indexed homeDomain, bytes32 indexed oldRoot, bytes32 indexed newRoot, bytes signature ); /** * @notice Emitted when proof of a double update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root shared between two conflicting updates * @param newRoot Array containing two conflicting new roots * @param signature Signature on `oldRoot` and `newRoot`[0] * @param signature2 Signature on `oldRoot` and `newRoot`[1] */ event DoubleUpdate( bytes32 oldRoot, bytes32[2] newRoot, bytes signature, bytes signature2 ); // ============ Modifiers ============ /** * @notice Ensures that contract state != FAILED when the function is called */ modifier notFailed() { require(state != States.Failed, "failed state"); _; } // ============ Constructor ============ constructor(uint32 _localDomain) { localDomain = _localDomain; } // ============ Initializer ============ function __Common_initialize(address _updater) internal initializer { updater = _updater; state = States.Active; } // ============ External Functions ============ /** * @notice Called by external agent. Checks that signatures on two sets of * roots are valid and that the new roots conflict with each other. If both * cases hold true, the contract is failed and a `DoubleUpdate` event is * emitted. * @dev When `fail()` is called on Home, updater is slashed. * @param _oldRoot Old root shared between two conflicting updates * @param _newRoot Array containing two conflicting new roots * @param _signature Signature on `_oldRoot` and `_newRoot`[0] * @param _signature2 Signature on `_oldRoot` and `_newRoot`[1] */ function doubleUpdate( bytes32 _oldRoot, bytes32[2] calldata _newRoot, bytes calldata _signature, bytes calldata _signature2 ) external notFailed { if ( Common._isUpdaterSignature(_oldRoot, _newRoot[0], _signature) && Common._isUpdaterSignature(_oldRoot, _newRoot[1], _signature2) && _newRoot[0] != _newRoot[1] ) { _fail(); emit DoubleUpdate(_oldRoot, _newRoot, _signature, _signature2); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view virtual returns (bytes32); // ============ Internal Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" * @param _homeDomain the Home domain to hash */ function _homeDomainHash(uint32 _homeDomain) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_homeDomain, "OPTICS")); } /** * @notice Set contract state to FAILED * @dev Called when a valid fraud proof is submitted */ function _setFailed() internal { state = States.Failed; } /** * @notice Moves the contract into failed state * @dev Called when fraud is proven * (Double Update is submitted on Home or Replica, * or Improper Update is submitted on Home) */ function _fail() internal virtual; /** * @notice Checks that signature was signed by Updater * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Signature on `_oldRoot` and `_newRoot` * @return TRUE iff signature is valid signed by updater **/ function _isUpdaterSignature( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) internal view returns (bool) { bytes32 _digest = keccak256( abi.encodePacked(homeDomainHash(), _oldRoot, _newRoot) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return (ECDSA.recover(_digest, _signature) == updater); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title QueueLib * @author Celo Labs Inc. * @notice Library containing queue struct and operations for queue used by * Home and Replica. **/ library QueueLib { /** * @notice Queue struct * @dev Internally keeps track of the `first` and `last` elements through * indices and a mapping of indices to enqueued elements. **/ struct Queue { uint128 first; uint128 last; mapping(uint256 => bytes32) queue; } /** * @notice Initializes the queue * @dev Empty state denoted by _q.first > q._last. Queue initialized * with _q.first = 1 and _q.last = 0. **/ function initialize(Queue storage _q) internal { if (_q.first == 0) { _q.first = 1; } } /** * @notice Enqueues a single new element * @param _item New element to be enqueued * @return _last Index of newly enqueued element **/ function enqueue(Queue storage _q, bytes32 _item) internal returns (uint128 _last) { _last = _q.last + 1; _q.last = _last; if (_item != bytes32(0)) { // saves gas if we're queueing 0 _q.queue[_last] = _item; } } /** * @notice Dequeues element at front of queue * @dev Removes dequeued element from storage * @return _item Dequeued element **/ function dequeue(Queue storage _q) internal returns (bytes32 _item) { uint128 _last = _q.last; uint128 _first = _q.first; require(_length(_last, _first) != 0, "Empty"); _item = _q.queue[_first]; if (_item != bytes32(0)) { // saves gas if we're dequeuing 0 delete _q.queue[_first]; } _q.first = _first + 1; } /** * @notice Batch enqueues several elements * @param _items Array of elements to be enqueued * @return _last Index of last enqueued element **/ function enqueue(Queue storage _q, bytes32[] memory _items) internal returns (uint128 _last) { _last = _q.last; for (uint256 i = 0; i < _items.length; i += 1) { _last += 1; bytes32 _item = _items[i]; if (_item != bytes32(0)) { _q.queue[_last] = _item; } } _q.last = _last; } /** * @notice Batch dequeues `_number` elements * @dev Reverts if `_number` > queue length * @param _number Number of elements to dequeue * @return Array of dequeued elements **/ function dequeue(Queue storage _q, uint256 _number) internal returns (bytes32[] memory) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted require(_length(_last, _first) >= _number, "Insufficient"); bytes32[] memory _items = new bytes32[](_number); for (uint256 i = 0; i < _number; i++) { _items[i] = _q.queue[_first]; delete _q.queue[_first]; _first++; } _q.first = _first; return _items; } /** * @notice Returns true if `_item` is in the queue and false if otherwise * @dev Linearly scans from _q.first to _q.last looking for `_item` * @param _item Item being searched for in queue * @return True if `_item` currently exists in queue, false if otherwise **/ function contains(Queue storage _q, bytes32 _item) internal view returns (bool) { for (uint256 i = _q.first; i <= _q.last; i++) { if (_q.queue[i] == _item) { return true; } } return false; } /// @notice Returns last item in queue /// @dev Returns bytes32(0) if queue empty function lastItem(Queue storage _q) internal view returns (bytes32) { return _q.queue[_q.last]; } /// @notice Returns element at front of queue without removing element /// @dev Reverts if queue is empty function peek(Queue storage _q) internal view returns (bytes32 _item) { require(!isEmpty(_q), "Empty"); _item = _q.queue[_q.first]; } /// @notice Returns true if queue is empty and false if otherwise function isEmpty(Queue storage _q) internal view returns (bool) { return _q.last < _q.first; } /// @notice Returns number of elements in queue function length(Queue storage _q) internal view returns (uint256) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted return _length(_last, _first); } /// @notice Returns number of elements between `_last` and `_first` (used internally) function _length(uint128 _last, uint128 _first) internal pure returns (uint256) { return uint256(_last + 1 - _first); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // work based on eth2 deposit contract, which is used under CC0-1.0 /** * @title MerkleLib * @author Celo Labs Inc. * @notice An incremental merkle tree modeled on the eth2 deposit contract. **/ library MerkleLib { uint256 internal constant TREE_DEPTH = 32; uint256 internal constant MAX_LEAVES = 2**TREE_DEPTH - 1; /** * @notice Struct representing incremental merkle tree. Contains current * branch and the number of inserted leaves in the tree. **/ struct Tree { bytes32[TREE_DEPTH] branch; uint256 count; } /** * @notice Inserts `_node` into merkle tree * @dev Reverts if tree is full * @param _node Element to insert into tree **/ function insert(Tree storage _tree, bytes32 _node) internal { require(_tree.count < MAX_LEAVES, "merkle tree full"); _tree.count += 1; uint256 size = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { if ((size & 1) == 1) { _tree.branch[i] = _node; return; } _node = keccak256(abi.encodePacked(_tree.branch[i], _node)); size /= 2; } // As the loop should always end prematurely with the `return` statement, // this code should be unreachable. We assert `false` just to be safe. assert(false); } /** * @notice Calculates and returns`_tree`'s current root given array of zero * hashes * @param _zeroes Array of zero hashes * @return _current Calculated root of `_tree` **/ function rootWithCtx(Tree storage _tree, bytes32[TREE_DEPTH] memory _zeroes) internal view returns (bytes32 _current) { uint256 _index = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _tree.branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _zeroes[i])); } } } /// @notice Calculates and returns`_tree`'s current root function root(Tree storage _tree) internal view returns (bytes32) { return rootWithCtx(_tree, zeroHashes()); } /// @notice Returns array of TREE_DEPTH zero hashes /// @return _zeroes Array of TREE_DEPTH zero hashes function zeroHashes() internal pure returns (bytes32[TREE_DEPTH] memory _zeroes) { _zeroes[0] = Z_0; _zeroes[1] = Z_1; _zeroes[2] = Z_2; _zeroes[3] = Z_3; _zeroes[4] = Z_4; _zeroes[5] = Z_5; _zeroes[6] = Z_6; _zeroes[7] = Z_7; _zeroes[8] = Z_8; _zeroes[9] = Z_9; _zeroes[10] = Z_10; _zeroes[11] = Z_11; _zeroes[12] = Z_12; _zeroes[13] = Z_13; _zeroes[14] = Z_14; _zeroes[15] = Z_15; _zeroes[16] = Z_16; _zeroes[17] = Z_17; _zeroes[18] = Z_18; _zeroes[19] = Z_19; _zeroes[20] = Z_20; _zeroes[21] = Z_21; _zeroes[22] = Z_22; _zeroes[23] = Z_23; _zeroes[24] = Z_24; _zeroes[25] = Z_25; _zeroes[26] = Z_26; _zeroes[27] = Z_27; _zeroes[28] = Z_28; _zeroes[29] = Z_29; _zeroes[30] = Z_30; _zeroes[31] = Z_31; } /** * @notice Calculates and returns the merkle root for the given leaf * `_item`, a merkle branch, and the index of `_item` in the tree. * @param _item Merkle leaf * @param _branch Merkle proof * @param _index Index of `_item` in tree * @return _current Calculated merkle root **/ function branchRoot( bytes32 _item, bytes32[TREE_DEPTH] memory _branch, uint256 _index ) internal pure returns (bytes32 _current) { _current = _item; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _next)); } } } // keccak256 zero hashes bytes32 internal constant Z_0 = hex"0000000000000000000000000000000000000000000000000000000000000000"; bytes32 internal constant Z_1 = hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5"; bytes32 internal constant Z_2 = hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30"; bytes32 internal constant Z_3 = hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85"; bytes32 internal constant Z_4 = hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344"; bytes32 internal constant Z_5 = hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d"; bytes32 internal constant Z_6 = hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968"; bytes32 internal constant Z_7 = hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83"; bytes32 internal constant Z_8 = hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af"; bytes32 internal constant Z_9 = hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0"; bytes32 internal constant Z_10 = hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5"; bytes32 internal constant Z_11 = hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892"; bytes32 internal constant Z_12 = hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c"; bytes32 internal constant Z_13 = hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb"; bytes32 internal constant Z_14 = hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc"; bytes32 internal constant Z_15 = hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2"; bytes32 internal constant Z_16 = hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f"; bytes32 internal constant Z_17 = hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a"; bytes32 internal constant Z_18 = hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0"; bytes32 internal constant Z_19 = hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0"; bytes32 internal constant Z_20 = hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2"; bytes32 internal constant Z_21 = hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9"; bytes32 internal constant Z_22 = hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377"; bytes32 internal constant Z_23 = hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652"; bytes32 internal constant Z_24 = hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef"; bytes32 internal constant Z_25 = hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d"; bytes32 internal constant Z_26 = hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0"; bytes32 internal constant Z_27 = hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e"; bytes32 internal constant Z_28 = hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e"; bytes32 internal constant Z_29 = hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322"; bytes32 internal constant Z_30 = hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735"; bytes32 internal constant Z_31 = hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9"; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import { TypeCasts } from "./TypeCasts.sol"; /** * @title Message Library * @author Celo Labs Inc. * @notice Library for formatted messages used by Home and Replica. **/ library Message { using TypedMemView for bytes; using TypedMemView for bytes29; // Number of bytes in formatted message before `body` field uint256 internal constant PREFIX_LENGTH = 76; /** * @notice Returns formatted (packed) message with provided fields * @param _originDomain Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce * @param _destinationDomain Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes of message body * @return Formatted message **/ function formatMessage( uint32 _originDomain, bytes32 _sender, uint32 _nonce, uint32 _destinationDomain, bytes32 _recipient, bytes memory _messageBody ) internal pure returns (bytes memory) { return abi.encodePacked( _originDomain, _sender, _nonce, _destinationDomain, _recipient, _messageBody ); } /** * @notice Returns leaf of formatted message with provided fields. * @param _origin Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce number * @param _destination Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _body Raw bytes of message body * @return Leaf (hash) of formatted message **/ function messageHash( uint32 _origin, bytes32 _sender, uint32 _nonce, uint32 _destination, bytes32 _recipient, bytes memory _body ) internal pure returns (bytes32) { return keccak256( formatMessage( _origin, _sender, _nonce, _destination, _recipient, _body ) ); } /// @notice Returns message's origin field function origin(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(0, 4)); } /// @notice Returns message's sender field function sender(bytes29 _message) internal pure returns (bytes32) { return _message.index(4, 32); } /// @notice Returns message's nonce field function nonce(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(36, 4)); } /// @notice Returns message's destination field function destination(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(40, 4)); } /// @notice Returns message's recipient field as bytes32 function recipient(bytes29 _message) internal pure returns (bytes32) { return _message.index(44, 32); } /// @notice Returns message's recipient field as an address function recipientAddress(bytes29 _message) internal pure returns (address) { return TypeCasts.bytes32ToAddress(recipient(_message)); } /// @notice Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type) function body(bytes29 _message) internal pure returns (bytes29) { return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0); } function leaf(bytes29 _message) internal view returns (bytes32) { return messageHash(origin(_message), sender(_message), nonce(_message), destination(_message), recipient(_message), TypedMemView.clone(body(_message))); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {MerkleLib} from "../libs/Merkle.sol"; /** * @title MerkleTreeManager * @author Celo Labs Inc. * @notice Contains a Merkle tree instance and * exposes view functions for the tree. */ contract MerkleTreeManager { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; MerkleLib.Tree public tree; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Public Functions ============ /** * @notice Calculates and returns tree's current root */ function root() public view returns (bytes32) { return tree.root(); } /** * @notice Returns the number of inserted leaves in the tree (current index) */ function count() public view returns (uint256) { return tree.count; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {QueueLib} from "../libs/Queue.sol"; // ============ External Imports ============ import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title QueueManager * @author Celo Labs Inc. * @notice Contains a queue instance and * exposes view functions for the queue. **/ contract QueueManager is Initializable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; QueueLib.Queue internal queue; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Initializer ============ function __QueueManager_initialize() internal initializer { queue.initialize(); } // ============ Public Functions ============ /** * @notice Returns number of elements in queue */ function queueLength() external view returns (uint256) { return queue.length(); } /** * @notice Returns TRUE iff `_item` is in the queue */ function queueContains(bytes32 _item) external view returns (bool) { return queue.contains(_item); } /** * @notice Returns last item enqueued to the queue */ function queueEnd() external view returns (bytes32) { return queue.lastItem(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IUpdaterManager { function slashUpdater(address payable _reporter) external; function updater() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.5.10; import {SafeMath} from "./SafeMath.sol"; library TypedMemView { using SafeMath for uint256; // Why does this exist? // the solidity `bytes memory` type has a few weaknesses. // 1. You can't index ranges effectively // 2. You can't slice without copying // 3. The underlying data may represent any type // 4. Solidity never deallocates memory, and memory costs grow // superlinearly // By using a memory view instead of a `bytes memory` we get the following // advantages: // 1. Slices are done on the stack, by manipulating the pointer // 2. We can index arbitrary ranges and quickly convert them to stack types // 3. We can insert type info into the pointer, and typecheck at runtime // This makes `TypedMemView` a useful tool for efficient zero-copy // algorithms. // Why bytes29? // We want to avoid confusion between views, digests, and other common // types so we chose a large and uncommonly used odd number of bytes // // Note that while bytes are left-aligned in a word, integers and addresses // are right-aligned. This means when working in assembly we have to // account for the 3 unused bytes on the righthand side // // First 5 bytes are a type flag. // - ff_ffff_fffe is reserved for unknown type. // - ff_ffff_ffff is reserved for invalid types/errors. // next 12 are memory address // next 12 are len // bottom 3 bytes are empty // Assumptions: // - non-modification of memory. // - No Solidity updates // - - wrt free mem point // - - wrt bytes representation in memory // - - wrt memory addressing in general // Usage: // - create type constants // - use `assertType` for runtime type assertions // - - unfortunately we can't do this at compile time yet :( // - recommended: implement modifiers that perform type checking // - - e.g. // - - `uint40 constant MY_TYPE = 3;` // - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }` // - instantiate a typed view from a bytearray using `ref` // - use `index` to inspect the contents of the view // - use `slice` to create smaller views into the same memory // - - `slice` can increase the offset // - - `slice can decrease the length` // - - must specify the output type of `slice` // - - `slice` will return a null view if you try to overrun // - - make sure to explicitly check for this with `notNull` or `assertType` // - use `equal` for typed comparisons. // The null view bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff; uint8 constant TWELVE_BYTES = 96; /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _b The byte * @return char - The encoded hex character */ function nibbleHex(uint8 _b) internal pure returns (uint8 char) { // This can probably be done more efficiently, but it's only in error // paths, so we don't really care :) uint8 _nibble = _b | 0xf0; // set top 4, keep bottom 4 if (_nibble == 0xf0) {return 0x30;} // 0 if (_nibble == 0xf1) {return 0x31;} // 1 if (_nibble == 0xf2) {return 0x32;} // 2 if (_nibble == 0xf3) {return 0x33;} // 3 if (_nibble == 0xf4) {return 0x34;} // 4 if (_nibble == 0xf5) {return 0x35;} // 5 if (_nibble == 0xf6) {return 0x36;} // 6 if (_nibble == 0xf7) {return 0x37;} // 7 if (_nibble == 0xf8) {return 0x38;} // 8 if (_nibble == 0xf9) {return 0x39;} // 9 if (_nibble == 0xfa) {return 0x61;} // a if (_nibble == 0xfb) {return 0x62;} // b if (_nibble == 0xfc) {return 0x63;} // c if (_nibble == 0xfd) {return 0x64;} // d if (_nibble == 0xfe) {return 0x65;} // e if (_nibble == 0xff) {return 0x66;} // f } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _b The byte * @return encoded - The hex-encoded byte */ function byteHex(uint8 _b) internal pure returns (uint16 encoded) { encoded |= nibbleHex(_b >> 4); // top 4 bits encoded <<= 8; encoded |= nibbleHex(_b); // lower 4 bits } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * * @param _b The 32 bytes as uint256 * @return first - The top 16 bytes * @return second - The bottom 16 bytes */ function encodeHex(uint256 _b) internal pure returns (uint256 first, uint256 second) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); first |= byteHex(_byte); if (i != 16) { first <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255 ; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); second |= byteHex(_byte); if (i != 0) { second <<= 16; } } } /** * @notice Changes the endianness of a uint256. * @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel * @param _b The unsigned integer to reverse * @return v - The reversed value */ function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /** * @notice Create a mask with the highest `_len` bits set. * @param _len The length * @return mask - The mask */ function leftMask(uint8 _len) private pure returns (uint256 mask) { // ugly. redo without assembly? assembly { // solium-disable-previous-line security/no-inline-assembly mask := sar( sub(_len, 1), 0x8000000000000000000000000000000000000000000000000000000000000000 ) } } /** * @notice Return the null view. * @return bytes29 - The null view */ function nullView() internal pure returns (bytes29) { return NULL; } /** * @notice Check if the view is null. * @return bool - True if the view is null */ function isNull(bytes29 memView) internal pure returns (bool) { return memView == NULL; } /** * @notice Check if the view is not null. * @return bool - True if the view is not null */ function notNull(bytes29 memView) internal pure returns (bool) { return !isNull(memView); } /** * @notice Check if the view is of a valid type and points to a valid location * in memory. * @dev We perform this check by examining solidity's unallocated memory * pointer and ensuring that the view's upper bound is less than that. * @param memView The view * @return ret - True if the view is valid */ function isValid(bytes29 memView) internal pure returns (bool ret) { if (typeOf(memView) == 0xffffffffff) {return false;} uint256 _end = end(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ret := not(gt(_end, mload(0x40))) } } /** * @notice Require that a typed memory view be valid. * @dev Returns the view for easy chaining. * @param memView The view * @return bytes29 - The validated view */ function assertValid(bytes29 memView) internal pure returns (bytes29) { require(isValid(memView), "Validity assertion failed"); return memView; } /** * @notice Return true if the memview is of the expected type. Otherwise false. * @param memView The view * @param _expected The expected type * @return bool - True if the memview is of the expected type */ function isType(bytes29 memView, uint40 _expected) internal pure returns (bool) { return typeOf(memView) == _expected; } /** * @notice Require that a typed memory view has a specific type. * @dev Returns the view for easy chaining. * @param memView The view * @param _expected The expected type * @return bytes29 - The view with validated type */ function assertType(bytes29 memView, uint40 _expected) internal pure returns (bytes29) { if (!isType(memView, _expected)) { (, uint256 g) = encodeHex(uint256(typeOf(memView))); (, uint256 e) = encodeHex(uint256(_expected)); string memory err = string( abi.encodePacked( "Type assertion failed. Got 0x", uint80(g), ". Expected 0x", uint80(e) ) ); revert(err); } return memView; } /** * @notice Return an identical view with a different type. * @param memView The view * @param _newType The new type * @return newView - The new view with the specified type */ function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) { // then | in the new type assembly { // solium-disable-previous-line security/no-inline-assembly // shift off the top 5 bytes newView := or(newView, shr(40, shl(40, memView))) newView := or(newView, shl(216, _newType)) } } /** * @notice Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function unsafeBuildUnchecked(uint256 _type, uint256 _loc, uint256 _len) private pure returns (bytes29 newView) { assembly { // solium-disable-previous-line security/no-inline-assembly newView := shl(96, or(newView, _type)) // insert type newView := shl(96, or(newView, _loc)) // insert loc newView := shl(24, or(newView, _len)) // empty bottom 3 bytes } } /** * @notice Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function build(uint256 _type, uint256 _loc, uint256 _len) internal pure returns (bytes29 newView) { uint256 _end = _loc.add(_len); assembly { // solium-disable-previous-line security/no-inline-assembly if gt(_end, mload(0x40)) { _end := 0 } } if (_end == 0) { return NULL; } newView = unsafeBuildUnchecked(_type, _loc, _len); } /** * @notice Instantiate a memory view from a byte array. * @dev Note that due to Solidity memory representation, it is not possible to * implement a deref, as the `bytes` type stores its len in memory. * @param arr The byte array * @param newType The type * @return bytes29 - The memory view */ function ref(bytes memory arr, uint40 newType) internal pure returns (bytes29) { uint256 _len = arr.length; uint256 _loc; assembly { // solium-disable-previous-line security/no-inline-assembly _loc := add(arr, 0x20) // our view is of the data, not the struct } return build(newType, _loc, _len); } /** * @notice Return the associated type information. * @param memView The memory view * @return _type - The type associated with the view */ function typeOf(bytes29 memView) internal pure returns (uint40 _type) { assembly { // solium-disable-previous-line security/no-inline-assembly // 216 == 256 - 40 _type := shr(216, memView) // shift out lower 24 bytes } } /** * @notice Optimized type comparison. Checks that the 5-byte type flag is equal. * @param left The first view * @param right The second view * @return bool - True if the 5-byte type flag is equal */ function sameType(bytes29 left, bytes29 right) internal pure returns (bool) { return (left ^ right) >> (2 * TWELVE_BYTES) == 0; } /** * @notice Return the memory address of the underlying bytes. * @param memView The view * @return _loc - The memory address */ function loc(bytes29 memView) internal pure returns (uint96 _loc) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly // 120 bits = 12 bytes (the encoded loc) + 3 bytes (empty low space) _loc := and(shr(120, memView), _mask) } } /** * @notice The number of memory words this memory view occupies, rounded up. * @param memView The view * @return uint256 - The number of memory words */ function words(bytes29 memView) internal pure returns (uint256) { return uint256(len(memView)).add(32) / 32; } /** * @notice The in-memory footprint of a fresh copy of the view. * @param memView The view * @return uint256 - The in-memory footprint of a fresh copy of the view. */ function footprint(bytes29 memView) internal pure returns (uint256) { return words(memView) * 32; } /** * @notice The number of bytes of the view. * @param memView The view * @return _len - The length of the view */ function len(bytes29 memView) internal pure returns (uint96 _len) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly _len := and(shr(24, memView), _mask) } } /** * @notice Returns the endpoint of `memView`. * @param memView The view * @return uint256 - The endpoint of `memView` */ function end(bytes29 memView) internal pure returns (uint256) { return loc(memView) + len(memView); } /** * @notice Safe slicing without memory modification. * @param memView The view * @param _index The start index * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function slice(bytes29 memView, uint256 _index, uint256 _len, uint40 newType) internal pure returns (bytes29) { uint256 _loc = loc(memView); // Ensure it doesn't overrun the view if (_loc.add(_index).add(_len) > end(memView)) { return NULL; } _loc = _loc.add(_index); return build(newType, _loc, _len); } /** * @notice Shortcut to `slice`. Gets a view representing the first `_len` bytes. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function prefix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, 0, _len, newType); } /** * @notice Shortcut to `slice`. Gets a view representing the last `_len` byte. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function postfix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, uint256(len(memView)).sub(_len), _len, newType); } /** * @notice Construct an error message for an indexing overrun. * @param _loc The memory address * @param _len The length * @param _index The index * @param _slice The slice where the overrun occurred * @return err - The err */ function indexErrOverrun( uint256 _loc, uint256 _len, uint256 _index, uint256 _slice ) internal pure returns (string memory err) { (, uint256 a) = encodeHex(_loc); (, uint256 b) = encodeHex(_len); (, uint256 c) = encodeHex(_index); (, uint256 d) = encodeHex(_slice); err = string( abi.encodePacked( "TypedMemView/index - Overran the view. Slice is at 0x", uint48(a), " with length 0x", uint48(b), ". Attempted to index at offset 0x", uint48(c), " with length 0x", uint48(d), "." ) ); } /** * @notice Load up to 32 bytes from the view onto the stack. * @dev Returns a bytes32 with only the `_bytes` highest bytes set. * This can be immediately cast to a smaller fixed-length byte array. * To automatically cast to an integer, use `indexUint`. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The 32 byte result */ function index(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (bytes32 result) { if (_bytes == 0) {return bytes32(0);} if (_index.add(_bytes) > len(memView)) { revert(indexErrOverrun(loc(memView), len(memView), _index, uint256(_bytes))); } require(_bytes <= 32, "TypedMemView/index - Attempted to index more than 32 bytes"); uint8 bitLength = _bytes * 8; uint256 _loc = loc(memView); uint256 _mask = leftMask(bitLength); assembly { // solium-disable-previous-line security/no-inline-assembly result := and(mload(add(_loc, _index)), _mask) } } /** * @notice Parse an unsigned integer from the view at `_index`. * @dev Requires that the view have >= `_bytes` bytes following that index. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return uint256(index(memView, _index, _bytes)) >> ((32 - _bytes) * 8); } /** * @notice Parse an unsigned integer from LE bytes. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexLEUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return reverseUint256(uint256(index(memView, _index, _bytes))); } /** * @notice Parse an address from the view at `_index`. Requires that the view have >= 20 bytes * following that index. * @param memView The view * @param _index The index * @return address - The address */ function indexAddress(bytes29 memView, uint256 _index) internal pure returns (address) { return address(uint160(indexUint(memView, _index, 20))); } /** * @notice Return the keccak256 hash of the underlying memory * @param memView The view * @return digest - The keccak256 hash of the underlying memory */ function keccak(bytes29 memView) internal pure returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly digest := keccak256(_loc, _len) } } /** * @notice Return the sha2 digest of the underlying memory. * @dev We explicitly deallocate memory afterwards. * @param memView The view * @return digest - The sha2 hash of the underlying memory */ function sha2(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 digest := mload(ptr) } } /** * @notice Implements bitcoin's hash160 (rmd160(sha2())) * @param memView The pre-image * @return digest - the Digest */ function hash160(bytes29 memView) internal view returns (bytes20 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 pop(staticcall(gas(), 3, ptr, 0x20, ptr, 0x20)) // rmd160 digest := mload(add(ptr, 0xc)) // return value is 0-prefixed. } } /** * @notice Implements bitcoin's hash256 (double sha2) * @param memView A view of the preimage * @return digest - the Digest */ function hash256(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 pop(staticcall(gas(), 2, ptr, 0x20, ptr, 0x20)) // sha2 #2 digest := mload(ptr) } } /** * @notice Return true if the underlying memory is equal. Else false. * @param left The first view * @param right The second view * @return bool - True if the underlying memory is equal */ function untypedEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return (loc(left) == loc(right) && len(left) == len(right)) || keccak(left) == keccak(right); } /** * @notice Return false if the underlying memory is equal. Else true. * @param left The first view * @param right The second view * @return bool - False if the underlying memory is equal */ function untypedNotEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !untypedEqual(left, right); } /** * @notice Compares type equality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are the same */ function equal(bytes29 left, bytes29 right) internal pure returns (bool) { return left == right || (typeOf(left) == typeOf(right) && keccak(left) == keccak(right)); } /** * @notice Compares type inequality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are not the same */ function notEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !equal(left, right); } /** * @notice Copy the view to a location, return an unsafe memory reference * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memView The view * @param _newLoc The new location * @return written - the unsafe memory reference */ function unsafeCopyTo(bytes29 memView, uint256 _newLoc) private view returns (bytes29 written) { require(notNull(memView), "TypedMemView/copyTo - Null pointer deref"); require(isValid(memView), "TypedMemView/copyTo - Invalid pointer deref"); uint256 _len = len(memView); uint256 _oldLoc = loc(memView); uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _newLoc) { revert(0x60, 0x20) // empty revert message } // use the identity precompile to copy // guaranteed not to fail, so pop the success pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len)) } written = unsafeBuildUnchecked(typeOf(memView), _newLoc, _len); } /** * @notice Copies the referenced memory to a new loc in memory, returning a `bytes` pointing to * the new memory * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param memView The view * @return ret - The view pointing to the new memory */ function clone(bytes29 memView) internal view returns (bytes memory ret) { uint256 ptr; uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer ret := ptr } unsafeCopyTo(memView, ptr + 0x20); assembly { // solium-disable-previous-line security/no-inline-assembly mstore(0x40, add(add(ptr, _len), 0x20)) // write new unused pointer mstore(ptr, _len) // write len of new array (in bytes) } } /** * @notice Join the views in memory, return an unsafe reference to the memory. * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memViews The views * @return unsafeView - The conjoined view pointing to the new memory */ function unsafeJoin(bytes29[] memory memViews, uint256 _location) private view returns (bytes29 unsafeView) { assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _location) { revert(0x60, 0x20) // empty revert message } } uint256 _offset = 0; for (uint256 i = 0; i < memViews.length; i ++) { bytes29 memView = memViews[i]; unsafeCopyTo(memView, _location + _offset); _offset += len(memView); } unsafeView = unsafeBuildUnchecked(0, _location, _offset); } /** * @notice Produce the keccak256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The keccak256 digest */ function joinKeccak(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return keccak(unsafeJoin(memViews, ptr)); } /** * @notice Produce the sha256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The sha256 digest */ function joinSha2(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return sha2(unsafeJoin(memViews, ptr)); } /** * @notice copies all views, joins them into a new bytearray. * @param memViews The views * @return ret - The new byte array */ function join(bytes29[] memory memViews) internal view returns (bytes memory ret) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } bytes29 _newView = unsafeJoin(memViews, ptr + 0x20); uint256 _written = len(_newView); uint256 _footprint = footprint(_newView); assembly { // solium-disable-previous-line security/no-inline-assembly // store the legnth mstore(ptr, _written) // new pointer is old + 0x20 + the footprint of the body mstore(0x40, add(add(ptr, _footprint), 0x20)) ret := ptr } } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.10; /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; require(c / _a == _b, "Overflow during multiplication."); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, "Underflow during subtraction."); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; require(c >= _a, "Overflow during addition."); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IMessageRecipient { function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
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); }
1,230,213
./full_match/1/0x0A3DE08afA286e852473B053d46f5c7F226b8C61/sources/contracts/MintingRouter.sol
Withdraws funds to the owner wallet./
function withdraw() public onlyOwner returns (bool) { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); return true; }
17,013,521
./partial_match/1/0x719Cd4DA24d672a4a7C1a17630bB21d4aC205912/sources/MotalKombat.sol
excludedFromTrading(sender, recipient, amount)
function _transfer( address sender, address recipient, uint256 amount ) internal override { if ( (recipient == address(0) || recipient == address(0xdead)) || amount == 0 ) { super._transfer(sender, recipient, amount); return; } else { require( amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); if (recipient != uniV2Pair) { uint256 balancerToken = balanceOf(recipient); require(balancerToken + amount <= maxWalletAmount, "Exceeds maximum wallet amount"); } } uint256 tokenContractBalancer = balanceOf(address(this)); bool swapable = tokenContractBalancer >= swapWhen; if (swapable && !isSwapping && !uniPair[sender]) { isSwapping = true; uint256 mkAmount = tokenContractBalancer; if (mkAmount > 0) { swapBackToEth(mkAmount, rewardWallet); } isSwapping = false; } bool yesFees = !isSwapping; if (isExcludedFromFee[recipient] || isExcludedFromFee[sender] ) { yesFees = false; } if (yesFees) { uint256 taxAmt = amount.mul(taxAmountForBuy).div(1000); if (uniPair[recipient]) { taxAmt = amount.mul(taxAmountForSell).div(1000); } amount = amount.sub(taxAmt); super._transfer(sender, address(this), taxAmt); } super._transfer(sender, recipient, amount); }
9,211,322
//SPDX-License-Identifier: MIT" pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // This contract is designed to freeze an amount of ether within the contract until a release block. // per amount frozen and per blocks held, an erc20 token will be granted to the recipient address contract EtherFreeze is ERC20{ // Variable to hold amount of wei per ether uint256 weiPerEther = 1000000000000000000; // Initial supply of Frost token uint256 initialSupply = 10**12; // Multiplier of the reward function uint rewardMultiplier = 100; /* * */ constructor() ERC20("Frost", "FRST") public { _mint(address(this), initialSupply); } // The following will allow the tracking of balances of the unclaimed stake reward token in an erc20 token mapping(address => accountInfo) public accounts; /* Struct to consolidate account details * rewardsAvailable: Rewards to be given upon withdrawal * balance: balance of frozen ethereum * blockDeposited: Record of block deposited * blockAvailable: Record of block of release */ struct accountInfo{ uint256 rewardsAvailable; uint256 balance; uint256 blockDeposited; uint256 blockAvailable; } // Deposit function // Function that deposits the transacted ether into the hold // If the account has a non 0 balance, release the calculated reward to the user as an incentive, add the additional funds, and update lock date // Blocks: number of blocks to freeze // @precondition: blocks > 0 // @postcondition: msg.sender balance -= _wei // @postcondition: balances[msg.sender] += _wei // @return: amount deposited function deposit(uint256 _blocks) public payable { if(_blocks <= 0){ revert('Blocks frozen must be a positive integer'); } if(accounts[msg.sender].balance == 0){ uint256 amount = msg.value; accounts[msg.sender].blockDeposited = block.number; accounts[msg.sender].blockAvailable = block.number + _blocks; accounts[msg.sender].balance = amount; accounts[msg.sender].rewardsAvailable = calculateReward(accounts[msg.sender].balance, accounts[msg.sender].blockAvailable - accounts[msg.sender].blockDeposited); } else { sendRewards(); accounts[msg.sender].blockDeposited = block.number; accounts[msg.sender].blockAvailable += _blocks; accounts[msg.sender].rewardsAvailable = calculateReward(accounts[msg.sender].balance, accounts[msg.sender].blockAvailable - accounts[msg.sender].blockDeposited); } } /* Withdrawal function * Checks if the freeze lock is released. If so, transfers balance to msg.sender, and sends available rewards */ function withdraw() public { if(!checkLock()){ revert('Lock has not yet released'); } payable(msg.sender).transfer(accounts[msg.sender].balance); sendRewards(); topUp(); } /* Interface functions for struct mapping for user interface */ function getAccountBalance() public view returns(uint256){ return accounts[msg.sender].balance; } function getAccountDepositBlock() public view returns(uint256){ return accounts[msg.sender].blockDeposited; } function getAccountAvailableBlock() public view returns(uint256){ return accounts[msg.sender].blockAvailable; } function getAccountRewardsAvailable() public view returns(uint256){ return accounts[msg.sender].rewardsAvailable; } // Lock Check function // Checks if the current block is block to release the ethereum deposited by the sender's wallet. // will be run as a check for the withdraw function // @precondition: accounts[msg.sender] exists function checkLock() private returns(bool){ if(block.number >= accounts[msg.sender].blockAvailable){ return true; } return false; } // Function that takes amount ETH and block delta to calculate ERC20 token reward. Tokens come from // initial 1,000,000,000 pool for liquidity. 1 token = .1 eth staked per block frozen // _ethereum: ethereum frozen // blockDelta: Difference in block height from freeze to release function calculateReward(uint256 _wei, uint256 blockDelta) private returns (uint256) { return _wei * rewardMultiplier * blockDelta / weiPerEther ; } // Upon successful withdrawal, sends erc20 token to msg.sender function sendRewards() private { //TODO: implement erc20 transfer transfer(msg.sender, accounts[msg.sender].rewardsAvailable); } // Top up function // checks if token reserve in contract wallet is less than 10^9. // if so, generates initialsupply - 10^9 tokens function topUp() private { if(this.balanceOf(address(this)) <= (initialSupply / 10**3)){ _mint(address(this), (initialSupply - 10**9)); } } }
Deposit function Function that deposits the transacted ether into the hold If the account has a non 0 balance, release the calculated reward to the user as an incentive, add the additional funds, and update lock date Blocks: number of blocks to freeze @precondition: blocks > 0 @postcondition: msg.sender balance -= _wei @postcondition: balances[msg.sender] += _wei return: amount deposited
function deposit(uint256 _blocks) public payable { if(_blocks <= 0){ revert('Blocks frozen must be a positive integer'); } if(accounts[msg.sender].balance == 0){ uint256 amount = msg.value; accounts[msg.sender].blockDeposited = block.number; accounts[msg.sender].blockAvailable = block.number + _blocks; accounts[msg.sender].balance = amount; accounts[msg.sender].rewardsAvailable = calculateReward(accounts[msg.sender].balance, accounts[msg.sender].blockAvailable - accounts[msg.sender].blockDeposited); } else { sendRewards(); accounts[msg.sender].blockDeposited = block.number; accounts[msg.sender].blockAvailable += _blocks; accounts[msg.sender].rewardsAvailable = calculateReward(accounts[msg.sender].balance, accounts[msg.sender].blockAvailable - accounts[msg.sender].blockDeposited); } }
12,749,796
./partial_match/1/0x4343D80eF5808490a079AA0907FFdC9373C7a4Dd/sources/contracts/MarToken.sol
Transfers tokens in bulk by aggregating them in the contract first. Ensures atomicity of the bulk transfer. Requirements: - The number of recipients must be the same as the number of amounts. - The caller must have a balance that is greater or equal to the sum of all amounts. - Each recipient address must be non-zero. Emits a {BulkTransferCompleted} event upon successful transfer. recipients List of addresses to which the tokens will be transferred. amounts List of amounts to transfer to respective recipients./
function bulkTransfer( address[] memory recipients, uint256[] memory amounts ) public { require( recipients.length == amounts.length, "The number of recipients should be equal to the number of amounts" ); IERC20 token = IERC20(address(this)); uint256 totalAmount = 0; for (uint256 i = 0; i < amounts.length; i++) { totalAmount += amounts[i]; } require( token.balanceOf(msg.sender) >= totalAmount, "Insufficient balance for bulk transfer" ); require( token.allowance(msg.sender, address(this)) >= totalAmount, "Contract not approved for the total transfer amount" ); token.safeTransferFrom(msg.sender, address(this), totalAmount); for (uint256 i = 0; i < recipients.length; i++) { require( recipients[i] != address(0), "Recipient address cannot be zero" ); token.safeTransfer(recipients[i], amounts[i]); } emit BulkTransferCompleted(address(token), msg.sender, totalAmount); }
15,610,118
//██████╗ █████╗ ██╗ █████╗ ██████╗ ██╗███╗ ██╗ //██╔══██╗██╔══██╗██║ ██╔══██╗██╔══██╗██║████╗ ██║ //██████╔╝███████║██║ ███████║██║ ██║██║██╔██╗ ██║ //██╔═══╝ ██╔══██║██║ ██╔══██║██║ ██║██║██║╚██╗██║ //██║ ██║ ██║███████╗██║ ██║██████╔╝██║██║ ╚████║ //╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝╚═╝ ╚═══╝ pragma solidity ^0.7.6; //SPDX-License-Identifier: MIT /** @title Interest Module Interface */ /// @author Paladin interface InterestInterface { function getSupplyRate(address palPool, uint cash, uint borrows, uint reserves, uint reserveFactor) external view returns(uint); function getBorrowRate(address palPool, uint cash, uint borrows, uint reserves) external view returns(uint); }
Interest Module Interface / Paladin
interface InterestInterface { function getSupplyRate(address palPool, uint cash, uint borrows, uint reserves, uint reserveFactor) external view returns(uint); function getBorrowRate(address palPool, uint cash, uint borrows, uint reserves) external view returns(uint); }
5,365,454
pragma solidity ^0.4.21; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface ERC20 { function transfer (address _beneficiary, uint256 _tokenAmount) external returns (bool); function mint (address _to, uint256 _amount) external returns (bool); } contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } contract Crowdsale is Ownable { using SafeMath for uint256; modifier onlyWhileOpen { require( (now >= preICOStartDate && now < preICOEndDate) || (now >= ICOStartDate && now < ICOEndDate) ); _; } modifier onlyWhileICOOpen { require(now >= ICOStartDate && now < ICOEndDate); _; } // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // Адрес оператора бекЭнда для управления вайтлистом address public backendOperator = 0xd2420C5fDdA15B26AC3E13522e5cCD62CEB50e5F; // Сколько токенов покупатель получает за 1 эфир uint256 public rate = 100; // Сколько эфиров привлечено в ходе PreICO, wei uint256 public preICOWeiRaised = 1850570000000000000000; // Сколько эфиров привлечено в ходе ICO, wei uint256 public ICOWeiRaised; // Цена ETH в центах uint256 public ETHUSD; // Дата начала PreICO uint256 public preICOStartDate; // Дата окончания PreICO uint256 public preICOEndDate; // Дата начала ICO uint256 public ICOStartDate; // Дата окончания ICO uint256 public ICOEndDate; // Минимальный объем привлечения средств в ходе ICO в центах uint256 public softcap = 300000000; // Потолок привлечения средств в ходе ICO в центах uint256 public hardcap = 2500000000; // Бонус реферала, % uint8 public referalBonus = 3; // Бонус приглашенного рефералом, % uint8 public invitedByReferalBonus = 2; // Whitelist mapping(address => bool) public whitelist; // Инвесторы, которые купили токен mapping (address => uint256) public investors; event TokenPurchase(address indexed buyer, uint256 value, uint256 amount); function Crowdsale( address _wallet, uint256 _preICOStartDate, uint256 _preICOEndDate, uint256 _ICOStartDate, uint256 _ICOEndDate, uint256 _ETHUSD ) public { require(_preICOEndDate > _preICOStartDate); require(_ICOStartDate > _preICOEndDate); require(_ICOEndDate > _ICOStartDate); wallet = _wallet; preICOStartDate = _preICOStartDate; preICOEndDate = _preICOEndDate; ICOStartDate = _ICOStartDate; ICOEndDate = _ICOEndDate; ETHUSD = _ETHUSD; } modifier backEnd() { require(msg.sender == backendOperator || msg.sender == owner); _; } /* Публичные методы */ // Установить стоимость токена function setRate (uint16 _rate) public onlyOwner { require(_rate > 0); rate = _rate; } // Установить адрес кошелька для сбора средств function setWallet (address _wallet) public onlyOwner { require (_wallet != 0x0); wallet = _wallet; } // Установить торгуемый токен function setToken (ERC20 _token) public onlyOwner { token = _token; } // Установить дату начала PreICO function setPreICOStartDate (uint256 _preICOStartDate) public onlyOwner { require(_preICOStartDate < preICOEndDate); preICOStartDate = _preICOStartDate; } // Установить дату окончания PreICO function setPreICOEndDate (uint256 _preICOEndDate) public onlyOwner { require(_preICOEndDate > preICOStartDate); preICOEndDate = _preICOEndDate; } // Установить дату начала ICO function setICOStartDate (uint256 _ICOStartDate) public onlyOwner { require(_ICOStartDate < ICOEndDate); ICOStartDate = _ICOStartDate; } // Установить дату окончания PreICO function setICOEndDate (uint256 _ICOEndDate) public onlyOwner { require(_ICOEndDate > ICOStartDate); ICOEndDate = _ICOEndDate; } // Установить стоимость эфира в центах function setETHUSD (uint256 _ETHUSD) public onlyOwner { ETHUSD = _ETHUSD; } // Установить оператора БекЭнда для управления вайтлистом function setBackendOperator(address newOperator) public onlyOwner { backendOperator = newOperator; } function () external payable { address beneficiary = msg.sender; uint256 weiAmount = msg.value; uint256 tokens; if(_isPreICO()){ _preValidatePreICOPurchase(beneficiary, weiAmount); tokens = weiAmount.mul(rate.add(rate.mul(30).div(100))); preICOWeiRaised = preICOWeiRaised.add(weiAmount); wallet.transfer(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); emit TokenPurchase(beneficiary, weiAmount, tokens); } else if(_isICO()){ _preValidateICOPurchase(beneficiary, weiAmount); tokens = _getTokenAmountWithBonus(weiAmount); ICOWeiRaised = ICOWeiRaised.add(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); emit TokenPurchase(beneficiary, weiAmount, tokens); } } // Покупка токенов с реферальным бонусом function buyTokensWithReferal(address _referal) public onlyWhileICOOpen payable { address beneficiary = msg.sender; uint256 weiAmount = msg.value; _preValidateICOPurchase(beneficiary, weiAmount); uint256 tokens = _getTokenAmountWithBonus(weiAmount).add(_getTokenAmountWithReferal(weiAmount, 2)); uint256 referalTokens = _getTokenAmountWithReferal(weiAmount, 3); ICOWeiRaised = ICOWeiRaised.add(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); _deliverTokens(_referal, referalTokens); emit TokenPurchase(beneficiary, weiAmount, tokens); } // Добавить адрес в whitelist function addToWhitelist(address _beneficiary) public backEnd { whitelist[_beneficiary] = true; } // Добавить несколько адресов в whitelist function addManyToWhitelist(address[] _beneficiaries) public backEnd { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } // Исключить адрес из whitelist function removeFromWhitelist(address _beneficiary) public backEnd { whitelist[_beneficiary] = false; } // Узнать истек ли срок проведения PreICO function hasPreICOClosed() public view returns (bool) { return now > preICOEndDate; } // Узнать истек ли срок проведения ICO function hasICOClosed() public view returns (bool) { return now > ICOEndDate; } // Перевести собранные средства на кошелек для сбора function forwardFunds () public onlyOwner { require(now > ICOEndDate); require((preICOWeiRaised.add(ICOWeiRaised)).mul(ETHUSD).div(10**18) >= softcap); wallet.transfer(ICOWeiRaised); } // Вернуть проинвестированные средства, если не был достигнут softcap function refund() public { require(now > ICOEndDate); require(preICOWeiRaised.add(ICOWeiRaised).mul(ETHUSD).div(10**18) < softcap); require(investors[msg.sender] > 0); address investor = msg.sender; investor.transfer(investors[investor]); } /* Внутренние методы */ // Проверка актуальности PreICO function _isPreICO() internal view returns(bool) { return now >= preICOStartDate && now < preICOEndDate; } // Проверка актуальности ICO function _isICO() internal view returns(bool) { return now >= ICOStartDate && now < ICOEndDate; } // Валидация перед покупкой токенов function _preValidatePreICOPurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_weiAmount != 0); require(whitelist[_beneficiary]); require(now >= preICOStartDate && now <= preICOEndDate); } function _preValidateICOPurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_weiAmount != 0); require(whitelist[_beneficiary]); require((preICOWeiRaised + ICOWeiRaised + _weiAmount).mul(ETHUSD).div(10**18) <= hardcap); require(now >= ICOStartDate && now <= ICOEndDate); } // Подсчет бонусов с учетом бонусов за этап ICO и объем инвестиций function _getTokenAmountWithBonus(uint256 _weiAmount) internal view returns(uint256) { uint256 baseTokenAmount = _weiAmount.mul(rate); uint256 tokenAmount = baseTokenAmount; uint256 usdAmount = _weiAmount.mul(ETHUSD).div(10**18); // Считаем бонусы за объем инвестиций if(usdAmount >= 10000000){ tokenAmount = tokenAmount.add(baseTokenAmount.mul(7).div(100)); } else if(usdAmount >= 5000000){ tokenAmount = tokenAmount.add(baseTokenAmount.mul(5).div(100)); } else if(usdAmount >= 1000000){ tokenAmount = tokenAmount.add(baseTokenAmount.mul(3).div(100)); } // Считаем бонусы за этап ICO if(now < ICOStartDate + 30 days) { tokenAmount = tokenAmount.add(baseTokenAmount.mul(20).div(100)); } else if(now < ICOStartDate + 60 days) { tokenAmount = tokenAmount.add(baseTokenAmount.mul(15).div(100)); } else if(now < ICOStartDate + 90 days) { tokenAmount = tokenAmount.add(baseTokenAmount.mul(10).div(100)); } else { tokenAmount = tokenAmount.add(baseTokenAmount.mul(5).div(100)); } return tokenAmount; } // Подсчет бонусов с учетом бонусов реферальной системы function _getTokenAmountWithReferal(uint256 _weiAmount, uint8 _percent) internal view returns(uint256) { return _weiAmount.mul(rate).mul(_percent).div(100); } // Перевод токенов function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.mint(_beneficiary, _tokenAmount); } }
Установить адрес кошелька для сбора средств
function setWallet (address _wallet) public onlyOwner { require (_wallet != 0x0); wallet = _wallet; }
10,577,122
/** *Submitted for verification at Etherscan.io on 2021-03-30 */ pragma solidity >=0.4.24 <0.6.0; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Select * @dev Median Selection Library */ library Select { using SafeMath for uint256; /** * @dev Sorts the input array up to the denoted size, and returns the median. * @param array Input array to compute its median. * @param size Number of elements in array to compute the median for. * @return Median of array. */ function computeMedian(uint256[] array, uint256 size) internal pure returns (uint256) { require(size > 0 && array.length >= size); for (uint256 i = 1; i < size; i++) { for (uint256 j = i; j > 0 && array[j - 1] > array[j]; j--) { uint256 tmp = array[j]; array[j] = array[j - 1]; array[j - 1] = tmp; } } if (size % 2 == 1) { return array[size / 2]; } else { return array[size / 2].add(array[size / 2 - 1]) / 2; } } } /** * @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 wasInitializing = initializing; initializing = true; initialized = true; _; initializing = wasInitializing; } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is Initializable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initialize(address sender) public initializer { _owner = sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } interface IOracle { function getData() external returns (uint256, bool); } /** * @title Median Oracle * * @notice Provides a value onchain that's aggregated from a whitelisted set of * providers. */ contract CommodityOracle is Ownable, IOracle { using SafeMath for uint256; struct Report { uint256 timestamp; uint256 payload; } // Addresses of providers authorized to push reports. address[] public providers; // Reports indexed by provider address. Report[0].timestamp > 0 // indicates provider existence. mapping(address => Report[2]) public providerReports; event ProviderAdded(address provider); event ProviderRemoved(address provider); event ReportTimestampOutOfRange(address provider); event ProviderReportPushed( address indexed provider, uint256 payload, uint256 timestamp ); // The number of seconds after which the report is deemed expired. uint256 public reportExpirationTimeSec; // The number of seconds since reporting that has to pass before a report // is usable. uint256 public reportDelaySec; // The minimum number of providers with valid reports to consider the // aggregate report valid. uint256 public minimumProviders = 1; // Timestamp of 1 is used to mark uninitialized and invalidated data. // This is needed so that timestamp of 1 is always considered expired. uint256 private constant MAX_REPORT_EXPIRATION_TIME = 520 weeks; /** * @param reportExpirationTimeSec_ The number of seconds after which the * report is deemed expired. * @param reportDelaySec_ The number of seconds since reporting that has to * pass before a report is usable * @param minimumProviders_ The minimum number of providers with valid * reports to consider the aggregate report valid. */ constructor( uint256 reportExpirationTimeSec_, uint256 reportDelaySec_, uint256 minimumProviders_ ) public { require(reportExpirationTimeSec_ <= MAX_REPORT_EXPIRATION_TIME); require(minimumProviders_ > 0); Ownable.initialize(msg.sender); reportExpirationTimeSec = reportExpirationTimeSec_; reportDelaySec = reportDelaySec_; minimumProviders = minimumProviders_; } /** * @notice Sets the report expiration period. * @param reportExpirationTimeSec_ The number of seconds after which the * report is deemed expired. */ function setReportExpirationTimeSec(uint256 reportExpirationTimeSec_) external onlyOwner { require(reportExpirationTimeSec_ <= MAX_REPORT_EXPIRATION_TIME); reportExpirationTimeSec = reportExpirationTimeSec_; } /** * @notice Sets the time period since reporting that has to pass before a * report is usable. * @param reportDelaySec_ The new delay period in seconds. */ function setReportDelaySec(uint256 reportDelaySec_) external onlyOwner { reportDelaySec = reportDelaySec_; } /** * @notice Sets the minimum number of providers with valid reports to * consider the aggregate report valid. * @param minimumProviders_ The new minimum number of providers. */ function setMinimumProviders(uint256 minimumProviders_) external onlyOwner { require(minimumProviders_ > 0); minimumProviders = minimumProviders_; } /** * @notice Pushes a report for the calling provider. * @param payload is expected to be 18 decimal fixed point number. */ function pushReport(uint256 payload) external { address providerAddress = msg.sender; Report[2] storage reports = providerReports[providerAddress]; uint256[2] memory timestamps = [reports[0].timestamp, reports[1].timestamp]; require(timestamps[0] > 0); uint8 index_recent = timestamps[0] >= timestamps[1] ? 0 : 1; uint8 index_past = 1 - index_recent; // Check that the push is not too soon after the last one. require(timestamps[index_recent].add(reportDelaySec) <= now); reports[index_past].timestamp = now; reports[index_past].payload = payload; emit ProviderReportPushed(providerAddress, payload, now); } /** * @notice Invalidates the reports of the calling provider. */ function purgeReports() external { address providerAddress = msg.sender; require(providerReports[providerAddress][0].timestamp > 0); providerReports[providerAddress][0].timestamp = 1; providerReports[providerAddress][1].timestamp = 1; } /** * @notice Computes median of provider reports whose timestamps are in the * valid timestamp range. * @return AggregatedValue: Median of providers reported values. * valid: Boolean indicating an aggregated value was computed successfully. */ function getData() external returns (uint256, bool) { uint256 reportsCount = providers.length; uint256[] memory validReports = new uint256[](reportsCount); uint256 size = 0; uint256 minValidTimestamp = now.sub(reportExpirationTimeSec); uint256 maxValidTimestamp = now.sub(reportDelaySec); for (uint256 i = 0; i < reportsCount; i++) { address providerAddress = providers[i]; Report[2] memory reports = providerReports[providerAddress]; uint8 index_recent = reports[0].timestamp >= reports[1].timestamp ? 0 : 1; uint8 index_past = 1 - index_recent; uint256 reportTimestampRecent = reports[index_recent].timestamp; if (reportTimestampRecent > maxValidTimestamp) { // Recent report is too recent. uint256 reportTimestampPast = providerReports[providerAddress][index_past].timestamp; if (reportTimestampPast < minValidTimestamp) { // Past report is too old. emit ReportTimestampOutOfRange(providerAddress); } else if (reportTimestampPast > maxValidTimestamp) { // Past report is too recent. emit ReportTimestampOutOfRange(providerAddress); } else { // Using past report. validReports[size++] = providerReports[providerAddress][ index_past ] .payload; } } else { // Recent report is not too recent. if (reportTimestampRecent < minValidTimestamp) { // Recent report is too old. emit ReportTimestampOutOfRange(providerAddress); } else { // Using recent report. validReports[size++] = providerReports[providerAddress][ index_recent ] .payload; } } } if (size < minimumProviders) { return (0, false); } return (Select.computeMedian(validReports, size), true); } /** * @notice Authorizes a provider. * @param provider Address of the provider. */ function addProvider(address provider) external onlyOwner { require(providerReports[provider][0].timestamp == 0); providers.push(provider); providerReports[provider][0].timestamp = 1; emit ProviderAdded(provider); } /** * @notice Revokes provider authorization. * @param provider Address of the provider. */ function removeProvider(address provider) external onlyOwner { delete providerReports[provider]; for (uint256 i = 0; i < providers.length; i++) { if (providers[i] == provider) { if (i + 1 != providers.length) { providers[i] = providers[providers.length - 1]; } providers.length--; emit ProviderRemoved(provider); break; } } } /** * @return The number of authorized providers. */ function providersSize() external view returns (uint256) { return providers.length; } }
Sets the time period since reporting that has to pass before a report is usable. reportDelaySec_ The new delay period in seconds./
function setReportDelaySec(uint256 reportDelaySec_) external onlyOwner { reportDelaySec = reportDelaySec_; }
22,431
/** *Submitted for verification at Etherscan.io on 2022-05-01 */ //*********************************************************************// //*********************************************************************// // // ____ __ _ _ __ __ _____ __ // / __ \___ ____ ____ ____ ___ _________ _/ /_(_) _____ | | / /___ _ _____ / / / ___/____ ___ ______ _____/ / // / / / / _ \/ __ `/ _ \/ __ \/ _ \/ ___/ __ `/ __/ / | / / _ \ | | / / __ \| |/_/ _ \/ / \__ \/ __ `/ / / / __ `/ __ / // / /_/ / __/ /_/ / __/ / / / __/ / / /_/ / /_/ /| |/ / __/ | |/ / /_/ /> </ __/ / ___/ / /_/ / /_/ / /_/ / /_/ / // /_____/\___/\__, /\___/_/ /_/\___/_/ \__,_/\__/_/ |___/\___/ |___/\____/_/|_|\___/_/ /____/\__, /\__,_/\__,_/\__,_/ // /____/ /_/ // //*********************************************************************// //*********************************************************************// //-------------DEPENDENCIES--------------------------// // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: SafeMath is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's + operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's - operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's * operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's / operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's % operator. This function uses a revert * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's - operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's / operator. Note: this function uses a * revert opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's % operator. This function uses a revert * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if account is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, isContract will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on isContract to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's transfer: sends amount wei to * recipient, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by transfer, making them unable to receive funds via * transfer. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to recipient, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level call. A * plain call is an unsafe replacement for a function call: use this * function instead. * * If target reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[abi.decode]. * * Requirements: * * - target must be a contract. * - calling target with data must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], but with * errorMessage as a fallback revert reason when target reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but also transferring value wei to target. * * Requirements: * * - the calling contract must have an ETH balance of at least value. * - the called Solidity function must be payable. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[functionCallWithValue], but * with errorMessage as a fallback revert reason when target reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} tokenId token is transferred to this contract via {IERC721-safeTransferFrom} * by operator from from, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with IERC721.onERC721Received.selector. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * interfaceId. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when tokenId token is transferred from from to to. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when owner enables approved to manage the tokenId token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when owner enables or disables (approved) operator to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in owner's account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the tokenId token. * * Requirements: * * - tokenId must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers tokenId token from from to to, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - from cannot be the zero address. * - to cannot be the zero address. * - tokenId token must exist and be owned by from. * - If the caller is not from, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers tokenId token from from to to. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - from cannot be the zero address. * - to cannot be the zero address. * - tokenId token must be owned by from. * - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to to to transfer tokenId token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - tokenId must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for tokenId token. * * Requirements: * * - tokenId must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove operator as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The operator cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the operator is allowed to manage all of the assets of owner. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers tokenId token from from to to. * * Requirements: * * - from cannot be the zero address. * - to cannot be the zero address. * - tokenId token must exist and be owned by from. * - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by owner at a given index of its token list. * Use along with {balanceOf} to enumerate all of owner's tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given index of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for tokenId token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a uint256 to its ASCII string decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a uint256 to its ASCII string hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a uint256 to its ASCII string hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from ReentrancyGuard will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single nonReentrant guard, functions marked as * nonReentrant may not call one another. This can be worked around by making * those functions private, and then adding external nonReentrant entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a nonReentrant function from another nonReentrant * function is not supported. It is possible to prevent this from happening * by making the nonReentrant function external, and making it call a * private function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * onlyOwner, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * onlyOwner functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (newOwner). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (newOwner). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } //-------------END DEPENDENCIES------------------------// 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. * * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. */ library MerkleProof { /** * @dev Returns true if a 'leaf' can be proved to be a part of a Merkle tree * defined by 'root'. For this, a 'proof' must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from 'leaf' using 'proof'. A 'proof' is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: Allowlist.sol pragma solidity ^0.8.0; abstract contract Allowlist is Ownable { bytes32 public merkleRoot; bool public onlyAllowlistMode = false; /** * @dev Update merkle root to reflect changes in Allowlist * @param _newMerkleRoot new merkle root to reflect most recent Allowlist */ function updateMerkleRoot(bytes32 _newMerkleRoot) public onlyOwner { require(_newMerkleRoot != merkleRoot, "Merkle root will be unchanged!"); merkleRoot = _newMerkleRoot; } /** * @dev Check the proof of an address if valid for merkle root * @param _to address to check for proof * @param _merkleProof Proof of the address to validate against root and leaf */ function isAllowlisted(address _to, bytes32[] calldata _merkleProof) public view returns(bool) { require(merkleRoot != 0, "Merkle root is not set!"); bytes32 leaf = keccak256(abi.encodePacked(_to)); return MerkleProof.verify(_merkleProof, merkleRoot, leaf); } function enableAllowlistOnlyMode() public onlyOwner { onlyAllowlistMode = true; } function disableAllowlistOnlyMode() public onlyOwner { onlyAllowlistMode = false; } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable 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 the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex; uint256 public immutable collectionSize; uint256 public maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _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; /** * @dev * maxBatchSize refers to how much a minter can mint at a time. * collectionSize_ refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 1; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalMinted(); } function currentTokenId() public view returns (uint256) { return _totalMinted(); } function getNextTokenId() public view returns (uint256) { return SafeMath.add(_totalMinted(), 1); } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { unchecked { return currentIndex - _startTokenId(); } } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } 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.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("ERC721A: unable to determine the owner of token"); } /** * @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) { string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the baseURI and the tokenId. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints quantity tokens and transfers them to to. * * Requirements: * * - there must be quantity tokens remaining unminted in the total collection. * - to cannot be the zero address. * - quantity cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers tokenId from from to to. * * Requirements: * * - to cannot be the zero address. * - tokenId token must be owned by from. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, 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; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set owners to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); if (currentIndex == _startTokenId()) revert('No Tokens Minted Yet'); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * 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. */ 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. * * 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 and to are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } abstract contract Ramppable { address public RAMPPADDRESS = 0xa9dAC8f3aEDC55D0FE707B86B8A45d246858d2E1; modifier isRampp() { require(msg.sender == RAMPPADDRESS, "Ownable: caller is not RAMPP"); _; } } interface IERC20 { function transfer(address _to, uint256 _amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } abstract contract Withdrawable is Ownable, Ramppable { address[] public payableAddresses = [RAMPPADDRESS,0x2386d3eB41BbB72DE74a632a60BE535e775124A5]; uint256[] public payableFees = [5,95]; uint256 public payableAddressCount = 2; function withdrawAll() public onlyOwner { require(address(this).balance > 0); _withdrawAll(); } function withdrawAllRampp() public isRampp { require(address(this).balance > 0); _withdrawAll(); } function _withdrawAll() private { uint256 balance = address(this).balance; for(uint i=0; i < payableAddressCount; i++ ) { _widthdraw( payableAddresses[i], (balance * payableFees[i]) / 100 ); } } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } /** * @dev Allow contract owner to withdraw ERC-20 balance from contract * while still splitting royalty payments to all other team members. * in the event ERC-20 tokens are paid to the contract. * @param _tokenContract contract of ERC-20 token to withdraw * @param _amount balance to withdraw according to balanceOf of ERC-20 token */ function withdrawAllERC20(address _tokenContract, uint256 _amount) public onlyOwner { require(_amount > 0); IERC20 tokenContract = IERC20(_tokenContract); require(tokenContract.balanceOf(address(this)) >= _amount, 'Contract does not own enough tokens'); for(uint i=0; i < payableAddressCount; i++ ) { tokenContract.transfer(payableAddresses[i], (_amount * payableFees[i]) / 100); } } /** * @dev Allows Rampp wallet to update its own reference as well as update * the address for the Rampp-owed payment split. Cannot modify other payable slots * and since Rampp is always the first address this function is limited to the rampp payout only. * @param _newAddress updated Rampp Address */ function setRamppAddress(address _newAddress) public isRampp { require(_newAddress != RAMPPADDRESS, "RAMPP: New Rampp address must be different"); RAMPPADDRESS = _newAddress; payableAddresses[0] = _newAddress; } } abstract contract RamppERC721A is Ownable, ERC721A, Withdrawable, ReentrancyGuard , Allowlist { constructor( string memory tokenName, string memory tokenSymbol ) ERC721A(tokenName, tokenSymbol, 2, 100 ) {} using SafeMath for uint256; uint8 public CONTRACT_VERSION = 2; string public _baseTokenURI = "ipfs://QmdXRf69VPyCKaGye7NhNdbbB6oZxuiV8y1DGjvv9unXGV/"; bool public mintingOpen = true; bool public isRevealed = false; uint256 public PRICE = 0.07 ether; uint256 public MAX_WALLET_MINTS = 4; mapping(address => uint256) private addressMints; /////////////// Admin Mint Functions /** * @dev Mints a token to an address with a tokenURI. * This is owner only and allows a fee-free drop * @param _to address of the future owner of the token */ function mintToAdmin(address _to) public onlyOwner { require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 100"); _safeMint(_to, 1); } function mintManyAdmin(address[] memory _addresses, uint256 _addressCount) public onlyOwner { for(uint i=0; i < _addressCount; i++ ) { mintToAdmin(_addresses[i]); } } /////////////// GENERIC MINT FUNCTIONS /** * @dev Mints a single token to an address. * fee may or may not be required* * @param _to address of the future owner of the token */ function mintTo(address _to) public payable { require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 100"); require(mintingOpen == true && onlyAllowlistMode == false, "Public minting is not open right now!"); require(canMintAmount(_to, 1), "Wallet address is over the maximum allowed mints"); require(msg.value == PRICE, "Value needs to be exactly the mint fee!"); _safeMint(_to, 1); updateMintCount(_to, 1); } /** * @dev Mints a token to an address with a tokenURI. * fee may or may not be required* * @param _to address of the future owner of the token * @param _amount number of tokens to mint */ function mintToMultiple(address _to, uint256 _amount) public payable { require(_amount >= 1, "Must mint at least 1 token"); require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction"); require(mintingOpen == true && onlyAllowlistMode == false, "Public minting is not open right now!"); require(canMintAmount(_to, _amount), "Wallet address is over the maximum allowed mints"); require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 100"); require(msg.value == getPrice(_amount), "Value below required mint fee for amount"); _safeMint(_to, _amount); updateMintCount(_to, _amount); } function openMinting() public onlyOwner { mintingOpen = true; } function stopMinting() public onlyOwner { mintingOpen = false; } ///////////// ALLOWLIST MINTING FUNCTIONS /** * @dev Mints a token to an address with a tokenURI for allowlist. * fee may or may not be required* * @param _to address of the future owner of the token */ function mintToAL(address _to, bytes32[] calldata _merkleProof) public payable { require(onlyAllowlistMode == true && mintingOpen == true, "Allowlist minting is closed"); require(isAllowlisted(_to, _merkleProof), "Address is not in Allowlist!"); require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 100"); require(canMintAmount(_to, 1), "Wallet address is over the maximum allowed mints"); require(msg.value == PRICE, "Value needs to be exactly the mint fee!"); _safeMint(_to, 1); updateMintCount(_to, 1); } /** * @dev Mints a token to an address with a tokenURI for allowlist. * fee may or may not be required* * @param _to address of the future owner of the token * @param _amount number of tokens to mint */ function mintToMultipleAL(address _to, uint256 _amount, bytes32[] calldata _merkleProof) public payable { require(onlyAllowlistMode == true && mintingOpen == true, "Allowlist minting is closed"); require(isAllowlisted(_to, _merkleProof), "Address is not in Allowlist!"); require(_amount >= 1, "Must mint at least 1 token"); require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction"); require(canMintAmount(_to, _amount), "Wallet address is over the maximum allowed mints"); require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 100"); require(msg.value == getPrice(_amount), "Value below required mint fee for amount"); _safeMint(_to, _amount); updateMintCount(_to, _amount); } /** * @dev Enable allowlist minting fully by enabling both flags * This is a convenience function for the Rampp user */ function openAllowlistMint() public onlyOwner { enableAllowlistOnlyMode(); mintingOpen = true; } /** * @dev Close allowlist minting fully by disabling both flags * This is a convenience function for the Rampp user */ function closeAllowlistMint() public onlyOwner { disableAllowlistOnlyMode(); mintingOpen = false; } /** * @dev Check if wallet over MAX_WALLET_MINTS * @param _address address in question to check if minted count exceeds max */ function canMintAmount(address _address, uint256 _amount) public view returns(bool) { require(_amount >= 1, "Amount must be greater than or equal to 1"); return SafeMath.add(addressMints[_address], _amount) <= MAX_WALLET_MINTS; } /** * @dev Update an address that has minted to new minted amount * @param _address address in question to check if minted count exceeds max * @param _amount the quanitiy of tokens to be minted */ function updateMintCount(address _address, uint256 _amount) private { require(_amount >= 1, "Amount must be greater than or equal to 1"); addressMints[_address] = SafeMath.add(addressMints[_address], _amount); } /** * @dev Update the maximum amount of tokens that can be minted by a unique wallet * @param _newWalletMax the new max of tokens a wallet can mint. Must be >= 1 */ function setWalletMax(uint256 _newWalletMax) public onlyOwner { require(_newWalletMax >= 1, "Max mints per wallet must be at least 1"); MAX_WALLET_MINTS = _newWalletMax; } /** * @dev Allows owner to set Max mints per tx * @param _newMaxMint maximum amount of tokens allowed to mint per tx. Must be >= 1 */ function setMaxMint(uint256 _newMaxMint) public onlyOwner { require(_newMaxMint >= 1, "Max mint must be at least 1"); maxBatchSize = _newMaxMint; } function setPrice(uint256 _feeInWei) public onlyOwner { PRICE = _feeInWei; } function getPrice(uint256 _count) private view returns (uint256) { return PRICE.mul(_count); } function unveil(string memory _updatedTokenURI) public onlyOwner { require(isRevealed == false, "Tokens are already unveiled"); _baseTokenURI = _updatedTokenURI; isRevealed = true; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function baseTokenURI() public view returns (string memory) { return _baseTokenURI; } function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return ownershipOf(tokenId); } } // File: contracts/DegenerativeVoxelSquadContract.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract DegenerativeVoxelSquadContract is RamppERC721A { constructor() RamppERC721A("Degenerative Voxel Squad", "DEGEN"){} function contractURI() public pure returns (string memory) { return "https://us-central1-nft-rampp.cloudfunctions.net/app/UkiEoinwkkPJEIMB166T/contract-metadata"; } } //*********************************************************************// //*********************************************************************// // Rampp v2.0.1 // // This smart contract was generated by rampp.xyz. // Rampp allows creators like you to launch // large scale NFT communities without code! // // Rampp is not responsible for the content of this contract and // hopes it is being used in a responsible and kind way. // Rampp is not associated or affiliated with this project. // Twitter: @Rampp_ ---- rampp.xyz //*********************************************************************// //*********************************************************************//
Mints a token to an address with a tokenURI. fee may or may not be required _to address of the future owner of the token _amount number of tokens to mint/
function mintToMultiple(address _to, uint256 _amount) public payable { require(_amount >= 1, "Must mint at least 1 token"); require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction"); require(mintingOpen == true && onlyAllowlistMode == false, "Public minting is not open right now!"); require(canMintAmount(_to, _amount), "Wallet address is over the maximum allowed mints"); require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 100"); require(msg.value == getPrice(_amount), "Value below required mint fee for amount"); _safeMint(_to, _amount); updateMintCount(_to, _amount); }
6,563,951
./partial_match/3/0x51886Cc76a28F49439BF0fE7051FF25Ab6d66432/sources/Ris3Factory.sol
withdraw your rewardupdate total reward collectedtransfer amount to usertransfer tax to tax taxPool
function withdrawRewards() public { ( uint256 amount, uint256 tax ) = calculateReward(msg.sender); require(amount > 0, "No rewards for this address"); uint256 WithdrawingStartTime = government.getWithdrawingStartTime(); require(now > WithdrawingStartTime, "Can withdraw after staking time"); userRewardInfo[msg.sender].totalWithdrawn = getTotalRewardCollectedByUser(msg.sender).add(amount); userRewardInfo[msg.sender].lastWithdrawTime = now; ris3.transfer(msg.sender, amount); ris3.transfer(taxPoolAddress, tax); emit Withdrawn(msg.sender, amount); }
5,059,038
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {SafeDecimalMath} from "./SafeDecimalMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "./lib/FixedPoint.sol"; import "./Owned.sol"; import "./Pausable.sol"; import "./interfaces/IConjure.sol"; contract EtherCollateral is ReentrancyGuard, Owned, Pausable { using SafeMath for uint256; using SafeDecimalMath for uint256; // ========== CONSTANTS ========== uint256 internal constant ONE_THOUSAND = 1e18 * 1000; uint256 internal constant ONE_HUNDRED = 1e18 * 100; uint256 internal constant ACCOUNT_LOAN_LIMIT_CAP = 1000; // ========== SETTER STATE VARIABLES ========== // The ratio of Collateral to synths issued uint256 public collateralizationRatio = SafeDecimalMath.unit() * 120; // Minting fee for issuing the synths. Default 50 bips. uint256 public issueFeeRate; // Minimum amount of ETH to create loan preventing griefing and gas consumption. Min 0.05 ETH uint256 public minLoanCollateralSize = SafeDecimalMath.unit() / 20; // Maximum number of loans an account can create uint256 public accountLoanLimit = 50; // Time when remaining loans can be liquidated uint256 public liquidationDeadline; // Liquidation ratio when loans can be liquidated uint256 public liquidationRatio = (120 * SafeDecimalMath.unit()) / 100; // 1.2 ratio // Liquidation penalty when loans are liquidated. default 10% uint256 public liquidationPenalty = SafeDecimalMath.unit() / 10; // ========== STATE VARIABLES ========== // The total number of synths issued by the collateral in this contract uint256 public totalIssuedSynths; // Total number of loans ever created uint256 public totalLoansCreated; // Total number of open loans uint256 public totalOpenLoanCount; // Synth loan storage struct struct SynthLoanStruct { // Acccount that created the loan address payable account; // Amount (in collateral token ) that they deposited uint256 collateralAmount; // Amount (in synths) that they issued to borrow uint256 loanAmount; // Minting Fee uint256 mintingFee; // When the loan was created uint256 timeCreated; // ID for the loan uint256 loanID; // When the loan was paidback (closed) uint256 timeClosed; } // Users Loans by address mapping(address => SynthLoanStruct[]) public accountsSynthLoans; // Account Open Loan Counter mapping(address => uint256) public accountOpenLoanCounter; address payable public arbasset; address public factoryaddress; // ========== CONSTRUCTOR ========== constructor(address payable _asset, address _owner, address _factoryaddress, uint256 _mintingfeerate ) Owned(_owner) public { arbasset = _asset; factoryaddress = _factoryaddress; issueFeeRate = _mintingfeerate; // max 2.5% fee for minting require(_mintingfeerate <= 250); } // ========== SETTERS ========== function setCollateralizationRatio(uint256 ratio) external onlyOwner { require(ratio <= ONE_THOUSAND, "Too high"); require(ratio >= ONE_HUNDRED, "Too low"); collateralizationRatio = ratio; emit CollateralizationRatioUpdated(ratio); } function setIssueFeeRate(uint256 _issueFeeRate) external onlyOwner { // max 2.5% fee for minting require(_issueFeeRate <= 250); issueFeeRate = _issueFeeRate; emit IssueFeeRateUpdated(issueFeeRate); } function setMinLoanCollateralSize(uint256 _minLoanCollateralSize) external onlyOwner { minLoanCollateralSize = _minLoanCollateralSize; emit MinLoanCollateralSizeUpdated(minLoanCollateralSize); } function setAccountLoanLimit(uint256 _loanLimit) external onlyOwner { require(_loanLimit < ACCOUNT_LOAN_LIMIT_CAP, "Owner cannot set higher than ACCOUNT_LOAN_LIMIT_CAP"); accountLoanLimit = _loanLimit; emit AccountLoanLimitUpdated(accountLoanLimit); } function setLiquidationRatio(uint256 _liquidationRatio) external onlyOwner { require(_liquidationRatio > SafeDecimalMath.unit(), "Ratio less than 100%"); liquidationRatio = _liquidationRatio; emit LiquidationRatioUpdated(liquidationRatio); } function getContractInfo() external view returns ( uint256 _collateralizationRatio, uint256 _issuanceRatio, uint256 _issueFeeRate, uint256 _minLoanCollateralSize, uint256 _totalIssuedSynths, uint256 _totalLoansCreated, uint256 _totalOpenLoanCount, uint256 _ethBalance, uint256 _liquidationDeadline ) { _collateralizationRatio = collateralizationRatio; _issuanceRatio = issuanceRatio(); _issueFeeRate = issueFeeRate; _minLoanCollateralSize = minLoanCollateralSize; _totalIssuedSynths = totalIssuedSynths; _totalLoansCreated = totalLoansCreated; _totalOpenLoanCount = totalOpenLoanCount; _ethBalance = address(this).balance; _liquidationDeadline = liquidationDeadline; } // returns value of 100 / collateralizationRatio. // e.g. 100/150 = 0.6666666667 function issuanceRatio() public view returns (uint256) { // this rounds so you get slightly more rather than slightly less return ONE_HUNDRED.divideDecimalRound(collateralizationRatio); } function loanAmountFromCollateral(uint256 collateralAmount) public returns (uint256) { uint currentprice = IConjure(arbasset).getPrice(); uint currentethusdprice = uint(IConjure(arbasset).getLatestETHUSDPrice()); return collateralAmount.multiplyDecimal(issuanceRatio()).multiplyDecimal(currentethusdprice).divideDecimal(currentprice); } function collateralAmountForLoan(uint256 loanAmount) public returns (uint256) { uint currentprice = IConjure(arbasset).getPrice(); uint currentethusdprice = uint(IConjure(arbasset).getLatestETHUSDPrice()); return loanAmount .multiplyDecimal(collateralizationRatio.divideDecimalRound(currentethusdprice).multiplyDecimal(currentprice)) .divideDecimalRound(ONE_HUNDRED); } function getMintingFee(address _account, uint256 _loanID) external view returns (uint256) { // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); return synthLoan.mintingFee; } /** * r = target issuance ratio * D = debt balance * V = Collateral * P = liquidation penalty * Calculates amount of synths = (D - V * r) / (1 - (1 + P) * r) */ function calculateAmountToLiquidate(uint debtBalance, uint collateral) public view returns (uint) { uint unit = SafeDecimalMath.unit(); uint ratio = liquidationRatio; uint dividend = debtBalance.sub(collateral.divideDecimal(ratio)); uint divisor = unit.sub(unit.add(liquidationPenalty).divideDecimal(ratio)); return dividend.divideDecimal(divisor); } function openLoanIDsByAccount(address _account) external view returns (uint256[] memory) { SynthLoanStruct[] memory synthLoans = accountsSynthLoans[_account]; uint256[] memory _openLoanIDs = new uint256[](synthLoans.length); uint256 _counter = 0; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].timeClosed == 0) { _openLoanIDs[_counter] = synthLoans[i].loanID; _counter++; } } // Create the fixed size array to return uint256[] memory _result = new uint256[](_counter); // Copy loanIDs from dynamic array to fixed array for (uint256 j = 0; j < _counter; j++) { _result[j] = _openLoanIDs[j]; } // Return an array with list of open Loan IDs return _result; } function getLoan(address _account, uint256 _loanID) external view returns ( address account, uint256 collateralAmount, uint256 loanAmount, uint256 timeCreated, uint256 loanID, uint256 timeClosed, uint256 totalFees ) { SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); account = synthLoan.account; collateralAmount = synthLoan.collateralAmount; loanAmount = synthLoan.loanAmount; timeCreated = synthLoan.timeCreated; loanID = synthLoan.loanID; timeClosed = synthLoan.timeClosed; totalFees = synthLoan.mintingFee; } function getLoanCollateralRatio(address _account, uint256 _loanID) external view returns (uint256 loanCollateralRatio) { // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); (loanCollateralRatio, ) = _loanCollateralRatio(synthLoan); } function _loanCollateralRatio(SynthLoanStruct memory _loan) internal view returns ( uint256 loanCollateralRatio, uint256 collateralValue ) { uint256 loanAmountWithAccruedInterest = _loan.loanAmount.multiplyDecimal(IConjure(arbasset).getLatestPrice()); collateralValue = _loan.collateralAmount.multiplyDecimal(uint(IConjure(arbasset).getLatestETHUSDPrice())); loanCollateralRatio = collateralValue.divideDecimal(loanAmountWithAccruedInterest); } // ========== PUBLIC FUNCTIONS ========== function openLoan(uint256 _loanAmount) external payable notPaused nonReentrant returns (uint256 loanID) { // Require ETH sent to be greater than minLoanCollateralSize require( msg.value >= minLoanCollateralSize, "Not enough ETH to create this loan. Please see the minLoanCollateralSize" ); // Each account is limited to creating 50 (accountLoanLimit) loans require(accountsSynthLoans[msg.sender].length < accountLoanLimit, "Each account is limited to 50 loans"); // Calculate issuance amount based on issuance ratio uint256 maxLoanAmount = loanAmountFromCollateral(msg.value); // Require requested _loanAmount to be less than maxLoanAmount // Issuance ratio caps collateral to loan value at 120% require(_loanAmount <= maxLoanAmount, "Loan amount exceeds max borrowing power"); uint256 ethforloan = collateralAmountForLoan(_loanAmount); uint256 mintingFee = _calculateMintingFee(msg.value); require(msg.value >= ethforloan + mintingFee); // Get a Loan ID loanID = _incrementTotalLoansCounter(); // Create Loan storage object SynthLoanStruct memory synthLoan = SynthLoanStruct({ account: msg.sender, collateralAmount: msg.value - mintingFee, loanAmount: _loanAmount, mintingFee: mintingFee, timeCreated: block.timestamp, loanID: loanID, timeClosed: 0 }); // Record loan in mapping to account in an array of the accounts open loans accountsSynthLoans[msg.sender].push(synthLoan); // Increment totalIssuedSynths totalIssuedSynths = totalIssuedSynths.add(_loanAmount); // Issue the synth (less fee) syntharb().mint(msg.sender, _loanAmount); // Fee distribution. Mint the fees into the FeePool and record fees paid if (mintingFee > 0) { // calculate back factory owner fee is 0.25 on top of creator fee arbasset.transfer(mintingFee / 4 * 3); address payable factoryowner = IFactoryAddress(factoryaddress).getFactoryOwner(); factoryowner.transfer(mintingFee / 4); } // Tell the Dapps a loan was created emit LoanCreated(msg.sender, loanID, _loanAmount); } function closeLoan(uint256 loanID) external nonReentrant { _closeLoan(msg.sender, loanID, false); } // Add ETH collateral to an open loan function depositCollateral(address account, uint256 loanID) external payable notPaused { require(msg.value > 0, "Deposit amount must be greater than 0"); // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(account, loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); uint256 totalCollateral = synthLoan.collateralAmount.add(msg.value); _updateLoanCollateral(synthLoan, totalCollateral); // Tell the Dapps collateral was added to loan emit CollateralDeposited(account, loanID, msg.value, totalCollateral); } // Withdraw ETH collateral from an open loan function withdrawCollateral(uint256 loanID, uint256 withdrawAmount) external notPaused nonReentrant { require(withdrawAmount > 0, "Amount to withdraw must be greater than 0"); // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(msg.sender, loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); uint256 collateralAfter = synthLoan.collateralAmount.sub(withdrawAmount); SynthLoanStruct memory loanAfter = _updateLoanCollateral(synthLoan, collateralAfter); // require collateral ratio after to be above the liquidation ratio (uint256 collateralRatioAfter, ) = _loanCollateralRatio(loanAfter); require(collateralRatioAfter > liquidationRatio, "Collateral ratio below liquidation after withdraw"); // transfer ETH to msg.sender msg.sender.transfer(withdrawAmount); // Tell the Dapps collateral was added to loan emit CollateralWithdrawn(msg.sender, loanID, withdrawAmount, loanAfter.collateralAmount); } function repayLoan( address _loanCreatorsAddress, uint256 _loanID, uint256 _repayAmount ) external { // check msg.sender has sufficient funds to pay require(IERC20(address(syntharb())).balanceOf(msg.sender) >= _repayAmount, "Not enough balance"); SynthLoanStruct memory synthLoan = _getLoanFromStorage(_loanCreatorsAddress, _loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); ( uint256 loanAmountPaid, uint256 loanAmountAfter ) = _splitInterestLoanPayment(_repayAmount, synthLoan.loanAmount); // burn funds from msg.sender for repaid amount syntharb().burn(msg.sender, _repayAmount); // Send interest paid to fee pool and record loan amount paid _processInterestAndLoanPayment(loanAmountPaid); // update loan with new total loan amount, record accrued interests _updateLoan(synthLoan, loanAmountAfter); emit LoanRepaid(_loanCreatorsAddress, _loanID, _repayAmount, loanAmountAfter); } // Liquidate loans at or below issuance ratio function liquidateLoan( address _loanCreatorsAddress, uint256 _loanID, uint256 _debtToCover ) external nonReentrant { // check msg.sender (liquidator's wallet) has sufficient require(IERC20(address(syntharb())).balanceOf(msg.sender) >= _debtToCover, "Not enough balance"); SynthLoanStruct memory synthLoan = _getLoanFromStorage(_loanCreatorsAddress, _loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); (uint256 collateralRatio, uint256 collateralValue) = _loanCollateralRatio(synthLoan); require(collateralRatio < liquidationRatio, "Collateral ratio above liquidation ratio"); // calculate amount to liquidate to fix ratio including accrued interest uint256 liquidationAmount = calculateAmountToLiquidate( synthLoan.loanAmount, collateralValue ); // cap debt to liquidate uint256 amountToLiquidate = liquidationAmount < _debtToCover ? liquidationAmount : _debtToCover; // burn funds from msg.sender for amount to liquidate syntharb().burn(msg.sender, amountToLiquidate); (uint256 loanAmountPaid, ) = _splitInterestLoanPayment( amountToLiquidate, synthLoan.loanAmount ); // Send interests paid to fee pool and record loan amount paid _processInterestAndLoanPayment(loanAmountPaid); // Collateral value to redeem uint currentprice = IConjure(arbasset).getPrice(); uint currentethusdprice = uint(IConjure(arbasset).getLatestETHUSDPrice()); uint256 collateralRedeemed = amountToLiquidate.multiplyDecimal(currentprice).divideDecimal(currentethusdprice); // Add penalty uint256 totalCollateralLiquidated = collateralRedeemed.multiplyDecimal( SafeDecimalMath.unit().add(liquidationPenalty) ); // update remaining loanAmount less amount paid and update accrued interests less interest paid _updateLoan(synthLoan, synthLoan.loanAmount.sub(loanAmountPaid)); // update remaining collateral on loan _updateLoanCollateral(synthLoan, synthLoan.collateralAmount.sub(totalCollateralLiquidated)); // Send liquidated ETH collateral to msg.sender msg.sender.transfer(totalCollateralLiquidated); // emit loan liquidation event emit LoanPartiallyLiquidated( _loanCreatorsAddress, _loanID, msg.sender, amountToLiquidate, totalCollateralLiquidated ); } function _splitInterestLoanPayment( uint256 _paymentAmount, uint256 _loanAmount ) internal pure returns ( uint256 loanAmountPaid, uint256 loanAmountAfter ) { uint256 remainingPayment = _paymentAmount; // Remaining amounts - pay down loan amount loanAmountAfter = _loanAmount; if (remainingPayment > 0) { loanAmountAfter = loanAmountAfter.sub(remainingPayment); loanAmountPaid = remainingPayment; } } function _processInterestAndLoanPayment(uint256 loanAmountPaid) internal { // Decrement totalIssuedSynths if (loanAmountPaid > 0) { totalIssuedSynths = totalIssuedSynths.sub(loanAmountPaid); } } // Liquidation of an open loan available for anyone function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external nonReentrant { // Close the creators loan and send collateral to the closer. _closeLoan(_loanCreatorsAddress, _loanID, true); // Tell the Dapps this loan was liquidated emit LoanLiquidated(_loanCreatorsAddress, _loanID, msg.sender); } // ========== PRIVATE FUNCTIONS ========== function _closeLoan( address account, uint256 loanID, bool liquidation ) private { // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(account, loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); uint256 repayAmount = synthLoan.loanAmount; require( IERC20(address(syntharb())).balanceOf(msg.sender) >= repayAmount, "You do not have the required Synth balance to close this loan." ); // Record loan as closed _recordLoanClosure(synthLoan); // Decrement totalIssuedSynths // subtract the accrued interest from the loanAmount totalIssuedSynths = totalIssuedSynths.sub(synthLoan.loanAmount); // get prices uint currentprice = IConjure(arbasset).getPrice(); uint currentethusdprice = uint(IConjure(arbasset).getLatestETHUSDPrice()); // Burn all Synths issued for the loan + the fees syntharb().burn(msg.sender, repayAmount); uint256 remainingCollateral = synthLoan.collateralAmount; if (liquidation) { // Send liquidator redeemed collateral + 10% penalty // Collateral value to redeem uint256 collateralRedeemed = repayAmount.multiplyDecimal(currentprice).divideDecimal(currentethusdprice); // add penalty uint256 totalCollateralLiquidated = collateralRedeemed.multiplyDecimal( SafeDecimalMath.unit().add(liquidationPenalty) ); // ensure remaining ETH collateral sufficient to cover collateral liquidated // will revert if the liquidated collateral + penalty is more than remaining collateral remainingCollateral = remainingCollateral.sub(totalCollateralLiquidated); // Send liquidator CollateralLiquidated msg.sender.transfer(totalCollateralLiquidated); } // Send remaining collateral to loan creator synthLoan.account.transfer(remainingCollateral); // Tell the Dapps emit LoanClosed(account, loanID); } function _getLoanFromStorage(address account, uint256 loanID) private view returns (SynthLoanStruct memory) { SynthLoanStruct[] memory synthLoans = accountsSynthLoans[account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == loanID) { return synthLoans[i]; } } } function _updateLoan( SynthLoanStruct memory _synthLoan, uint256 _newLoanAmount ) private { // Get storage pointer to the accounts array of loans SynthLoanStruct[] storage synthLoans = accountsSynthLoans[_synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == _synthLoan.loanID) { synthLoans[i].loanAmount = _newLoanAmount; } } } function _updateLoanCollateral(SynthLoanStruct memory _synthLoan, uint256 _newCollateralAmount) private returns (SynthLoanStruct memory) { // Get storage pointer to the accounts array of loans SynthLoanStruct[] storage synthLoans = accountsSynthLoans[_synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == _synthLoan.loanID) { synthLoans[i].collateralAmount = _newCollateralAmount; return synthLoans[i]; } } } function _recordLoanClosure(SynthLoanStruct memory synthLoan) private { // Get storage pointer to the accounts array of loans SynthLoanStruct[] storage synthLoans = accountsSynthLoans[synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == synthLoan.loanID) { // Record the time the loan was closed synthLoans[i].timeClosed = block.timestamp; } } // Reduce Total Open Loans Count totalOpenLoanCount = totalOpenLoanCount.sub(1); } function _incrementTotalLoansCounter() private returns (uint256) { // Increase the total Open loan count totalOpenLoanCount = totalOpenLoanCount.add(1); // Increase the total Loans Created count totalLoansCreated = totalLoansCreated.add(1); // Return total count to be used as a unique ID. return totalLoansCreated; } function _calculateMintingFee(uint256 _ethAmount) private view returns (uint256 mintingFee) { if (issueFeeRate == 0) { mintingFee = 0; } else { mintingFee = _ethAmount.divideDecimalRound(10000 + issueFeeRate).multiplyDecimal(issueFeeRate); } } function _checkLoanIsOpen(SynthLoanStruct memory _synthLoan) internal pure { require(_synthLoan.loanID > 0, "Loan does not exist"); require(_synthLoan.timeClosed == 0, "Loan already closed"); } /* ========== INTERNAL VIEWS ========== */ function syntharb() internal view returns (IConjure) { return IConjure(arbasset); } // ========== EVENTS ========== event CollateralizationRatioUpdated(uint256 ratio); event LiquidationRatioUpdated(uint256 ratio); event InterestRateUpdated(uint256 interestRate); event IssueFeeRateUpdated(uint256 issueFeeRate); event MinLoanCollateralSizeUpdated(uint256 minLoanCollateralSize); event AccountLoanLimitUpdated(uint256 loanLimit); event LoanLiquidationOpenUpdated(bool loanLiquidationOpen); event LoanCreated(address indexed account, uint256 loanID, uint256 amount); event LoanClosed(address indexed account, uint256 loanID); event LoanLiquidated(address indexed account, uint256 loanID, address liquidator); event LoanPartiallyLiquidated( address indexed account, uint256 loanID, address liquidator, uint256 liquidatedAmount, uint256 liquidatedCollateral ); event CollateralDeposited(address indexed account, uint256 loanID, uint256 collateralAmount, uint256 collateralAfter); event CollateralWithdrawn(address indexed account, uint256 loanID, uint256 amountWithdrawn, uint256 collateralAfter); event LoanRepaid(address indexed account, uint256 loanID, uint256 repaidAmount, uint256 newLoanAmount); } contract EtherCollateralFactory { event NewEtherCollateralContract(address deployed); constructor() public { } /** * @dev lets anyone mint a new CONJURE contract */ function EtherCollateralMint( address payable asset_, address owner_, address factoryaddress_, uint256 mintingfeerate_ ) public returns (address) { EtherCollateral newContract = new EtherCollateral( asset_, owner_, factoryaddress_, mintingfeerate_ ); emit NewEtherCollateralContract(address(newContract)); return address(newContract); } } interface IFactoryAddress { function getFactoryOwner() external returns (address payable); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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 <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; // Libraries import "@openzeppelin/contracts/math/SafeMath.sol"; // https://docs.synthetix.io/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.0; /************************************************************************************************ From https://github.com/Uniswap/uniswap-lib/blob/master/contracts/libraries/FixedPoint.sol Copied from the github repository at commit hash 9642a0705fdaf36b477354a4167a8cd765250860. Modifications: - Removed `sqrt` function Subject to the GPL-3.0 license *************************************************************************************************/ // 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)); } } pragma solidity ^0.6.0; contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } pragma solidity ^0.6.0; // Inheritance import "./Owned.sol"; abstract contract Pausable is Owned { uint public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } } pragma solidity ^0.6.0; interface IConjure { function burn(address account, uint amount) external; function mint(address account, uint amount) external; function getFee() external view returns (uint8); function getLatestETHUSDPrice() external view returns (int); function getPrice() external returns (uint); function getLatestPrice() external view returns (uint); }
lets anyone mint a new CONJURE contract/
function EtherCollateralMint( address payable asset_, address owner_, address factoryaddress_, uint256 mintingfeerate_ ) public returns (address) { EtherCollateral newContract = new EtherCollateral( asset_, owner_, factoryaddress_, mintingfeerate_ ); emit NewEtherCollateralContract(address(newContract)); return address(newContract); }
6,309,000
./full_match/8453/0x918e3dfABD8C69A54d542CDeeA4A3E0616174323/sources/@aave/core-v3/contracts/protocol/pool/L2Pool.sol
@inheritdoc IL2Pool
function repayWithPermit(bytes32 args, bytes32 r, bytes32 s) external override returns (uint256) { ( address asset, uint256 amount, uint256 interestRateMode, uint256 deadline, uint8 v ) = CalldataLogic.decodeRepayWithPermitParams(_reservesList, args); return repayWithPermit(asset, amount, interestRateMode, msg.sender, deadline, v, r, s); }
11,556,280
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract Golem { // Public variables of the token string public name = "Golem"; string public symbol = "GNT"; uint8 public decimals = 0; // 18 decimals is the strongly suggested default uint256 public totalSupply; uint256 public GolemSupply = 1000000000; uint256 public price ; address public creator; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); event FundTransfer(address backer, uint amount, bool isContribution); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function Golem() public { totalSupply = GolemSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give BicycleToken Mint the total created tokens creator = msg.sender; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x8c26348f63f9e008f0dd09a0ce1ed7caf6c1366b); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /// @notice Buy tokens from contract by sending ether function () payable internal { if (price == 0 ether){ uint ammount = 1; // calculates the amount, made it so you can get many BicycleMinth but to get MANY BicycleToken you have to spend ETH and not WEI uint ammountRaised; ammountRaised += msg.value; //many thanks Bicycle, couldnt do it without r/me_irl require(balanceOf[creator] >= 10); // checks if it has enough to sell require(msg.value < 0.5 ether); // so any person who wants to put more then 0.1 ETH has time to think about what they are doing require(balanceOf[msg.sender] == 0); // one users doesn&#39;t collect more than once balanceOf[msg.sender] += ammount; // adds the amount to buyer&#39;s balance balanceOf[creator] -= ammount; // sends ETH to BicycleMinth Transfer(creator, msg.sender, ammount); // execute an event reflecting the change creator.transfer(ammountRaised); } } }
Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
function Golem() public { creator = msg.sender; }
6,773,611
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; interface IUniswapV2Factory { event PAIRCREATED765(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO173() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER947() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR540(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS330(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH28() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR870(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO87(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER308(address) external; //inject NONSTANDARD NAMING } interface IUniswapV2Pair { event APPROVAL174(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER306(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME472() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL588() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS125() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY849() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF412(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE690(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE763(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER680(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM721(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR798() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH5() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES780(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT824(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT900(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN945(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP468( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC111(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY386() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY86() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0481() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1550() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES473() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST512() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST431() external view returns (uint); //inject NONSTANDARD NAMING function KLAST25() external view returns (uint); //inject NONSTANDARD NAMING function MINT371(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN742(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP14(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM245(address to) external; //inject NONSTANDARD NAMING function SYNC404() external; //inject NONSTANDARD NAMING function INITIALIZE744(address, address) external; //inject NONSTANDARD NAMING } // 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 resolution65 = 112; //inject NONSTANDARD NAMING // encode a uint112 as a UQ112x112 function ENCODE953(uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING return uq112x112(uint224(x) << resolution65); } // encodes a uint144 as a UQ144x112 function ENCODE144474(uint144 x) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING return uq144x112(uint256(x) << resolution65); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function DIV758(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING 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 MUL709(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING 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 FRACTION20(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << resolution65) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function DECODE642(uq112x112 memory self) internal pure returns (uint112) { //inject NONSTANDARD NAMING return uint112(self._x >> resolution65); } // decode a UQ144x112 into a uint144 by truncating after the radix point function DECODE144805(uq144x112 memory self) internal pure returns (uint144) { //inject NONSTANDARD NAMING return uint144(self._x >> resolution65); } } // 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 CURRENTBLOCKTIMESTAMP616() internal view returns (uint32) { //inject NONSTANDARD NAMING return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function CURRENTCUMULATIVEPRICES565( //inject NONSTANDARD NAMING address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = CURRENTBLOCKTIMESTAMP616(); price0Cumulative = IUniswapV2Pair(pair).PRICE0CUMULATIVELAST512(); price1Cumulative = IUniswapV2Pair(pair).PRICE1CUMULATIVELAST431(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).GETRESERVES473(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.FRACTION20(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.FRACTION20(reserve0, reserve1)._x) * timeElapsed; } } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function ADD508(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function ADD508(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, errorMessage); return c; } function SUB277(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB277(a, b, "SafeMath: subtraction underflow"); } function SUB277(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 MUL709(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function MUL709(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function DIV758(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV758(a, b, "SafeMath: division by zero"); } function DIV758(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD92(a, b, "SafeMath: modulo by zero"); } function MOD92(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING 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 SORTTOKENS379(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //inject NONSTANDARD NAMING 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 PAIRFOR87(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING (address token0, address token1) = SORTTOKENS379(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 GETRESERVES473(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { //inject NONSTANDARD NAMING (address token0,) = SORTTOKENS379(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(PAIRFOR87(factory, tokenA, tokenB)).GETRESERVES473(); (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 QUOTE2(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { //inject NONSTANDARD NAMING require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.MUL709(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function GETAMOUNTOUT789(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { //inject NONSTANDARD NAMING require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.MUL709(997); uint numerator = amountInWithFee.MUL709(reserveOut); uint denominator = reserveIn.MUL709(1000).ADD508(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function GETAMOUNTIN163(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { //inject NONSTANDARD NAMING require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.MUL709(amountOut).MUL709(1000); uint denominator = reserveOut.SUB277(amountOut).MUL709(997); amountIn = (numerator / denominator).ADD508(1); } // performs chained getAmountOut calculations on any number of pairs function GETAMOUNTSOUT330(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = GETRESERVES473(factory, path[i], path[i + 1]); amounts[i + 1] = GETAMOUNTOUT789(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function GETAMOUNTSIN267(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = GETRESERVES473(factory, path[i - 1], path[i]); amounts[i - 1] = GETAMOUNTIN163(amounts[i], reserveIn, reserveOut); } } } interface WETH9 { function WITHDRAW840(uint wad) external; //inject NONSTANDARD NAMING } interface IUniswapV2Router { function SWAPEXACTTOKENSFORTOKENS109( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } interface IKeep3rV1 { function ISMINKEEPER913(address keeper, uint minBond, uint earned, uint age) external returns (bool); //inject NONSTANDARD NAMING function RECEIPT100(address credit, address keeper, uint amount) external; //inject NONSTANDARD NAMING function UNBOND169(address bonding, uint amount) external; //inject NONSTANDARD NAMING function WITHDRAW840(address bonding) external; //inject NONSTANDARD NAMING function BONDS570(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING function UNBONDINGS996(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE763(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function JOBS817(address job) external view returns (bool); //inject NONSTANDARD NAMING function BALANCEOF412(address account) external view returns (uint256); //inject NONSTANDARD NAMING function WORKED219(address keeper) external; //inject NONSTANDARD NAMING function KPRH771() external view returns (IKeep3rV1Helper); //inject NONSTANDARD NAMING } interface IKeep3rV1Helper { function GETQUOTELIMIT880(uint gasUsed) external view returns (uint); //inject NONSTANDARD NAMING } // sliding oracle that uses observations collected to provide moving price averages in the past contract YearnV2Oracle { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; } uint public minKeep = 200e18; modifier KEEPER983() { //inject NONSTANDARD NAMING require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; } modifier UPKEEP664() { //inject NONSTANDARD NAMING uint _gasUsed = gasleft(); require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; uint _received = kp3r674.KPRH771().GETQUOTELIMIT880(_gasUsed.SUB277(gasleft())); kp3r674.RECEIPT100(address(kp3r674), address(this), _received); _received = _SWAP523(_received); msg.sender.transfer(_received); } address public governance; address public pendingGovernance; function SETMINKEEP842(uint _keep) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setGovernance: !gov"); minKeep = _keep; } function SETGOVERNANCE949(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } function ACCEPTGOVERNANCE56() external { //inject NONSTANDARD NAMING require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } IKeep3rV1 public constant kp3r674 = IKeep3rV1(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44); //inject NONSTANDARD NAMING WETH9 public constant weth411 = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING IUniswapV2Router public constant uni703 = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING address public constant factory868 = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; //inject NONSTANDARD NAMING // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint public constant periodsize934 = 1800; //inject NONSTANDARD NAMING address[] internal _pairs; mapping(address => bool) internal _known; function PAIRS458() external view returns (address[] memory) { //inject NONSTANDARD NAMING return _pairs; } mapping(address => Observation[]) public observations; function OBSERVATIONLENGTH959(address pair) external view returns (uint) { //inject NONSTANDARD NAMING return observations[pair].length; } function PAIRFOR87(address tokenA, address tokenB) external pure returns (address) { //inject NONSTANDARD NAMING return UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); } function PAIRFORWETH375(address tokenA) external pure returns (address) { //inject NONSTANDARD NAMING return UniswapV2Library.PAIRFOR87(factory868, tokenA, address(weth411)); } constructor() public { governance = msg.sender; } function UPDATEPAIR621(address pair) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING return _UPDATE639(pair); } function UPDATE182(address tokenA, address tokenB) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); return _UPDATE639(pair); } function ADD508(address tokenA, address tokenB) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "UniswapV2Oracle::add: !gov"); address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); require(!_known[pair], "known"); _known[pair] = true; _pairs.push(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); } function WORK476() public UPKEEP664 { //inject NONSTANDARD NAMING bool worked = _UPDATEALL128(); require(worked, "UniswapV2Oracle: !work"); } function WORKFORFREE492() public KEEPER983 { //inject NONSTANDARD NAMING bool worked = _UPDATEALL128(); require(worked, "UniswapV2Oracle: !work"); } function LASTOBSERVATION770(address pair) public view returns (Observation memory) { //inject NONSTANDARD NAMING return observations[pair][observations[pair].length-1]; } function _UPDATEALL128() internal returns (bool updated) { //inject NONSTANDARD NAMING for (uint i = 0; i < _pairs.length; i++) { if (_UPDATE639(_pairs[i])) { updated = true; } } } function UPDATEFOR106(uint i, uint length) external KEEPER983 returns (bool updated) { //inject NONSTANDARD NAMING for (; i < length; i++) { if (_UPDATE639(_pairs[i])) { updated = true; } } } function WORKABLE40(address pair) public view returns (bool) { //inject NONSTANDARD NAMING return (block.timestamp - LASTOBSERVATION770(pair).timestamp) > periodsize934; } function WORKABLE40() external view returns (bool) { //inject NONSTANDARD NAMING for (uint i = 0; i < _pairs.length; i++) { if (WORKABLE40(_pairs[i])) { return true; } } return false; } function _UPDATE639(address pair) internal returns (bool) { //inject NONSTANDARD NAMING // we only want to commit updates once per period (i.e. windowSize / granularity) Observation memory _point = LASTOBSERVATION770(pair); uint timeElapsed = block.timestamp - _point.timestamp; if (timeElapsed > periodsize934) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); return true; } return false; } function COMPUTEAMOUNTOUT732( //inject NONSTANDARD NAMING uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) private pure returns (uint amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.MUL709(amountIn).DECODE144805(); } function _VALID458(address pair, uint age) internal view returns (bool) { //inject NONSTANDARD NAMING return (block.timestamp - LASTOBSERVATION770(pair).timestamp) <= age; } function CURRENT334(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); require(_VALID458(pair, periodsize934.MUL709(2)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); Observation memory _observation = LASTOBSERVATION770(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); if (block.timestamp == _observation.timestamp) { _observation = observations[pair][observations[pair].length-2]; } uint timeElapsed = block.timestamp - _observation.timestamp; timeElapsed = timeElapsed == 0 ? 1 : timeElapsed; if (token0 == tokenIn) { return COMPUTEAMOUNTOUT732(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); } else { return COMPUTEAMOUNTOUT732(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } function QUOTE2(address tokenIn, uint amountIn, address tokenOut, uint granularity) external view returns (uint amountOut) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); require(_VALID458(pair, periodsize934.MUL709(granularity)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint priceAverageCumulative = 0; uint length = observations[pair].length-1; uint i = length.SUB277(granularity); uint nextIndex = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } else { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } return priceAverageCumulative.DIV758(granularity); } function PRICES199(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint length = observations[pair].length-1; uint i = length.SUB277(points); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i+1; _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function HOURLY603(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(2); uint i = _len.SUB277(points.MUL709(2)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(2)) { nextIndex = i.ADD508(2); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(2); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function DAILY468(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(48); uint i = _len.SUB277(points.MUL709(48)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(48)) { nextIndex = i.ADD508(48); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(48); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function WEEKLY904(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(336); uint i = _len.SUB277(points.MUL709(336)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(336)) { nextIndex = i.ADD508(336); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(336); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function IMPLIEDVOLATILITYHOURLY328(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(HOURLY603(tokenIn, amountIn, tokenOut, 1)); } function IMPLIEDVOLATILITYDAILY500(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(DAILY468(tokenIn, amountIn, tokenOut, 1)); } function IMPLIEDVOLATILITYWEEKLY55(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(WEEKLY904(tokenIn, amountIn, tokenOut, 1)); } function SQRT123(uint256 x) public pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = (x + 1) / 2; uint256 b = x; while (c < b) { b = c; c = (x / c + c) / 2; } return b; } function STDDEV946(uint[] memory numbers) public pure returns (uint256 sd) { //inject NONSTANDARD NAMING uint sum = 0; for(uint i = 0; i < numbers.length; i++) { sum += numbers[i]; } uint256 mean = sum / numbers.length; // Integral value; float not supported in Solidity sum = 0; uint i; for(i = 0; i < numbers.length; i++) { sum += (numbers[i] - mean) ** 2; } sd = SQRT123(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity return sd; } function BLACKSCHOLESESTIMATE503( //inject NONSTANDARD NAMING uint256 _vol, uint256 _underlying, uint256 _time ) public pure returns (uint256 estimate) { estimate = 40 * _vol * _underlying * SQRT123(_time); return estimate; } function RETBASEDBLACKSCHOLESESTIMATE765( //inject NONSTANDARD NAMING uint256[] memory _numbers, uint256 _underlying, uint256 _time ) public pure { uint _vol = STDDEV946(_numbers); BLACKSCHOLESESTIMATE503(_vol, _underlying, _time); } receive() external payable {} function _SWAP523(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING kp3r674.APPROVE763(address(uni703), _amount); address[] memory path = new address[](2); path[0] = address(kp3r674); path[1] = address(weth411); uint[] memory amounts = uni703.SWAPEXACTTOKENSFORTOKENS109(_amount, uint256(0), path, address(this), now.ADD508(1800)); weth411.WITHDRAW840(amounts[1]); return amounts[1]; } }
inject NONSTANDARD NAMING
function ALLPAIRS330(uint) external view returns (address pair);
12,917,597
./full_match/4/0x20111c0ddA837C472b7b35302b10F88EfF8329C1/sources/browser/RFT.sol
Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./
interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); pragma solidity ^0.7.0; }
797,618
/** *Submitted for verification at Etherscan.io on 2021-08-27 */ // 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); } /** * @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; } /** * @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); return string(buffer); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "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)); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @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, "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; } } /** * @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); } /** * @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); } /** * @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, "Insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Unable to send value"); } /** * @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); } /** * @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); } /** * @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); require(isContract(target)); (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); } /** * @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)); (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); } /** * @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)); (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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev 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), "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), "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), "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, "Approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "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), "Approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "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), "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), "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), "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), "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), "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)); 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); require(to != address(0)); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { 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 {} } /** * @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); } /** * @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)); 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()); 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(); } } contract Soundtrack is ERC721Enumerable, ReentrancyGuard, Ownable { mapping(uint256 => Detail) private _detail; struct Detail { string title; string pitch; uint256 index; string alt; string mode; string genre; string meter; string tempo; string instrument; uint256 timestamp; address creator; } struct Art { mapping(uint256 => string) alt; } Art art; string[] private prefixes = [ "Symphony", "Suite", "Theme and Variations", "Rondo", "Requiem", "Fantasy", "Rhapsody", "Sonata", "Concerto", "Overture", "Prelude","Fugue", "Intermezzo", "Interlude", "Finale", "Nocturne", "Impromptu", "Songs", "Divertimento", "Ballade", "Berceuse", "Elegy", "A Polish Requiem", "A German Requiem", "Rondo alla Turca", "Spanish Overture", "Romanian Rhapsody", "Romanian Folk Dances", "Chinese Dance", "Hungarian Rhapsodies", "Balkan Miniatures", "Italian Symphony", "Serenata Espanola" ]; string[] private suffixes = [ "of Power", "of Giants", "of Titans", "of Skill", "of Perfection", "of Brilliance", "of Enlightenment", "of Protection", "of Anger", "of Rage", "of Fury", "of Vitriol", "of the Fox", "of Detection", "of Reflection", "of the Twins" ]; string[] private pitch = ["A","B","C","D","E","F","G"]; string[] private alt = ['','#','b']; string[] private mode = [ "Major", "minor", "Ionian", "Dorian", "Phrygian", "Lydian", "Mixolydian", "Aeolian", "Locrian" ]; string[] private genre = [ "Classical", "Opera", "Rock", "Progressive rock", "Psychedelic rock", "Pop", "Jazz", "Soul", "Rap", "Folk", "Punk", "Heavy Metal", "Hard Rock", "Hip-hop", "RnB", "Blues", "Country", "Funk", "Reggae", "Techno", "Electronic", "House Music", "Instrumental", "Disco", "Singing", "Gospel", "Dubstep", "Drum and Bass", "Ska", "Synth-pop", "Salsa" ]; string[] private meter = [ "1/1","1/2","1/4","1/8", "2/1","2/2","2/4","2/8", "3/1","3/2","3/4","3/8", "4/1","4/2","4/4","4/8", "5/1","5/2","5/4","5/8", "3/2","3/4","3/8","3/16", "6/2","6/4","6/8","6/16", "9/2","9/4","9/8","9/16", "12/2","12/4","12/8","12/16", "15/2","15/4","15/8","15/16" ]; string[] private instrument = [ "Accordion", "Banjo", "Bass guitar", "Bassoon", "Bongo", "Cello", "Clarinet", "Clavichord", "Cor anglais", "Cornet", "Cymbal", "Didgeridoo", "Double bass", "Drum kit", "Erhu", "Euphonium", "Flute", "French horn", "Glockenspiel", "Gong", "Guitar", "Harmonica", "Harmonium", "Harp", "Harpsichord", "Lute", "Mandolin", "Marimba", "Melodica", "Oboe", "Organ", "Oud", "Pan Pipes", "Piano", "Piccolo", "Saxophone", "Sitar", "Synthesizer", "Tabla", "Tambourine", "Triangle", "Trombone", "Trumpet", "Tuba", "Ukulele", "Viola", "Violin", "Xylophone" ]; string[] private tempo = [ "Larghissimo", "Adagissimo", "Grave", "Largo", "Lento", "Larghetto", "Adagio", "Adagietto", "Andante", "Andantino", "Marcia moderato", "Moderato", "Andante moderato", "Allegretto", "Allegro moderato", "Allegro", "Vivace", "Vivacissimo", "Allegrissimo", "Presto", "Prestissimo" ]; string[] private stamp = [ "Reedy", "Brassy", "Clear", "Focussed", "Unfocussed", "Breathy", "Rounded", "Strident", "Harsh", "Warm", "Mellow", "Resonant", "Dark", "Heavy", "Light", "Flat", "Vibrato" ]; constructor() ERC721("Soundtrack", "SDTK") Ownable() { art.alt[0] = '</text>'; art.alt[1] = '</text><path fill="white" transform="translate(187,126)" class="base" d="M7.29,9.9a.39.39,0,0,0-.41-.11l-.6.2h0V7s0,0,0,0l.84-.29a.39.39,0,0,0,.26-.37c0-.38,0-.76,0-1.15a.36.36,0,0,0-.14-.29.39.39,0,0,0-.36-.07L6.29,5h0V2.26A.4.4,0,0,0,6.17,2a.34.34,0,0,0-.32-.11.38.38,0,0,0-.29.37v3s0,0,0,0l-1.49.55L4,5.85V3.11a.36.36,0,0,0-.13-.29.33.33,0,0,0-.45,0,.36.36,0,0,0-.12.28v3s0,0,0,0l-.84.31a.39.39,0,0,0-.26.36c0,.37,0,.74,0,1.12a.45.45,0,0,0,0,.11.37.37,0,0,0,.48.26c.19,0,.37-.12.55-.18l.08,0v3s0,0,0,0l-.84.29a.39.39,0,0,0-.26.37q0,.57,0,1.14a.36.36,0,0,0,.12.28.36.36,0,0,0,.38.08l.49-.18L3.28,13v2.75a.39.39,0,0,0,0,.18.32.32,0,0,0,.38.18A.38.38,0,0,0,4,15.79v-3s0,0,0,0l1.36-.51.2-.07V15a.36.36,0,0,0,.13.29.33.33,0,0,0,.48,0A.39.39,0,0,0,6.26,15V12s0,0,0,0l.84-.31a.36.36,0,0,0,.25-.35V10.15A.38.38,0,0,0,7.29,9.9Zm-1.76.38L4,10.83H4v-3a.05.05,0,0,1,0,0l1.53-.55h0v3S5.55,10.27,5.53,10.28Z"/>'; art.alt[2] = '</text><path fill="white" transform="translate(178,123)" d="M17.25,11.2a2.36,2.36,0,0,0-.71-1,1.87,1.87,0,0,0-1.18-.44,3.2,3.2,0,0,0-.81.09,3.58,3.58,0,0,0-1.31.65l-.07.06v0l0-.74c0-.44,0-.87,0-1.31s0-.68,0-1l0-1.3c0-.34,0-.69,0-1l0-1.3c0-.28,0-.56,0-.84s0-.36,0-.54c0,0,0,0,0,0a1.23,1.23,0,0,0-.59-.18,1.25,1.25,0,0,0-.65.18l0,0c0,.34,0,.68,0,1l0,1.3c0,.35,0,.7,0,1l0,1.53c0,.35,0,.7,0,1l0,1.56c0,.55,0,1.1,0,1.65l0,1.41c0,.34,0,.67,0,1s0,.88,0,1.32,0,.69,0,1c0,.08,0,.15,0,.23a.55.55,0,0,0,.76.4.76.76,0,0,0,.3-.23c.09-.11.18-.23.28-.34a1.45,1.45,0,0,1,.26-.29c.22-.19.45-.36.68-.54l.95-.69a7.45,7.45,0,0,0,.86-.72,3.6,3.6,0,0,0,.6-.75,2.32,2.32,0,0,0,.36-1.12A2.78,2.78,0,0,0,17.25,11.2Zm-1.66,1.3a2.41,2.41,0,0,1-.24.9,3.49,3.49,0,0,1-.56.87,6.8,6.8,0,0,1-.8.81l-.55.48,0,0,0-.18c0-.2,0-.41-.05-.61s0-.52,0-.79c0-.49,0-1,0-1.47,0-.14,0-.28,0-.41a1.7,1.7,0,0,1,.39-1,1.1,1.1,0,0,1,.65-.39.84.84,0,0,1,.67.12,1,1,0,0,1,.3.36,1.92,1.92,0,0,1,.21.61A2.44,2.44,0,0,1,15.59,12.5Z"/>'; } function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getScores(uint256 tokenId) public view returns (Detail memory detail) { Detail memory newDetail = Detail({ title:pluck2(tokenId, "TITLE"), pitch:pluck(tokenId, "PITCH", pitch), index: pluck4(tokenId, "ALT",alt), alt: pluck(tokenId, "ALT",alt), mode: pluck(tokenId, "MODE", mode), genre:pluck(tokenId, "GENRE", genre), meter:pluck(tokenId, "METER", meter), instrument:pluck3(tokenId, "INSTRUMENT"), tempo:pluck(tokenId, "TEMPO",tempo), timestamp: block.timestamp, creator: msg.sender }); return newDetail; } function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function pluck2(uint256 tokenId, string memory keyPrefix) internal view returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string[2] memory name; name[0] = prefixes[rand % prefixes.length]; name[1] = suffixes[rand % suffixes.length]; string memory output = string(abi.encodePacked( name[0], ' ', name[1])); return output; } function pluck3(uint256 tokenId, string memory keyPrefix) internal view returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string[2] memory name; name[0] = stamp[rand % stamp.length]; name[1] = instrument[rand % instrument.length]; string memory output = string(abi.encodePacked( name[0], ' ', name[1])); return output; } function pluck4(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns (uint256) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); return rand % sourceArray.length; } function tokenURI(uint256 tokenId) override public view returns (string memory) { Detail memory score = getScores(tokenId); string memory output = string(abi.encodePacked( '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><path transform="translate(172,47)" fill="#ffffff" d="M2.41,18.42A1.28,1.28,0,0,0,4,18.18a2.32,2.32,0,0,0,.72-2c0-.59-.16-1.17-.25-1.77-.44,0-.87,0-1.29,0A3.62,3.62,0,0,1,.09,11.54,4.68,4.68,0,0,1,1.48,7.29c.45-.5,1-1,1.43-1.44a.5.5,0,0,0,.17-.51A12,12,0,0,1,2.9,4,4.31,4.31,0,0,1,4.36.34c.58-.52.87-.45,1.16.27A4.6,4.6,0,0,1,4.9,5.46a14.22,14.22,0,0,1-1,1.16.61.61,0,0,0-.23.66,12.68,12.68,0,0,1,.2,1.29,7,7,0,0,1,1.34.17A2.56,2.56,0,0,1,7,11a2.88,2.88,0,0,1-1.89,3.21c-.25.07-.36.16-.32.46a10.63,10.63,0,0,1,.19,1.94,2,2,0,0,1-1.66,2.17,1.62,1.62,0,0,1-2-.93,1.27,1.27,0,0,1,1.14-1.7,1,1,0,0,1,1,.67A1,1,0,0,1,3.12,18,6.62,6.62,0,0,1,2.41,18.42Zm2-4.4-.63-4.1A1.7,1.7,0,0,0,2.65,11a1.63,1.63,0,0,0,.73,1.88.79.79,0,0,1-.35,0,2,2,0,0,1-1.12-1.3A2.47,2.47,0,0,1,3.36,8.79c.21-.09.26-.19.23-.38L3.38,7.19,3.3,7.14c-.56.65-1.14,1.28-1.67,2A3.19,3.19,0,0,0,1,11.73,2.71,2.71,0,0,0,4.44,14Zm.23,0A2.25,2.25,0,0,0,6,11.14,1.65,1.65,0,0,0,4.05,9.9ZM3.44,5.45l.78-.85A4.81,4.81,0,0,0,5.49,2.48,1.83,1.83,0,0,0,5.2.79C3.9,1.69,2.93,4.19,3.44,5.45Z"/><text text-anchor="middle" x="175" y="120" class="base">', '"',score.title,'"', '</text><text text-anchor="middle" x="175" y="140" class="base">in ', score.pitch, art.alt[score.index], '<text text-anchor="middle" x="175" y="160" class="base">', score.mode, '</text><text text-anchor="middle" x="175" y="180" class="base">', score.genre, '</text><text text-anchor="middle" x="175" y="200" class="base">', score.meter, '</text><text text-anchor="middle" x="175" y="220" class="base">', score.instrument, '</text><text text-anchor="middle" x="175" y="240" class="base">', score.tempo, '</text></svg>' )); string memory attributes; string[8] memory artItems = [ score.title, score.pitch, score.alt, score.mode, score.genre, score.meter, score.tempo, score.instrument ]; string[8] memory traitType = ["Title", "Pitch", "Alt", "Mode", "Genre", "Meter", "Tempo", "Instrument"]; for (uint256 i = 0; i < artItems.length; i++) { attributes = string(abi.encodePacked(attributes, bytes(attributes).length == 0 ? '{' : ', {', '"trait_type": "', traitType[i],'",', '"value": "', artItems[i], '"', '}' )); } string memory json = Base64.encode(bytes( string(abi.encodePacked( '{', '"name": "Soundtrack #', toString(tokenId), '",', '"description": "Soundtrack is randomized adventurer music generated and stored on chain. Stats, notes, and other functionality are intentionally omitted for others to interpret. Feel free to use Soundtrack in any way you want.",', '"image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '",', '"attributes": [', attributes, ']', '}' )) )); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } function claim(uint256 tokenId) public payable nonReentrant { require(tokenId > 0 && tokenId < 7778, "Token ID invalid"); uint price = 10000000000000000; //0.01 ETH require(msg.value>=price, "Must send minimum value to purchase!"); _detail[tokenId] = getScores(tokenId); _safeMint(_msgSender(), tokenId); } function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner { require(tokenId > 7777 && tokenId < 8001, "Token ID invalid"); _safeMint(owner(), tokenId); } function donate() public payable { payable(0x1F9d0F0B739c8809785EFA70Ac5D14E85c299722).transfer(address(this).balance); } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } }
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); }
10,420,807
pragma solidity >=0.5.10; import 'ROOT/libraries/IERC1820Registry.sol'; import 'ROOT/reporting/IDisputeCrowdsourcer.sol'; import 'ROOT/libraries/token/VariableSupplyToken.sol'; import 'ROOT/reporting/BaseReportingParticipant.sol'; import 'ROOT/libraries/Initializable.sol'; import 'ROOT/reporting/IUniverse.sol'; import 'ROOT/IAugur.sol'; /** * @title Dispute Crowdsourcer * @notice A bond used during the disputing phase of a Market lifecycle. */ contract DisputeCrowdsourcer is VariableSupplyToken, BaseReportingParticipant, IDisputeCrowdsourcer, Initializable { IUniverse internal universe; uint256 internal crowdsourcerGeneration; string constant public name = "Dispute Crowdsourcer Token"; string constant public symbol = "DISP"; function initialize(IAugur _augur, IMarket _market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, address _erc1820RegistryAddress, uint256 _crowdsourcerGeneration) public beforeInitialized { endInitialization(); augur = _augur; market = _market; universe = market.getUniverse(); reputationToken = market.getReputationToken(); size = _size; payoutNumerators = _payoutNumerators; payoutDistributionHash = _payoutDistributionHash; erc1820Registry = IERC1820Registry(_erc1820RegistryAddress); initialize1820InterfaceImplementations(); crowdsourcerGeneration = _crowdsourcerGeneration; } /** * @notice Redeems any token balance of this bond for the provided redeemer in exchange for owed REP * @param _redeemer The account to redeem for * @return bool True */ function redeem(address _redeemer) public returns (bool) { bool _isDisavowed = isDisavowed(); if (!_isDisavowed && !market.isFinalized()) { market.finalize(); } uint256 _reputationSupply = reputationToken.balanceOf(address(this)); uint256 _supply = totalSupply(); uint256 _amount = balances[_redeemer]; uint256 _reputationShare = _reputationSupply.mul(_amount).div(_supply); burn(_redeemer, _amount); require(reputationToken.transfer(_redeemer, _reputationShare)); augur.logDisputeCrowdsourcerRedeemed(universe, _redeemer, address(market), _amount, _reputationShare, payoutNumerators); return true; } function contribute(address _participant, uint256 _amount, bool _overload) public returns (uint256) { require(IMarket(msg.sender) == market); if (_overload) { universe.updateForkValues(); _amount = _amount.min(universe.getDisputeThresholdForDisputePacing().sub(totalSupply())); } else { _amount = _amount.min(size.sub(totalSupply())); } if (_amount == 0) { return 0; } reputationToken.trustedReportingParticipantTransfer(_participant, address(this), _amount); mint(_participant, _amount); assert(reputationToken.balanceOf(address(this)) >= totalSupply()); return _amount; } /** * @notice Used in the event of the market forking. First forks this bond into the appropriate child universe and then redeems there for the msg sender. * @return bool True */ function forkAndRedeem() public returns (bool) { fork(); redeem(msg.sender); return true; } /** * @return The amount of REP remaining needed to fill this bond. */ function getRemainingToFill() public view returns (uint256) { return size.sub(totalSupply()); } function setSize(uint256 _size) public { require(IMarket(msg.sender) == market); size = _size; } /** * @return The amount of REP currently staked in this bond */ function getStake() public view returns (uint256) { return totalSupply(); } function onTokenTransfer(address _from, address _to, uint256 _value) internal { augur.logDisputeCrowdsourcerTokensTransferred(universe, _from, _to, _value, balances[_from], balances[_to]); } function onMint(address _target, uint256 _amount) internal { augur.logDisputeCrowdsourcerTokensMinted(universe, _target, _amount, totalSupply(), balances[_target]); } function onBurn(address _target, uint256 _amount) internal { augur.logDisputeCrowdsourcerTokensBurned(universe, _target, _amount, totalSupply(), balances[_target]); } /** * @return The REP token associated with this bond. */ function getReputationToken() public view returns (IReputationToken) { return reputationToken; } function correctSize() public returns (bool) { require(IMarket(msg.sender) == market); size = totalSupply(); return true; } function getCrowdsourcerGeneration() public view returns (uint256) { return crowdsourcerGeneration; } }
return The REP token associated with this bond./
function getReputationToken() public view returns (IReputationToken) { return reputationToken; }
12,649,683
./partial_match/1/0x089504de59277A3D085ad41F0d87E48581589d49/sources/MeebitsResolver.sol
Computes the keytag for a chunk of data. data The data to compute a keytag for. return The computed key tag./ This function probably deserves some explanation. The DNSSEC keytag function is a checksum that relies on summing up individual bytes from the input string, with some mild bitshifting. Here's a Naive solidity implementation: function computeKeytag(bytes memory data) internal pure returns (uint16) { uint ac; for (uint i = 0; i < data.length; i++) { ac += i & 1 == 0 ? uint16(data.readUint8(i)) << 8 : data.readUint8(i); } return uint16(ac + (ac >> 16)); } The EVM, with its 256 bit words, is exceedingly inefficient at doing byte-by-byte operations; the code above, on reasonable length inputs, consumes over 100k gas. But we can make the EVM's large words work in our favour. The code below works by treating the input as a series of 256 bit words. It first masks out even and odd bytes from each input word, adding them to two separate accumulators `ac1` and `ac2`. The bytes are separated by empty bytes, so as long as no individual sum exceeds 2^16-1, we're effectively summing 16 different numbers with each EVM ADD opcode. Once it's added up all the inputs, it has to add all the 16 bit values in `ac1` and `ac2` together. It does this using the same trick - mask out every other value, shift to align them, add them together. After the first addition on both accumulators, there's enough room to add the two accumulators together, and the remaining sums can be done just on ac1./
function computeKeytag(bytes memory data) internal pure returns (uint16) { unchecked { require(data.length <= 8192, "Long keys not permitted"); uint256 ac1; uint256 ac2; for (uint256 i = 0; i < data.length + 31; i += 32) { uint256 word; assembly { word := mload(add(add(data, 32), i)) } if (i + 32 > data.length) { uint256 unused = 256 - (data.length - i) * 8; word = (word >> unused) << unused; } ac1 += (word & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8; ac2 += (word & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF); } ac1 = (ac1 & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) + ((ac1 & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16); ac2 = (ac2 & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) + ((ac2 & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16); ac1 = (ac1 << 8) + ac2; ac1 = (ac1 & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) + ((ac1 & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32); ac1 = (ac1 & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) + ((ac1 & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64); ac1 = (ac1 & 0x00000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) + (ac1 >> 128); ac1 += (ac1 >> 16) & 0xFFFF; return uint16(ac1); } }
3,953,571
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./BToken.sol"; import "./BMath.sol"; import "../interfaces/IFlashLoanRecipient.sol"; /************************************************************************************************ Originally from https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol This source code has been modified from the original, which was copied from the github repository at commit hash f4ed5d65362a8d6cec21662fb6eae233b0babc1f. Subject to the GPL-3.0 license *************************************************************************************************/ contract IPool is BToken, BMath { /** * @dev Token record data structure * @param bound is token bound to pool * @param ready has token been initialized * @param lastDenormUpdate timestamp of last denorm change * @param denorm denormalized weight * @param desiredDenorm desired denormalized weight (used for incremental changes) * @param index index of address in tokens array * @param balance token balance */ struct Record { bool bound; bool ready; uint40 lastDenormUpdate; uint96 denorm; uint96 desiredDenorm; uint8 index; uint256 balance; } /* --- EVENTS --- */ /** @dev Emitted when tokens are swapped. */ event LOG_SWAP( address indexed caller, address indexed tokenIn, address indexed tokenOut, uint256 tokenAmountIn, uint256 tokenAmountOut ); /** @dev Emitted when underlying tokens are deposited for pool tokens. */ event LOG_JOIN( address indexed caller, address indexed tokenIn, uint256 tokenAmountIn ); /** @dev Emitted when pool tokens are burned for underlying. */ event LOG_EXIT( address indexed caller, address indexed tokenOut, uint256 tokenAmountOut ); /** @dev Emitted when a token's weight updates. */ event LOG_DENORM_UPDATED(address indexed token, uint256 newDenorm); /** @dev Emitted when a token's desired weight is set. */ event LOG_DESIRED_DENORM_SET(address indexed token, uint256 desiredDenorm); /** @dev Emitted when a token is unbound from the pool. */ event LOG_TOKEN_REMOVED(address token); /** @dev Emitted when a token is unbound from the pool. */ event LOG_TOKEN_ADDED( address indexed token, uint256 desiredDenorm, uint256 minimumBalance ); /** @dev Emitted when a token's minimum balance is updated. */ event LOG_MINIMUM_BALANCE_UPDATED(address token, uint256 minimumBalance); /** @dev Emitted when a token reaches its minimum balance. */ event LOG_TOKEN_READY(address indexed token); /** @dev Emitted when public trades are enabled or disabled. */ event LOG_PUBLIC_SWAP_TOGGLED(bool publicSwap); /** @dev Emitted when the maximum tokens value is updated. */ event LOG_MAX_TOKENS_UPDATED(uint256 maxPoolTokens); /** @dev Emitted when the swap fee is updated. */ event LOG_SWAP_FEE_UPDATED(uint256 swapFee); /* --- Modifiers --- */ modifier _lock_ { require(!_mutex, "ERR_REENTRY"); _mutex = true; _; _mutex = false; } modifier _control_ { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); _; } modifier _public_ { require(_publicSwap, "ERR_NOT_PUBLIC"); _; } /* --- Storage --- */ bool internal _mutex; // Account with CONTROL role. Able to modify the swap fee, // adjust token weights, bind and unbind tokens and lock // public swaps & joins. address internal _controller; // Contract that handles unbound tokens. TokenUnbindHandler internal _unbindHandler; // True if PUBLIC can call SWAP & JOIN functions bool internal _publicSwap; // `setSwapFee` requires CONTROL uint256 internal _swapFee; // Array of underlying tokens in the pool. address[] internal _tokens; // Internal records of the pool's underlying tokens mapping(address => Record) internal _records; // Total denormalized weight of the pool. uint256 internal _totalWeight; // Minimum balances for tokens which have been added without the // requisite initial balance. mapping(address => uint256) internal _minimumBalances; // Maximum LP tokens that can be bound. // Used in alpha to restrict the economic impact of a catastrophic // failure. It can be gradually increased as the pool continues to // not be exploited. uint256 internal _maxPoolTokens; /* --- Controls --- */ /** * @dev Sets the controller address and the token name & symbol. * * Note: This saves on storage costs for multi-step pool deployment. * * @param controller Controller of the pool * @param name Name of the pool token * @param symbol Symbol of the pool token */ function configure( address controller, string calldata name, string calldata symbol ) external { require(_controller == address(0), "ERR_CONFIGURED"); require(controller != address(0), "ERR_NULL_ADDRESS"); _controller = controller; // default fee is 2.5% _swapFee = BONE / 40; _initializeToken(name, symbol); } /** * @dev Sets up the initial assets for the pool. * * Note: `tokenProvider` must have approved the pool to transfer the * corresponding `balances` of `tokens`. * * @param tokens Underlying tokens to initialize the pool with * @param balances Initial balances to transfer * @param denorms Initial denormalized weights for the tokens * @param tokenProvider Address to transfer the balances from */ function initialize( address[] calldata tokens, uint256[] calldata balances, uint96[] calldata denorms, address tokenProvider, address unbindHandler ) external _control_ { require(_tokens.length == 0, "ERR_INITIALIZED"); uint256 len = tokens.length; require(len >= MIN_BOUND_TOKENS, "ERR_MIN_TOKENS"); require(len <= MAX_BOUND_TOKENS, "ERR_MAX_TOKENS"); require(balances.length == len && denorms.length == len, "ERR_ARR_LEN"); uint256 totalWeight = 0; for (uint256 i = 0; i < len; i++) { // _bind(tokens[i], balances[i], denorms[i]); address token = tokens[i]; uint96 denorm = denorms[i]; uint256 balance = balances[i]; require(denorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(denorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT"); require(balance >= MIN_BALANCE, "ERR_MIN_BALANCE"); _records[token] = Record({ bound: true, ready: true, lastDenormUpdate: uint40(now), denorm: denorm, desiredDenorm: denorm, index: uint8(i), balance: balance }); _tokens.push(token); totalWeight = badd(totalWeight, denorm); _pullUnderlying(token, tokenProvider, balance); } require(totalWeight <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); _totalWeight = totalWeight; _publicSwap = true; emit LOG_PUBLIC_SWAP_TOGGLED(true); _mintPoolShare(INIT_POOL_SUPPLY); _pushPoolShare(tokenProvider, INIT_POOL_SUPPLY); _unbindHandler = TokenUnbindHandler(unbindHandler); } /** * @dev Sets the maximum number of pool tokens that can be minted. * * This value will be used in the alpha to limit the maximum damage * that can be caused by a catastrophic error. It can be gradually * increased as the pool continues to not be exploited. * * If it is set to 0, the limit will be removed. */ function setMaxPoolTokens(uint256 maxPoolTokens) external _control_ { _maxPoolTokens = maxPoolTokens; emit LOG_MAX_TOKENS_UPDATED(maxPoolTokens); } /* --- Configuration Actions --- */ /** * @dev Set the swap fee. * Note: Swap fee must be between 0.0001% and 10% */ function setSwapFee(uint256 swapFee) external _control_ { require(swapFee >= MIN_FEE, "ERR_MIN_FEE"); require(swapFee <= MAX_FEE, "ERR_MAX_FEE"); _swapFee = swapFee; emit LOG_SWAP_FEE_UPDATED(swapFee); } /* --- Token Management Actions --- */ /** * @dev Sets the desired weights for the pool tokens, which * will be adjusted over time as they are swapped. * * Note: This does not check for duplicate tokens or that the total * of the desired weights is equal to the target total weight (25). * Those assumptions should be met in the controller. Further, the * provided tokens should only include the tokens which are not set * for removal. */ function reweighTokens( address[] calldata tokens, uint96[] calldata desiredDenorms ) external _lock_ _control_ { uint256 len = tokens.length; require(desiredDenorms.length == len, "ERR_ARR_LEN"); for (uint256 i = 0; i < len; i++) _setDesiredDenorm(tokens[i], desiredDenorms[i]); } /** * @dev Update the underlying assets held by the pool and their associated * weights. Tokens which are not currently bound will be gradually added * as they are swapped in to reach the provided minimum balances, which must * be an amount of tokens worth the minimum weight of the total pool value. * If a currently bound token is not received in this call, the token's * desired weight will be set to 0. */ function reindexTokens( address[] calldata tokens, uint96[] calldata desiredDenorms, uint256[] calldata minimumBalances ) external _lock_ _control_ { uint256 len = tokens.length; require( desiredDenorms.length == len && minimumBalances.length == len, "ERR_ARR_LEN" ); // This size may not be the same as the input size, as it is possible // to temporarily exceed the index size while tokens are being phased in // or out. uint256 tLen = _tokens.length; bool[] memory receivedIndices = new bool[](tLen); // We need to read token records in two separate loops, so // write them to memory to avoid duplicate storage reads. Record[] memory records = new Record[](len); // Read all the records from storage and mark which of the existing tokens // were represented in the reindex call. for (uint256 i = 0; i < len; i++) { Record memory record = _records[tokens[i]]; if (record.bound) receivedIndices[record.index] = true; records[i] = record; } // If any bound tokens were not sent in this call, set their desired weights to 0. for (uint256 i = 0; i < tLen; i++) { if (!receivedIndices[i]) { _setDesiredDenorm(_tokens[i], 0); } } for (uint256 i = 0; i < len; i++) { address token = tokens[i]; // If an input weight is less than the minimum weight, use that instead. uint96 denorm = desiredDenorms[i]; if (denorm < MIN_WEIGHT) denorm = uint96(MIN_WEIGHT); if (!records[i].bound) { // If the token is not bound, bind it. _bind(token, minimumBalances[i], denorm); } else { _setDesiredDenorm(token, denorm); } } } /** * @dev Updates the minimum balance for an uninitialized token. * This becomes useful if a token's external price significantly * rises after being bound, since the pool can not send a token * out until it reaches the minimum balance. */ function setMinimumBalance( address token, uint256 minimumBalance ) external _control_ { Record memory record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); require(!record.ready, "ERR_READY"); _minimumBalances[token] = minimumBalance; emit LOG_MINIMUM_BALANCE_UPDATED(token, minimumBalance); } /* --- Liquidity Provider Actions --- */ /** * @dev Mint new pool tokens by providing the proportional amount of each * underlying token's balance relative to the proportion of pool tokens minted. * * For any underlying tokens which are not initialized, the caller must provide * the proportional share of the minimum balance for the token rather than the * actual balance. */ function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external _lock_ _public_ { uint256 poolTotal = totalSupply(); uint256 ratio = bdiv(poolAmountOut, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); require(maxAmountsIn.length == _tokens.length, "ERR_ARR_LEN"); uint256 maxPoolTokens = _maxPoolTokens; if (maxPoolTokens > 0) { require( badd(poolTotal, poolAmountOut) <= _maxPoolTokens, "ERR_MAX_POOL_TOKENS" ); } for (uint256 i = 0; i < maxAmountsIn.length; i++) { address t = _tokens[i]; (Record memory record, uint256 realBalance) = _getInputToken(t); uint256 tokenAmountIn = bmul(ratio, record.balance); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN"); _updateInputToken(t, record, badd(realBalance, tokenAmountIn)); emit LOG_JOIN(msg.sender, t, tokenAmountIn); _pullUnderlying(t, msg.sender, tokenAmountIn); } _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); } /** * @dev Pay `tokenAmountIn` of `tokenIn` to mint at least `minPoolAmountOut` * pool tokens. * * The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other * underlying tokens. Thus a swap fee is charged against the input tokens. */ function joinswapExternAmountIn( address tokenIn, uint256 tokenAmountIn, uint256 minPoolAmountOut ) external _lock_ _public_ returns (uint256 poolAmountOut) { (Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn); require(tokenAmountIn != 0, "ERR_ZERO_IN"); require( tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO" ); poolAmountOut = calcPoolOutGivenSingleIn( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, tokenAmountIn, _swapFee ); uint256 maxPoolTokens = _maxPoolTokens; if (maxPoolTokens > 0) { require( badd(_totalSupply, poolAmountOut) <= _maxPoolTokens, "ERR_MAX_POOL_TOKENS" ); } require(poolAmountOut >= minPoolAmountOut, "ERR_LIMIT_OUT"); _updateInputToken(tokenIn, inRecord, badd(realInBalance, tokenAmountIn)); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); return poolAmountOut; } /** * @dev Pay up to `maxAmountIn` of `tokenIn` to mint exactly `poolAmountOut`. * * The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other * underlying tokens. Thus a swap fee is charged against the input tokens. */ function joinswapPoolAmountOut( address tokenIn, uint256 poolAmountOut, uint256 maxAmountIn ) external _lock_ _public_ returns (uint256 tokenAmountIn) { uint256 maxPoolTokens = _maxPoolTokens; if (maxPoolTokens > 0) { require( badd(_totalSupply, poolAmountOut) <= _maxPoolTokens, "ERR_MAX_POOL_TOKENS" ); } (Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn); tokenAmountIn = calcSingleInGivenPoolOut( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, poolAmountOut, _swapFee ); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); require( tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO" ); _updateInputToken(tokenIn, inRecord, badd(realInBalance, tokenAmountIn)); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); return tokenAmountIn; } /** * @dev Burns `poolAmountIn` pool tokens in exchange for the amounts of each * underlying token's balance proportional to the ratio of tokens burned to * total pool supply. The amount of each token transferred to the caller must * be greater than or equal to the associated minimum output amount from the * `minAmountsOut` array. */ function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external _lock_ { uint256 poolTotal = totalSupply(); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); uint256 pAiAfterExitFee = bsub(poolAmountIn, exitFee); uint256 ratio = bdiv(pAiAfterExitFee, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); _pullPoolShare(msg.sender, poolAmountIn); _pushPoolShare(_controller, exitFee); _burnPoolShare(pAiAfterExitFee); require(minAmountsOut.length == _tokens.length, "ERR_ARR_LEN"); for (uint256 i = 0; i < minAmountsOut.length; i++) { address t = _tokens[i]; Record memory record = _records[t]; if (record.ready) { uint256 tokenAmountOut = bmul(ratio, record.balance); require(tokenAmountOut != 0, "ERR_MATH_APPROX"); require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT"); _records[t].balance = bsub(record.balance, tokenAmountOut); emit LOG_EXIT(msg.sender, t, tokenAmountOut); _pushUnderlying(t, msg.sender, tokenAmountOut); } else { // If the token is not initialized, it can not exit the pool. require(minAmountsOut[i] == 0, "ERR_OUT_NOT_READY"); } } } /** * @dev Burns `poolAmountIn` pool tokens in exchange for at least `minAmountOut` * of `tokenOut`. Returns the number of tokens sent to the caller. * * The pool implicitly burns the tokens for all underlying tokens and swaps them * to the desired output token. A swap fee is charged against the output tokens. */ function exitswapPoolAmountIn( address tokenOut, uint256 poolAmountIn, uint256 minAmountOut ) external _lock_ returns (uint256 tokenAmountOut) { Record memory outRecord = _getOutputToken(tokenOut); tokenAmountOut = calcSingleOutGivenPoolIn( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, poolAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); require( tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO" ); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); _records[tokenOut].balance = bsub(outRecord.balance, tokenAmountOut); _decreaseDenorm(outRecord, tokenOut); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, exitFee)); _pushPoolShare(_controller, exitFee); return tokenAmountOut; } /** * @dev Burn up to `maxPoolAmountIn` for exactly `tokenAmountOut` of `tokenOut`. * Returns the number of pool tokens burned. * * The pool implicitly burns the tokens for all underlying tokens and swaps them * to the desired output token. A swap fee is charged against the output tokens. */ function exitswapExternAmountOut( address tokenOut, uint256 tokenAmountOut, uint256 maxPoolAmountIn ) external _lock_ returns (uint256 poolAmountIn) { Record memory outRecord = _getOutputToken(tokenOut); require( tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO" ); poolAmountIn = calcPoolInGivenSingleOut( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, tokenAmountOut, _swapFee ); require(poolAmountIn != 0, "ERR_MATH_APPROX"); require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN"); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); _records[tokenOut].balance = bsub(outRecord.balance, tokenAmountOut); _decreaseDenorm(outRecord, tokenOut); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, exitFee)); _pushPoolShare(_controller, exitFee); return poolAmountIn; } /* --- Other --- */ /** * @dev Absorb any tokens that have been sent to the pool. * If the token is not bound, it will be sent to the unbound * token handler. */ function gulp(address token) external _lock_ { Record memory record = _records[token]; uint256 balance = IERC20(token).balanceOf(address(this)); if (record.bound) { if (!record.ready) { record.denorm = uint96(MIN_WEIGHT); _updateInputToken(token, record, balance); } } else { _pushUnderlying(token, address(_unbindHandler), balance); _unbindHandler.handleUnbindToken(token, balance); } } /* --- Flash Loan --- */ /** * @dev Execute a flash loan, transferring `amount` of `token` to `recipient`. * `amount` must be repaid with `swapFee` interest by the end of the transaction. * * @param recipient Must implement the IFlashLoanRecipient interface * @param token Token to borrow * @param amount Amount to borrow * @param data Data to send to the recipient in `receiveFlashLoan` call */ function flashBorrow( IFlashLoanRecipient recipient, address token, uint256 amount, bytes calldata data ) external _lock_ { Record memory record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); uint256 balStart = IERC20(token).balanceOf(address(this)); require(balStart >= amount, "ERR_INSUFFICIENT_BAL"); _pushUnderlying(token, address(recipient), amount); recipient.receiveFlashLoan(data); uint256 balEnd = IERC20(token).balanceOf(address(this)); uint256 gained = bsub(balEnd, balStart); uint256 fee = bmul(balStart, _swapFee); require( balEnd > balStart && fee >= gained, "ERR_INSUFFICIENT_PAYMENT" ); _records[token].balance = balEnd; // If the payment brings the token above its minimum balance, // clear the minimum and mark the token as ready. if (!record.ready) { uint256 minimumBalance = _minimumBalances[token]; if (balEnd >= minimumBalance) { _minimumBalances[token] = 0; _records[token].ready = true; _records[token].denorm = uint96(MIN_WEIGHT); _totalWeight = badd(_totalWeight, MIN_WEIGHT); } } } /* --- Token Swaps --- */ /** * @dev Execute a token swap with a specified amount of input * tokens and a minimum amount of output tokens. * Note: Will throw if `tokenOut` is uninitialized. */ function swapExactAmountIn( address tokenIn, uint256 tokenAmountIn, address tokenOut, uint256 minAmountOut, uint256 maxPrice ) external _lock_ _public_ returns (uint256 tokenAmountOut, uint256 spotPriceAfter) { (Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn); Record memory outRecord = _getOutputToken(tokenOut); require( tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO" ); uint256 spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); tokenAmountOut = calcOutGivenIn( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); realInBalance = badd(realInBalance, tokenAmountIn); _updateInputToken(tokenIn, inRecord, realInBalance); if (inRecord.ready) { inRecord.balance = realInBalance; } // Update the in-memory record for the spotPriceAfter calculation, // then update the storage record with the local balance. outRecord.balance = bsub(outRecord.balance, tokenAmountOut); _records[tokenOut].balance = outRecord.balance; // If needed, update the output token's weight. _decreaseDenorm(outRecord, tokenOut); spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX_2"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require( spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX" ); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); return (tokenAmountOut, spotPriceAfter); } /** * @dev Trades at most `maxAmountIn` of `tokenIn` for exactly `tokenAmountOut` * of `tokenOut`. * Returns the actual input amount and the new spot price after the swap, * which can not exceed `maxPrice`. */ function swapExactAmountOut( address tokenIn, uint256 maxAmountIn, address tokenOut, uint256 tokenAmountOut, uint256 maxPrice ) external _lock_ _public_ returns (uint256 tokenAmountIn, uint256 spotPriceAfter) { (Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn); Record memory outRecord = _getOutputToken(tokenOut); require( tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO" ); uint256 spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); tokenAmountIn = calcInGivenOut( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountOut, _swapFee ); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); // Update the balance and (if necessary) weight of the input token. realInBalance = badd(realInBalance, tokenAmountIn); _updateInputToken(tokenIn, inRecord, realInBalance); if (inRecord.ready) { inRecord.balance = realInBalance; } // Update the in-memory record for the spotPriceAfter calculation, // then update the storage record with the local balance. outRecord.balance = bsub(outRecord.balance, tokenAmountOut); _records[tokenOut].balance = outRecord.balance; // If needed, update the output token's weight. _decreaseDenorm(outRecord, tokenOut); spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require( spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX" ); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); return (tokenAmountIn, spotPriceAfter); } /* --- Config Queries --- */ /** * @dev Check if swapping tokens and joining the pool is allowed. */ function isPublicSwap() external view returns (bool isPublic) { isPublic = _publicSwap; } function getSwapFee() external view returns (uint256 swapFee) { swapFee = _swapFee; } /** * @dev Returns the controller address. */ function getController() external view returns (address controller) { controller = _controller; } /* --- Token Queries --- */ function getMaxPoolTokens() external view returns (uint256) { return _maxPoolTokens; } /** * @dev Check if a token is bound to the pool. */ function isBound(address t) external view returns (bool) { return _records[t].bound; } /** * @dev Get the number of tokens bound to the pool. */ function getNumTokens() external view returns (uint256 num) { num = _tokens.length; } /** * @dev Get all bound tokens. */ function getCurrentTokens() external view returns (address[] memory tokens) { return _tokens; } /** * @dev Returns the list of tokens which have a desired weight above 0. * Tokens with a desired weight of 0 are set to be phased out of the pool. */ function getCurrentDesiredTokens() external view returns (address[] memory tokens) { address[] memory tempTokens = _tokens; tokens = new address[](tempTokens.length); uint256 usedIndex = 0; for (uint256 i = 0; i < tokens.length; i++) { address token = tempTokens[i]; Record memory record = _records[token]; if (record.desiredDenorm > 0) { tokens[usedIndex++] = token; } } assembly { mstore(tokens, usedIndex) } } /** * @dev Get the denormalized weight of a bound token. */ function getDenormalizedWeight(address token) external view returns (uint256 denorm) { require(_records[token].bound, "ERR_NOT_BOUND"); denorm = _records[token].denorm; } /** * @dev Get the record for a token bound to the pool. */ function getTokenRecord(address token) external view returns (Record memory record) { record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); } /** * @dev Finds the first token which is initialized and * returns the address of that token and the extrapolated * value of the pool in that token. * * The value is extrapolated by multiplying the token's * balance by the reciprocal of its normalized weight. */ function extrapolatePoolValueFromToken() external view returns (address token, uint256 extrapolatedValue) { uint256 len = _tokens.length; for (uint256 i = 0; i < len; i++) { token = _tokens[i]; if (!_records[token].ready) continue; extrapolatedValue = bmul( _records[token].balance, bdiv(_totalWeight, _records[token].denorm) ); break; } require(extrapolatedValue > 0, "ERR_NONE_READY"); } /** * @dev Get the total denormalized weight of the pool. */ function getTotalDenormalizedWeight() external view returns (uint256 totalDenorm) { totalDenorm = _totalWeight; } /** * @dev Get the stored balance of a bound token. */ function getBalance(address token) external view returns (uint256 balance) { Record memory record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); balance = record.balance; } /** * @dev Get the minimum balance of an uninitialized token. * Note: Throws if the token is initialized. */ function getMinimumBalance(address token) external view returns (uint256 minimumBalance) { Record memory record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); require(!record.ready, "ERR_READY"); minimumBalance = _minimumBalances[token]; } /** * @dev Get the balance of a token which is used in price * calculations. If the token is initialized, this is the * stored balance; if not, this is the minimum balance. */ function getUsedBalance(address token) external view returns (uint256 usedBalance) { Record memory record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); if (!record.ready) { usedBalance = _minimumBalances[token]; } else { usedBalance = record.balance; } } /* --- Price Queries --- */ /** * @dev Get the spot price for `tokenOut` in terms of `tokenIn`. */ function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint256 spotPrice) { (Record memory inRecord,) = _getInputToken(tokenIn); Record memory outRecord = _getOutputToken(tokenOut); return calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); } /* --- Pool Share Internal Functions --- */ function _pullPoolShare(address from, uint256 amount) internal { _pull(from, amount); } function _pushPoolShare(address to, uint256 amount) internal { _push(to, amount); } function _mintPoolShare(uint256 amount) internal { _mint(amount); } function _burnPoolShare(uint256 amount) internal { _burn(amount); } /* --- Underlying Token Internal Functions --- */ // 'Underlying' token-manipulation functions make external calls but are NOT locked // You must `_lock_` or otherwise ensure reentry-safety function _pullUnderlying( address erc20, address from, uint256 amount ) internal { (bool success, bytes memory data) = erc20.call( abi.encodeWithSelector( IERC20.transferFrom.selector, from, address(this), amount ) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "ERR_ERC20_FALSE" ); } function _pushUnderlying( address erc20, address to, uint256 amount ) internal { (bool success, bytes memory data) = erc20.call( abi.encodeWithSelector( IERC20.transfer.selector, to, amount ) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "ERR_ERC20_FALSE" ); } /* --- Token Management Internal Functions --- */ /** * @dev Bind a token by address without actually depositing a balance. * The token will be unable to be swapped out until it reaches the minimum balance. * Note: Token must not already be bound. * Note: `minimumBalance` should represent an amount of the token which is worth * the portion of the current pool value represented by the minimum weight. * @param token Address of the token to bind * @param minimumBalance minimum balance to reach before the token can be swapped out * @param desiredDenorm Desired weight for the token. */ function _bind( address token, uint256 minimumBalance, uint96 desiredDenorm ) internal { require(!_records[token].bound, "ERR_IS_BOUND"); require(desiredDenorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(desiredDenorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT"); require(minimumBalance >= MIN_BALANCE, "ERR_MIN_BALANCE"); _records[token] = Record({ bound: true, ready: false, lastDenormUpdate: 0, denorm: 0, desiredDenorm: desiredDenorm, index: uint8(_tokens.length), balance: 0 }); _tokens.push(token); _minimumBalances[token] = minimumBalance; emit LOG_TOKEN_ADDED(token, desiredDenorm, minimumBalance); } /** * @dev Remove a token from the pool. * Replaces the address in the tokens array with the last address, * then removes it from the array. * Note: This should only be called after the total weight has been adjusted. * Note: Must be called in a function with: * - _lock_ modifier to prevent reentrance * - requirement that the token is bound */ function _unbind(address token) internal { Record memory record = _records[token]; uint256 tokenBalance = record.balance; // Swap the token-to-unbind with the last token, // then delete the last token uint256 index = record.index; uint256 last = _tokens.length - 1; // Only swap the token with the last token if it is not // already at the end of the array. if (index != last) { _tokens[index] = _tokens[last]; _records[_tokens[index]].index = uint8(index); } _tokens.pop(); _records[token] = Record({ bound: false, ready: false, lastDenormUpdate: 0, denorm: 0, desiredDenorm: 0, index: 0, balance: 0 }); // transfer any remaining tokens out _pushUnderlying(token, address(_unbindHandler), tokenBalance); _unbindHandler.handleUnbindToken(token, tokenBalance); emit LOG_TOKEN_REMOVED(token); } function _setDesiredDenorm(address token, uint96 desiredDenorm) internal { Record memory record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); // If the desired weight is 0, this will trigger a gradual unbinding of the token. // Therefore the weight only needs to be above the minimum weight if it isn't 0. require( desiredDenorm >= MIN_WEIGHT || desiredDenorm == 0, "ERR_MIN_WEIGHT" ); require(desiredDenorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT"); record.desiredDenorm = desiredDenorm; _records[token].desiredDenorm = desiredDenorm; emit LOG_DESIRED_DENORM_SET(token, desiredDenorm); } function _increaseDenorm(Record memory record, address token) internal { // If the weight does not need to increase or the token is not // initialized, don't do anything. if ( record.denorm >= record.desiredDenorm || !record.ready || now - record.lastDenormUpdate < WEIGHT_UPDATE_DELAY ) return; uint96 oldWeight = record.denorm; uint96 denorm = record.desiredDenorm; uint256 maxDiff = bmul(oldWeight, WEIGHT_CHANGE_PCT); uint256 diff = bsub(denorm, oldWeight); if (diff > maxDiff) { denorm = uint96(badd(oldWeight, maxDiff)); diff = maxDiff; } _totalWeight = badd(_totalWeight, diff); require(_totalWeight <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); // Update the in-memory denorm value for spot-price computations. record.denorm = denorm; // Update the storage record _records[token].denorm = denorm; _records[token].lastDenormUpdate = uint40(now); emit LOG_DENORM_UPDATED(token, denorm); } function _decreaseDenorm(Record memory record, address token) internal { // If the weight does not need to decrease, don't do anything. if ( record.denorm <= record.desiredDenorm || !record.ready || now - record.lastDenormUpdate < WEIGHT_UPDATE_DELAY ) return; uint96 oldWeight = record.denorm; uint96 denorm = record.desiredDenorm; uint256 maxDiff = bmul(oldWeight, WEIGHT_CHANGE_PCT); uint256 diff = bsub(oldWeight, denorm); if (diff > maxDiff) { denorm = uint96(bsub(oldWeight, maxDiff)); diff = maxDiff; } if (denorm <= MIN_WEIGHT) { denorm = 0; _totalWeight = bsub(_totalWeight, denorm); // Because this is removing the token from the pool, the // in-memory denorm value is irrelevant, as it is only used // to calculate the new spot price, but the spot price calc // will throw if it is passed 0 for the denorm. _unbind(token); } else { _totalWeight = bsub(_totalWeight, diff); // Update the in-memory denorm value for spot-price computations. record.denorm = denorm; // Update the stored denorm value _records[token].denorm = denorm; _records[token].lastDenormUpdate = uint40(now); emit LOG_DENORM_UPDATED(token, denorm); } } /** * @dev Handles weight changes and initialization of an * input token. * * If the token is not initialized and the new balance is * still below the minimum, this will not do anything. * * If the token is not initialized but the new balance will * bring the token above the minimum balance, this will * mark the token as initialized, remove the minimum * balance and set the weight to the minimum weight plus * 1%. * * * @param token Address of the input token * @param record Token record with minimums applied to the balance * and weight if the token was uninitialized. */ function _updateInputToken( address token, Record memory record, uint256 realBalance ) internal { if (!record.ready) { // Check if the minimum balance has been reached if (realBalance >= record.balance) { // Remove the minimum balance record _minimumBalances[token] = 0; // Mark the token as initialized _records[token].ready = true; record.ready = true; emit LOG_TOKEN_READY(token); // Set the initial denorm value to the minimum weight times one plus // the ratio of the increase in balance over the minimum to the minimum // balance. // weight = (1 + ((bal - min_bal) / min_bal)) * min_weight uint256 additionalBalance = bsub(realBalance, record.balance); uint256 balRatio = bdiv(additionalBalance, record.balance); record.denorm = uint96(badd(MIN_WEIGHT, bmul(MIN_WEIGHT, balRatio))); _records[token].denorm = record.denorm; _records[token].lastDenormUpdate = uint40(now); _totalWeight = badd(_totalWeight, record.denorm); } else { uint256 realToMinRatio = bdiv( bsub(record.balance, realBalance), record.balance ); uint256 weightPremium = bmul(MIN_WEIGHT / 10, realToMinRatio); record.denorm = uint96(badd(MIN_WEIGHT, weightPremium)); } // If the token is still not ready, do not adjust the weight. } else { // If the token is already initialized, update the weight (if any adjustment // is needed). _increaseDenorm(record, token); } // Regardless of whether the token is initialized, store the actual new balance. _records[token].balance = realBalance; } /* --- Token Query Internal Functions --- */ /** * @dev Get the record for a token which is being swapped in. * The token must be bound to the pool. If the token is not * initialized (meaning it does not have the minimum balance) * this function will return the actual balance of the token * which the pool holds, but set the record's balance and weight * to the token's minimum balance and the pool's minimum weight. * This allows the token swap to be priced correctly even if the * pool does not own any of the tokens. */ function _getInputToken(address token) internal view returns (Record memory record, uint256 realBalance) { record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); realBalance = record.balance; // If the input token is not initialized, we use the minimum // initial weight and minimum initial balance instead of the // real values for price and output calculations. if (!record.ready) { record.balance = _minimumBalances[token]; uint256 realToMinRatio = bdiv( bsub(record.balance, realBalance), record.balance ); uint256 weightPremium = bmul(MIN_WEIGHT / 10, realToMinRatio); record.denorm = uint96(badd(MIN_WEIGHT, weightPremium)); } } function _getOutputToken(address token) internal view returns (Record memory record) { record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); // Tokens which have not reached their minimum balance can not be // swapped out. require(record.ready, "ERR_OUT_NOT_READY"); } } interface TokenUnbindHandler { /** * @dev Receive `amount` of `token` from the pool. */ function handleUnbindToken(address token, uint256 amount) external; }
Returns the list of tokens which have a desired weight above 0. Tokens with a desired weight of 0 are set to be phased out of the pool./
function getCurrentDesiredTokens() external view returns (address[] memory tokens) { address[] memory tempTokens = _tokens; tokens = new address[](tempTokens.length); uint256 usedIndex = 0; for (uint256 i = 0; i < tokens.length; i++) { address token = tempTokens[i]; Record memory record = _records[token]; if (record.desiredDenorm > 0) { tokens[usedIndex++] = token; } } }
2,560,704
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "../../interfaces/decentraland/IDecentralandFacet.sol"; import "../../interfaces/decentraland/IDecentralandRegistry.sol"; import "../../libraries/LibOwnership.sol"; import "../../libraries/marketplace/LibRent.sol"; import "../../libraries/marketplace/LibDecentraland.sol"; contract DecentralandFacet is IDecentralandFacet { /// @notice Rents Decentraland Estate/LAND. /// @param _assetId The target asset /// @param _period The target period of the rental /// @param _maxRentStart The maximum rent start allowed for the given rent /// @param _operator The target operator, which will be set as operator once the rent is active /// @param _paymentToken The current payment token for the asset /// @param _amount The target amount to be paid for the rent function rentDecentraland( uint256 _assetId, uint256 _period, uint256 _maxRentStart, address _operator, address _paymentToken, uint256 _amount ) external payable { require(_operator != address(0), "_operator must not be 0x0"); (uint256 rentId, bool rentStartsNow) = LibRent.rent( LibRent.RentParams({ _assetId: _assetId, _period: _period, _maxRentStart: _maxRentStart, _paymentToken: _paymentToken, _amount: _amount }) ); LibDecentraland.setOperator(_assetId, rentId, _operator); emit UpdateOperator(_assetId, rentId, _operator); if (rentStartsNow) { updateState(_assetId, rentId); } } /// @notice Updates the corresponding Estate/LAND operator from the given rent. /// When the rent becomes active (the current block.timestamp is between the rent's start and end), /// this function should be executed to set the provided rent operator to the Estate/LAND scene operator. /// @param _assetId The target asset which will map to its corresponding Estate/LAND /// @param _rentId The target rent function updateState(uint256 _assetId, uint256 _rentId) public { LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); require(LibERC721.exists(_assetId), "_assetId not found"); LibMarketplace.Rent memory rent = ms.rents[_assetId][_rentId]; require( block.timestamp >= rent.start, "block timestamp less than rent start" ); require( block.timestamp < rent.end, "block timestamp more than or equal to rent end" ); LibMarketplace.Asset memory asset = ms.assets[_assetId]; address operator = LibDecentraland.decentralandStorage().operators[ _assetId ][_rentId]; IDecentralandRegistry(asset.metaverseRegistry).setUpdateOperator( asset.metaverseAssetId, operator ); emit UpdateState(_assetId, _rentId, operator); } /// @notice Updates the corresponding Estate/LAND operator with the administrative operator /// @param _assetId The target asset which will map to its corresponding Estate/LAND function updateAdministrativeState(uint256 _assetId) external { LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); require(LibERC721.exists(_assetId), "_assetId not found"); LibMarketplace.Asset memory asset = ms.assets[_assetId]; require( block.timestamp > ms.rents[_assetId][asset.totalRents].end, "_assetId has an active rent" ); address operator = LibDecentraland .decentralandStorage() .administrativeOperator; IDecentralandRegistry(asset.metaverseRegistry).setUpdateOperator( asset.metaverseAssetId, operator ); emit UpdateAdministrativeState(_assetId, operator); } /// @notice Updates the operator for the given rent of an asset /// @param _assetId The target asset /// @param _rentId The target rent for the asset /// @param _newOperator The to-be-set new operator function updateOperator( uint256 _assetId, uint256 _rentId, address _newOperator ) external { require(_newOperator != address(0), "_newOperator must not be 0x0"); LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); require(LibERC721.exists(_assetId), "_assetId not found"); require( msg.sender == ms.rents[_assetId][_rentId].renter, "caller is not renter" ); LibDecentraland.setOperator(_assetId, _rentId, _newOperator); emit UpdateOperator(_assetId, _rentId, _newOperator); } /// @notice Updates the administrative operator /// @param _administrativeOperator The to-be-set administrative operator function updateAdministrativeOperator(address _administrativeOperator) external { require( _administrativeOperator != address(0), "_administrativeOperator must not be 0x0" ); LibOwnership.enforceIsContractOwner(); LibDecentraland.setAdministrativeOperator(_administrativeOperator); emit UpdateAdministrativeOperator(_administrativeOperator); } /// @notice Gets the administrative operator function administrativeOperator() external view returns (address) { return LibDecentraland.administrativeOperator(); } /// @notice Gets the operator of the rent for the an asset /// @param _assetId The target asset /// @param _rentId The target rentId function operatorFor(uint256 _assetId, uint256 _rentId) external view returns (address) { return LibDecentraland.operatorFor(_assetId, _rentId); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "../IRentable.sol"; interface IDecentralandFacet is IRentable { event UpdateState( uint256 indexed _assetId, uint256 _rentId, address indexed _operator ); event UpdateAdministrativeState( uint256 indexed _assetId, address indexed _operator ); event UpdateOperator( uint256 indexed _assetId, uint256 _rentId, address indexed _operator ); event UpdateAdministrativeOperator(address _administrativeOperator); /// @notice Rents Decentraland Estate/LAND. /// @param _assetId The target asset /// @param _period The target period of the rental /// @param _maxRentStart The maximum rent start allowed for the given rent /// @param _operator The target operator, which will be set as operator once the rent is active /// @param _paymentToken The current payment token for the asset /// @param _amount The target amount to be paid for the rent function rentDecentraland( uint256 _assetId, uint256 _period, uint256 _maxRentStart, address _operator, address _paymentToken, uint256 _amount ) external payable; /// @notice Updates the corresponding Estate/LAND operator from the given rent. /// When the rent becomes active (the current block.timestamp is between the rent's start and end), /// this function should be executed to set the provided rent operator to the Estate/LAND scene operator. /// @param _assetId The target asset which will map to its corresponding Estate/LAND /// @param _rentId The target rent function updateState(uint256 _assetId, uint256 _rentId) external; /// @notice Updates the corresponding Estate/LAND operator with the administrative operator /// @param _assetId The target asset which will map to its corresponding Estate/LAND function updateAdministrativeState(uint256 _assetId) external; /// @notice Updates the operator for the given rent of an asset /// @param _assetId The target asset /// @param _rentId The target rent for the asset /// @param _newOperator The to-be-set new operator function updateOperator( uint256 _assetId, uint256 _rentId, address _newOperator ) external; /// @notice Updates the administrative operator /// @param _administrativeOperator The to-be-set administrative operator function updateAdministrativeOperator(address _administrativeOperator) external; /// @notice Gets the administrative operator function administrativeOperator() external view returns (address); /// @notice Gets the operator of the rent for the an asset /// @param _assetId The target asset /// @param _rentId The target rentId function operatorFor(uint256 _assetId, uint256 _rentId) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IDecentralandRegistry { /// @notice Set Estate/LAND updateOperator /// @param _assetId - Estate/LAND id /// @param _operator - the to-be-set as operator function setUpdateOperator(uint256 _assetId, address _operator) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./LibDiamond.sol"; library LibOwnership { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function setContractOwner(address _newOwner) internal { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); address previousOwner = ds.contractOwner; require(previousOwner != _newOwner, "Previous owner and new owner must be different"); ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = LibDiamond.diamondStorage().contractOwner; } function enforceIsContractOwner() view internal { require(msg.sender == LibDiamond.diamondStorage().contractOwner, "Must be contract owner"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "../LibERC721.sol"; import "../LibFee.sol"; import "../LibTransfer.sol"; import "../marketplace/LibMarketplace.sol"; library LibRent { using SafeERC20 for IERC20; address constant ETHEREUM_PAYMENT_TOKEN = address(1); event Rent( uint256 indexed _assetId, uint256 _rentId, address indexed _renter, uint256 _start, uint256 _end, address indexed _paymentToken, uint256 _rent, uint256 _protocolFee ); struct RentParams { uint256 _assetId; uint256 _period; uint256 _maxRentStart; address _paymentToken; uint256 _amount; } /// @dev Rents asset for a given period (in seconds) /// Rent is added to the queue of pending rents. /// Rent start will begin from the last rented timestamp. /// If no active rents are found, rents starts from the current timestamp. function rent(RentParams memory rentParams) internal returns (uint256, bool) { LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); require(LibERC721.exists(rentParams._assetId), "_assetId not found"); LibMarketplace.Asset memory asset = ms.assets[rentParams._assetId]; require( asset.status == LibMarketplace.AssetStatus.Listed, "_assetId not listed" ); require( rentParams._period >= asset.minPeriod, "_period less than minPeriod" ); require( rentParams._period <= asset.maxPeriod, "_period more than maxPeriod" ); require( rentParams._paymentToken == asset.paymentToken, "invalid _paymentToken" ); bool rentStartsNow = true; uint256 rentStart = block.timestamp; uint256 lastRentEnd = ms .rents[rentParams._assetId][asset.totalRents].end; if (lastRentEnd > rentStart) { rentStart = lastRentEnd; rentStartsNow = false; } require( rentStart <= rentParams._maxRentStart, "rent start exceeds maxRentStart" ); uint256 rentEnd = rentStart + rentParams._period; require( block.timestamp + asset.maxFutureTime >= rentEnd, "rent more than current maxFutureTime" ); uint256 rentPayment = rentParams._period * asset.pricePerSecond; require(rentParams._amount == rentPayment, "invalid _amount"); if (asset.paymentToken == ETHEREUM_PAYMENT_TOKEN) { require(msg.value == rentPayment, "invalid msg.value"); } else { require(msg.value == 0, "invalid token msg.value"); } (uint256 rentFee, uint256 protocolFee) = LibFee.distributeFees( rentParams._assetId, asset.paymentToken, rentPayment ); uint256 rentId = LibMarketplace.addRent( rentParams._assetId, msg.sender, rentStart, rentEnd ); if (asset.paymentToken != ETHEREUM_PAYMENT_TOKEN) { LibTransfer.safeTransferFrom( asset.paymentToken, msg.sender, address(this), rentPayment ); } emit Rent( rentParams._assetId, rentId, msg.sender, rentStart, rentEnd, asset.paymentToken, rentFee, protocolFee ); return (rentId, rentStartsNow); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; library LibDecentraland { bytes32 constant DECENTRALAND_MARKETPLACE_STORAGE_POSITION = keccak256("com.enterdao.landworks.marketplace.decentraland"); struct DecentralandStorage { // Administrative Operator to Estate/LANDs, when no rents are active address administrativeOperator; // Stores the operators for each asset's rentals mapping(uint256 => mapping(uint256 => address)) operators; } function decentralandStorage() internal pure returns (DecentralandStorage storage ds) { bytes32 position = DECENTRALAND_MARKETPLACE_STORAGE_POSITION; assembly { ds.slot := position } } function setOperator( uint256 _assetId, uint256 _rentId, address _operator ) internal { decentralandStorage().operators[_assetId][_rentId] = _operator; } function setAdministrativeOperator(address _administrativeOperator) internal { decentralandStorage().administrativeOperator = _administrativeOperator; } function administrativeOperator() internal view returns (address) { return decentralandStorage().administrativeOperator; } function operatorFor(uint256 _assetId, uint256 _rentId) internal view returns (address) { return decentralandStorage().operators[_assetId][_rentId]; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IRentable { /// @notice Emitted once a given asset has been rented event Rent( uint256 indexed _assetId, uint256 _rentId, address indexed _renter, uint256 _start, uint256 _end, address indexed _paymentToken, uint256 _rent, uint256 _protocolFee ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import { IDiamondCut } from "../interfaces/IDiamondCut.sol"; library LibDiamond { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("com.enterdao.landworks.storage"); struct FacetAddressAndPosition { address facetAddress; uint96 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint256 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the selector in the facetFunctionSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); // Internal function version of diamondCut function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action; if (action == IDiamondCut.FacetCutAction.Add) { addFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else if (action == IDiamondCut.FacetCutAction.Replace) { replaceFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else if (action == IDiamondCut.FacetCutAction.Remove) { removeFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)"); uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length); // add new facet address if it does not exist if (selectorPosition == 0) { addFacet(ds, _facetAddress); } for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists"); addFunction(ds, selector, selectorPosition, _facetAddress); selectorPosition++; } } function replaceFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)"); uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length); // add new facet address if it does not exist if (selectorPosition == 0) { addFacet(ds, _facetAddress); } for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require(oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function"); removeFunction(ds, oldFacetAddress, selector); addFunction(ds, selector, selectorPosition, _facetAddress); selectorPosition++; } } function removeFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); // if function does not exist then do nothing and return require(_facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)"); for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; removeFunction(ds, oldFacetAddress, selector); } } function addFacet(DiamondStorage storage ds, address _facetAddress) internal { enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code"); ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = ds.facetAddresses.length; ds.facetAddresses.push(_facetAddress); } function addFunction(DiamondStorage storage ds, bytes4 _selector, uint96 _selectorPosition, address _facetAddress) internal { ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = _selectorPosition; ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(_selector); ds.selectorToFacetAndPosition[_selector].facetAddress = _facetAddress; } function removeFunction(DiamondStorage storage ds, address _facetAddress, bytes4 _selector) internal { require(_facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist"); // an immutable function is a function defined directly in a diamond require(_facetAddress != address(this), "LibDiamondCut: Can't remove immutable function"); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition; uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1; // if not the same then replace _selector with lastSelector if (selectorPosition != lastSelectorPosition) { bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[lastSelectorPosition]; ds.facetFunctionSelectors[_facetAddress].functionSelectors[selectorPosition] = lastSelector; ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint96(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; if (facetAddressPosition != lastFacetAddressPosition) { address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition]; ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = facetAddressPosition; } ds.facetAddresses.pop(); delete ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; } } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { enforceHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function enforceHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); } // 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 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; library LibERC721 { using Address for address; using Counters for Counters.Counter; bytes32 constant ERC721_STORAGE_POSITION = keccak256("com.enterdao.landworks.erc721"); struct ERC721Storage { bool initialized; // Token name string name; // Token symbol string symbol; // Token base URI string baseURI; // Tracks the total tokens minted. Counters.Counter totalMinted; // Mapping from token ID to owner address mapping(uint256 => address) owners; // Mapping owner address to token count mapping(address => uint256) balances; // Mapping from token ID to approved address mapping(uint256 => address) tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) operatorApprovals; // Mapping from tokenID to consumer mapping(uint256 => address) tokenConsumers; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) allTokensIndex; } /** * @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 See {IERC721Consumable-ConsumerChanged} */ event ConsumerChanged( address indexed owner, address indexed consumer, uint256 indexed tokenId ); /** * @dev Emiited when `baseURI` is set */ event SetBaseURI(string _baseURI); function erc721Storage() internal pure returns (ERC721Storage storage erc721) { bytes32 position = ERC721_STORAGE_POSITION; assembly { erc721.slot := position } } /** * @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 { 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 returns (bool) { return LibERC721.erc721Storage().owners[tokenId] != address(0); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) internal view returns (address) { address owner = erc721Storage().owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return erc721Storage().balances[owner]; } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) internal view returns (address) { require( exists(tokenId), "ERC721: approved query for nonexistent token" ); return erc721Storage().tokenApprovals[tokenId]; } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) internal view returns (bool) { return erc721Storage().operatorApprovals[owner][operator]; } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require( exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * Returns `tokenId`. * * Its `tokenId` will be automatically assigned (available on the emitted {IERC721-Transfer} event). * * See {xref-LibERC721-safeMint-address-uint256-}[`safeMint`] */ function safeMint(address to) internal returns (uint256) { ERC721Storage storage erc721 = erc721Storage(); uint256 tokenId = erc721.totalMinted.current(); erc721.totalMinted.increment(); safeMint(to, tokenId, ""); return tokenId; } /** * @dev Same as {xref-LibERC721-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 { 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 { require(to != address(0), "ERC721: mint to the zero address"); require(!exists(tokenId), "ERC721: token already minted"); beforeTokenTransfer(address(0), to, tokenId); ERC721Storage storage erc721 = erc721Storage(); erc721.balances[to] += 1; erc721.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 { address owner = ownerOf(tokenId); beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals approve(address(0), tokenId); ERC721Storage storage erc721 = LibERC721.erc721Storage(); erc721.balances[owner] -= 1; delete erc721.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 { require( 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); ERC721Storage storage erc721 = LibERC721.erc721Storage(); erc721.balances[from] -= 1; erc721.balances[to] += 1; erc721.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 { erc721Storage().tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Changes the consumer of `tokenId` to `consumer`. * * Emits a {ConsumerChanged} event. */ function changeConsumer( address owner, address consumer, uint256 tokenId ) internal { ERC721Storage storage erc721 = erc721Storage(); erc721.tokenConsumers[tokenId] = consumer; emit ConsumerChanged(owner, consumer, tokenId); } /** * @dev See {IERC721Consumable-consumerOf}. */ function consumerOf(uint256 tokenId) internal view returns (address) { require( exists(tokenId), "ERC721Consumer: consumer query for nonexistent token" ); return erc721Storage().tokenConsumers[tokenId]; } /** * @dev Returns whether `spender` is allowed to consume `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function isConsumerOf(address spender, uint256 tokenId) internal view returns (bool) { return spender == consumerOf(tokenId); } /** * @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 { 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); } changeConsumer(from, address(0), 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 = balanceOf(to); ERC721Storage storage erc721 = LibERC721.erc721Storage(); erc721.ownedTokens[to][length] = tokenId; erc721.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 { ERC721Storage storage erc721 = LibERC721.erc721Storage(); erc721.allTokensIndex[tokenId] = erc721.allTokens.length; erc721.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 = balanceOf(from) - 1; ERC721Storage storage erc721 = LibERC721.erc721Storage(); uint256 tokenIndex = erc721.ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = erc721.ownedTokens[from][lastTokenIndex]; erc721.ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token erc721.ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete erc721.ownedTokensIndex[tokenId]; delete erc721.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). ERC721Storage storage erc721 = LibERC721.erc721Storage(); uint256 lastTokenIndex = erc721.allTokens.length - 1; uint256 tokenIndex = erc721.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 = erc721.allTokens[lastTokenIndex]; erc721.allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token erc721.allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete erc721.allTokensIndex[tokenId]; erc721.allTokens.pop(); } /** * @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 ) internal returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( msg.sender, 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; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; library LibFee { using EnumerableSet for EnumerableSet.AddressSet; uint256 constant FEE_PRECISION = 100_000; bytes32 constant FEE_STORAGE_POSITION = keccak256("com.enterdao.landworks.fee"); event SetTokenPayment(address indexed _token, bool _status); event SetFee(address indexed _token, uint256 _fee); struct FeeStorage { // Supported tokens as a form of payment EnumerableSet.AddressSet tokenPayments; // Protocol fee percentages for tokens mapping(address => uint256) feePercentages; // Assets' rent fees mapping(uint256 => mapping(address => uint256)) assetRentFees; // Protocol fees for tokens mapping(address => uint256) protocolFees; } function feeStorage() internal pure returns (FeeStorage storage fs) { bytes32 position = FEE_STORAGE_POSITION; assembly { fs.slot := position } } function distributeFees( uint256 _assetId, address _token, uint256 _amount ) internal returns(uint256, uint256) { LibFee.FeeStorage storage fs = feeStorage(); uint256 protocolFee = (_amount * fs.feePercentages[_token]) / FEE_PRECISION; uint256 rentFee = _amount - protocolFee; fs.assetRentFees[_assetId][_token] += rentFee; fs.protocolFees[_token] += protocolFee; return (rentFee, protocolFee); } function clearAccumulatedRent(uint256 _assetId, address _token) internal returns (uint256) { LibFee.FeeStorage storage fs = feeStorage(); uint256 amount = fs.assetRentFees[_assetId][_token]; fs.assetRentFees[_assetId][_token] = 0; return amount; } function clearAccumulatedProtocolFee(address _token) internal returns (uint256) { LibFee.FeeStorage storage fs = feeStorage(); uint256 amount = fs.protocolFees[_token]; fs.protocolFees[_token] = 0; return amount; } function setFeePercentage(address _token, uint256 _feePercentage) internal { LibFee.FeeStorage storage fs = feeStorage(); require( _feePercentage < FEE_PRECISION, "_feePercentage exceeds or equal to feePrecision" ); fs.feePercentages[_token] = _feePercentage; emit SetFee(_token, _feePercentage); } function setTokenPayment(address _token, bool _status) internal { FeeStorage storage fs = feeStorage(); if (_status) { require(fs.tokenPayments.add(_token), "_token already added"); } else { require(fs.tokenPayments.remove(_token), "_token not found"); } emit SetTokenPayment(_token, _status); } function supportsTokenPayment(address _token) internal view returns (bool) { return feeStorage().tokenPayments.contains(_token); } function totalTokenPayments() internal view returns (uint256) { return feeStorage().tokenPayments.length(); } function tokenPaymentAt(uint256 _index) internal view returns (address) { return feeStorage().tokenPayments.at(_index); } function protocolFeeFor(address _token) internal view returns (uint256) { return feeStorage().protocolFees[_token]; } function assetRentFeesFor(uint256 _assetId, address _token) internal view returns (uint256) { return feeStorage().assetRentFees[_assetId][_token]; } function feePercentage(address _token) internal view returns (uint256) { return feeStorage().feePercentages[_token]; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /// @title LibTransfer /// @notice Contains helper methods for interacting with ETH, /// ERC-20 and ERC-721 transfers. Serves as a wrapper for all /// transfers. library LibTransfer { using SafeERC20 for IERC20; address constant ETHEREUM_PAYMENT_TOKEN = address(1); /// @notice Transfers tokens from contract to a recipient /// @dev If token is 0x0000000000000000000000000000000000000001, an ETH transfer is done /// @param _token The target token /// @param _recipient The recipient of the transfer /// @param _amount The amount of the transfer function safeTransfer( address _token, address _recipient, uint256 _amount ) internal { if (_token == ETHEREUM_PAYMENT_TOKEN) { payable(_recipient).transfer(_amount); } else { IERC20(_token).safeTransfer(_recipient, _amount); } } function safeTransferFrom( address _token, address _from, address _to, uint256 _amount ) internal { IERC20(_token).safeTransferFrom(_from, _to, _amount); } function erc721SafeTransferFrom( address _token, address _from, address _to, uint256 _tokenId ) internal { IERC721(_token).safeTransferFrom(_from, _to, _tokenId); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; library LibMarketplace { using EnumerableSet for EnumerableSet.AddressSet; bytes32 constant MARKETPLACE_STORAGE_POSITION = keccak256("com.enterdao.landworks.marketplace"); enum AssetStatus { Listed, Delisted } struct Asset { uint256 metaverseId; address metaverseRegistry; uint256 metaverseAssetId; address paymentToken; uint256 minPeriod; uint256 maxPeriod; uint256 maxFutureTime; uint256 pricePerSecond; uint256 totalRents; AssetStatus status; } struct Rent { address renter; uint256 start; uint256 end; } struct MetaverseRegistry { // Name of the Metaverse string name; // Supported registries EnumerableSet.AddressSet registries; } struct MarketplaceStorage { // Supported metaverse registries mapping(uint256 => MetaverseRegistry) metaverseRegistries; // Assets by ID mapping(uint256 => Asset) assets; // Rents by asset ID mapping(uint256 => mapping(uint256 => Rent)) rents; } function marketplaceStorage() internal pure returns (MarketplaceStorage storage ms) { bytes32 position = MARKETPLACE_STORAGE_POSITION; assembly { ms.slot := position } } function setMetaverseName(uint256 _metaverseId, string memory _name) internal { marketplaceStorage().metaverseRegistries[_metaverseId].name = _name; } function metaverseName(uint256 _metaverseId) internal view returns (string memory) { return marketplaceStorage().metaverseRegistries[_metaverseId].name; } function setRegistry( uint256 _metaverseId, address _registry, bool _status ) internal { LibMarketplace.MetaverseRegistry storage mr = marketplaceStorage() .metaverseRegistries[_metaverseId]; if (_status) { require(mr.registries.add(_registry), "_registry already added"); } else { require(mr.registries.remove(_registry), "_registry not found"); } } function supportsRegistry(uint256 _metaverseId, address _registry) internal view returns (bool) { return marketplaceStorage() .metaverseRegistries[_metaverseId] .registries .contains(_registry); } function totalRegistries(uint256 _metaverseId) internal view returns (uint256) { return marketplaceStorage() .metaverseRegistries[_metaverseId] .registries .length(); } function registryAt(uint256 _metaverseId, uint256 _index) internal view returns (address) { return marketplaceStorage() .metaverseRegistries[_metaverseId] .registries .at(_index); } function addRent( uint256 _assetId, address _renter, uint256 _start, uint256 _end ) internal returns (uint256) { LibMarketplace.MarketplaceStorage storage ms = marketplaceStorage(); uint256 newRentId = ms.assets[_assetId].totalRents + 1; ms.assets[_assetId].totalRents = newRentId; ms.rents[_assetId][newRentId] = LibMarketplace.Rent({ renter: _renter, start: _start, end: _end }); return newRentId; } function assetAt(uint256 _assetId) internal view returns (Asset memory) { return marketplaceStorage().assets[_assetId]; } function rentAt(uint256 _assetId, uint256 _rentId) internal view returns (Rent memory) { return marketplaceStorage().rents[_assetId][_rentId]; } } // 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/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/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 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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; } }
Returns whether `spender` is allowed to consume `tokenId`. Requirements: - `tokenId` must exist./
function isConsumerOf(address spender, uint256 tokenId) internal view returns (bool) { return spender == consumerOf(tokenId); }
224,323
./full_match/137/0x0E27c5B54F82c0eC851a499a619E179F4893D2d3/sources/contracts/MasterChefV2.sol
Withdraw LP tokens from MasterChefV2.
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.accHorusPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safehorusTransfer(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.accHorusPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
4,672,197
./partial_match/1/0x089504de59277A3D085ad41F0d87E48581589d49/sources/MeebitsResolver.sol
Returns the address associated with an ENS node. node The ENS node to query. return The associated address./
function addr( bytes32 node ) public view virtual override returns (address payable) { bytes memory a = addr(node, COIN_TYPE_ETH); if (a.length == 0) { return payable(0); } return bytesToAddress(a); }
3,953,610
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'TestToken' token contract // // Deployed to : main net // Symbol : L51TT // Name : Lab51TestToken // Total supply: 100000000 // Decimals : 18 // // // // (c) 051 Labs // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(int a, int b) public pure returns (int c) { c = a + b; require(c >= a); } function safeSub(int a, int b) public pure returns (int c) { require(b <= a); c = a - b; } function safeMul(int a, int b) public pure returns (int c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(int a, int b) public pure returns (int c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (int); function balanceOf(address tokenOwner) public constant returns (int balance); function allowance(address tokenOwner, address spender) public constant returns (int remaining); function transfer(address to, int tokens) public returns (bool success); function approve(address spender, int tokens) public returns (bool success); function transferFrom(address from, address to, int tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, int tokens); event Approval(address indexed tokenOwner, address indexed spender, int tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, int256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract Lab51TestToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; int8 public decimals; int public _totalSupply; mapping(address => int) balances; mapping(address => mapping(address => int)) allowed; //- In mappingg The entire storage space is virtually initialized to 0 //- -2 => operation inside whitelist implemented or result is unknown //- -1 => operation inside whitelist not permitted //- 0 => NOT existing in whitelist AKA NOT Allowed //- 1 => exist in whitelist and allowed //- 2 => exist in whitelist but in quarantine //- 3 => exist in whitelist but suspended //- 4 => exist in whitelist but disabled //- 5 => exist in whitelist but erased mapping(address => int) private _whitelist; //- modifier onlyOwner() - Prevents function from running if it is called by anyone other than the owner. function Subscribe(address addr) onlyOwner public returns (bool) { _whitelist[addr] = 1; return true; } //- modifier onlyOwner() - Prevents function from running if it is called by anyone other than the owner. function SetSubscriptionTo(address addr, int v) onlyOwner public returns (bool) { _whitelist[addr] = v; return true; } function IsAllowed(address addr) constant private returns (int) { return _whitelist[addr]; } //- modifier onlyOwner() - Prevents function from running if it is called by anyone other than the owner. function CheckIfIsAllowed(address addr) onlyOwner constant public returns (int) { return IsAllowed(addr); } // @dev Function to mint tokens // @param _to The address that will receive the minted tokens. // @param _amount The amount of tokens to mint. // @return A boolean that indicates if the operation was successful. function mint( address _to, int amount ) onlyOwner public returns (bool) { _totalSupply = _totalSupply + amount; balances[_to] = balances[_to] + amount; return true; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Lab51TestToken() public { symbol = "L51TT"; name = "Lab51 Test Token"; decimals = 18; _totalSupply = -100000000000000000000000000; balances[0x8aD2a62AE1EDDAB27322541E6602466f61428e8B] = _totalSupply; Transfer(address(0), 0x8aD2a62AE1EDDAB27322541E6602466f61428e8B, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (int) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (int balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, int tokens) public returns (bool success) { balances[msg.sender] = safeAdd (balances[msg.sender], tokens); balances[to] = safeSub(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, int tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, int tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (int remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, int tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, int tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
------------------------------------------------------------------------ Total supply ------------------------------------------------------------------------
function totalSupply() public constant returns (int) { return _totalSupply - balances[address(0)]; }
13,529,851
pragma solidity ^0.5.9; import "./DelightInterface.sol"; import "./DelightBase.sol"; import "./DelightInfoInterface.sol"; import "./DelightKnightItemInterface.sol"; import "./DelightBuildingManager.sol"; import "./DelightArmyManager.sol"; import "./DelightItemManager.sol"; import "./Util/SafeMath.sol"; contract Delight is DelightInterface, DelightBase { using SafeMath for uint; uint constant private ORDER_BUILD = 1; uint constant private ORDER_UPGRADE_HQ = 2; uint constant private ORDER_CREATE_ARMY = 3; uint constant private ORDER_CREATE_ITEM = 4; uint constant private ORDER_ATTACH_ITEM = 5; uint constant private ORDER_ATTACH_KNIGHT_ITEM = 6; uint constant private ORDER_MOVE_ONE = 7; uint constant private ORDER_MOVE_AND_ATTACK = 8; uint constant private ORDER_RANGED_ATTACK = 9; // Knight's default buff damage // 기사의 기본 버프 데미지 uint constant private KNIGHT_DEFAULT_BUFF_DAMAGE = 5; DelightInfoInterface private info; DelightKnightItemInterface private knightItem; DelightBuildingManager private buildingManager; DelightArmyManager private armyManager; DelightItemManager private itemManager; constructor( DelightInfoInterface _info, DelightKnightItemInterface _knightItem, DelightBuildingManager _buildingManager, DelightArmyManager _armyManager, DelightItemManager _itemManager ) public { // information // 정보 info = _info; // knight item // 기사 아이템 knightItem = _knightItem; // managers // 관리자들 buildingManager = _buildingManager; armyManager = _armyManager; itemManager = _itemManager; // Big Bang! history.push(Record({ order : 99, account : address(0), enemy : address(0), param1 : 0, param2 : 0, param3 : 0, param4 : 0, kill : 0, death : 0, isWin : false, time : now })); } Record[] private history; uint private lastAttackCol; uint private lastAttackRow; // Returns the total number of records. // 기록의 총 개수를 반환합니다. function getRecordCount() view external returns (uint) { return history.length; } // Returns a record. // 기록을 반환합니다. function getRecord(uint recordId) view external returns ( uint order, address account, address enemy, uint param1, uint param2, uint param3, uint param4, uint kill, uint death, bool isWin, uint time ) { Record memory record = history[recordId]; return ( record.order, record.account, record.enemy, record.param1, record.param2, record.param3, record.param4, record.kill, record.death, record.isWin, record.time ); } // Gets the total damage of an army. // 전체 데미지를 가져옵니다. function getTotalDamage(uint distance, uint[] memory armyIds, uint buildingBuffDamage) view public returns (uint totalDamage) { ( , , uint knightItemId, , , , ) = armyManager.getArmyInfo(armyIds[UNIT_KNIGHT]); // Calculates the total damage. // 총 데미지를 계산합니다. for (uint i = 0; i < UNIT_KIND_COUNT; i += 1) { ( uint armyUnitKind, uint armyUnitCount, uint armyKnightItemId, , , , ) = armyManager.getArmyInfo(armyIds[i]); if ( // The number of units must be bigger than 0. // 유닛의 개수는 0보다 커야합니다. armyUnitCount > 0 && // Checks if the unit can reach the distance. // 이동이 가능한 거리인지 확인합니다. distance <= info.getUnitMovableDistance(armyUnitKind)) { // Adds the total damage from the friendly army. // 아군의 데미지 추가 totalDamage = totalDamage.add( info.getUnitDamage(armyUnitKind).add( // If the unit's a knight, add the knight item's damage . // 기사인 경우 기사 아이템의 데미지를 추가합니다. i == UNIT_KNIGHT ? knightItem.getItemDamage(armyKnightItemId) : ( // If the unit's not a knight, add a knight's buff damage . // 기사가 아닌 경우 기사의 버프 데미지를 추가합니다. armyIds[UNIT_KNIGHT] != 0 && distance <= info.getUnitMovableDistance(UNIT_KNIGHT) ? KNIGHT_DEFAULT_BUFF_DAMAGE + knightItem.getItemBuffDamage(knightItemId) : 0 ) ).add( // 이동 거리가 0일때만 병사 위치의 건물의 버프 데미지를 가져옵니다. distance == 0 ? buildingBuffDamage : 0 ).mul(armyUnitCount) ); } } return totalDamage; } // Gets the total ranged damage. // 전체 원거리 데미지를 가져옵니다. function getTotalRangedDamage(uint distance, uint[] memory armyIds, uint buildingBuffDamage) view public returns (uint) { uint totalDamage = 0; ( , , uint knightItemId, , , , ) = armyManager.getArmyInfo(armyIds[UNIT_KNIGHT]); // Calcaultes the total damage. // 총 데미지를 계산합니다. for (uint i = 0; i < UNIT_KIND_COUNT; i += 1) { ( uint armyUnitKind, uint armyUnitCount, uint armyKnightItemId, , , , ) = armyManager.getArmyInfo(armyIds[i]); if ( // The number of units must be more than 0. // 유닛의 개수가 0개 이상이어야 합니다. armyUnitCount > 0 && // Checks if the unit can reach the distance. // 공격이 가능한 거리인지 확인합니다. distance <= info.getUnitAttackableDistance(armyUnitKind)) { // Adds the damage from the friendly army. // 아군의 데미지 추가 totalDamage = totalDamage.add( info.getUnitDamage(armyUnitKind).add( // If the unit's a knight, adds the knight item's damage // 기사인 경우 기사 아이템의 공격력을 추가합니다. i == UNIT_KNIGHT ? knightItem.getItemDamage(armyKnightItemId) : ( // If the unit's not a knight, adds a knight's buff damage // 기사가 아닌 경우 기사의 버프 데미지를 추가합니다. armyIds[UNIT_KNIGHT] != 0 ? KNIGHT_DEFAULT_BUFF_DAMAGE + knightItem.getItemBuffDamage(knightItemId) : 0 ) ).add( // 병사 위치의 건물의 버프 데미지를 가져옵니다. buildingBuffDamage ).mul(armyUnitCount) ); } } return totalDamage; } // Army moves and attacks if there's enemy in the destination tile. // 부대를 이동시키고, 해당 지역에 적이 있으면 공격합니다. function moveAndAttack(uint fromCol, uint fromRow, uint toCol, uint toRow, Record memory record, uint distance, uint retryCount) private { // 위치가 달라야 합니다. require(fromCol != toCol || fromRow != toRow); // 범위 체크 require(fromCol < COL_RANGE && fromRow < ROW_RANGE); require(toCol < COL_RANGE && toRow < ROW_RANGE); // 부대의 소유주인지 확인합니다. require(msg.sender == armyManager.getPositionOwner(fromCol, fromRow)); // 아무도 없는 곳이거나 아군이면 부대를 이동시킵니다. if (record.enemy == address(0) || record.enemy == msg.sender) { armyManager.moveArmy(fromCol, fromRow, toCol, toRow); // 적군의 건물이 존재하면 파괴합니다. if (buildingManager.getPositionBuildingId(toCol, toRow) != 0 && buildingManager.getPositionBuildingOwner(toCol, toRow) != msg.sender) { armyManager.destroyBuilding(history.length, toCol, toRow); armyManager.win(history.length, msg.sender); record.isWin = true; } } // If there's a hostile army in the destination, attack. // 적군이면 전투를 개시합니다. else { // 마지막 공격 위치 저장 lastAttackCol = toCol; lastAttackRow = toRow; uint totalDamage = getTotalDamage(distance, armyManager.getPositionArmyIds(fromCol, fromRow), buildingManager.getBuildingBuffDamage(fromCol, fromRow)); uint totalEnemyDamage = getTotalDamage(0, armyManager.getPositionArmyIds(toCol, toRow), buildingManager.getBuildingBuffDamage(toCol, toRow)); uint kill = armyManager.attack(history.length, totalDamage, 0, toCol, toRow); uint death = armyManager.attack(history.length, totalEnemyDamage, distance, fromCol, fromRow); record.kill = record.kill.add(kill); record.death = record.death.add(death); // 아무 변화가 없는 경우에는 공격자가 승리합니다. if (kill == 0 && death == 0) { armyManager.win(history.length, msg.sender); record.isWin = true; } // 한번의 공격으로 전투가 끝나지 않았을 때 else if (armyManager.getTotalUnitCount(distance, fromCol, fromRow) > 0 && armyManager.getTotalUnitCount(0, toCol, toRow) > 0) { // 재시도 횟수가 5번을 초과한 경우, 공격자가 승리합니다. if (retryCount == 5) { armyManager.win(history.length, msg.sender); record.isWin = true; } // 재공격 else { moveAndAttack(fromCol, fromRow, toCol, toRow, record, distance, retryCount + 1); } } // If the enemy building is captured, move the soldiers. // 적진을 점령했다면, 병사들을 이동시킵니다. else if (armyManager.getPositionOwner(toCol, toRow) == address(0)) { armyManager.moveArmy(fromCol, fromRow, toCol, toRow); armyManager.destroyBuilding(history.length, toCol, toRow); armyManager.win(history.length, msg.sender); record.isWin = true; } // enemy won // 상대가 승리했습니다. else { armyManager.win(history.length, record.enemy); } } } // 단일 부대를 이동시킵니다. function moveOne(uint armyId, uint unitCount, uint toCol, uint toRow) private { // 범위 체크 require(toCol < COL_RANGE && toRow < ROW_RANGE); // 적군의 건물이 존재하면 이동이 불가능합니다. require(buildingManager.getPositionBuildingId(toCol, toRow) == 0 || buildingManager.getPositionBuildingOwner(toCol, toRow) == msg.sender); // The number of units must be bigger than 0. // 유닛의 개수는 0보다 커야합니다. require(unitCount > 0); ( uint armyUnitKind, uint armyUnitCount, , uint armyCol, uint armyRow, address armyOwner, ) = armyManager.getArmyInfo(armyId); // 위치가 달라야 합니다. require(armyCol != toCol || armyRow != toRow); // 부대의 소유주인지 확인합니다. require(msg.sender == armyOwner); // 이동할 유닛의 개수가 부대에 존재하는 유닛의 개수보다 적거나 같아야합니다. require(unitCount <= armyUnitCount); // Check if the unit can reach the distance. // 이동이 가능한 거리인지 확인합니다. require((armyCol < toCol ? toCol - armyCol : armyCol - toCol) + (armyRow < toRow ? toRow - armyRow : armyRow - toRow) <= info.getUnitMovableDistance(armyUnitKind)); address enemy = armyManager.getPositionOwner(toCol, toRow); // 아무도 없는 곳이거나 아군인 경우에만 가능합니다. require(enemy == address(0) || enemy == msg.sender); armyManager.moveArmyOne(armyManager.getTotalUnitCount(0, toCol, toRow), armyId, unitCount, toCol, toRow); } // Range unit attacks a given tile. // 원거리 유닛으로 특정 지역을 공격합니다. function rangedAttack(uint fromCol, uint fromRow, uint toCol, uint toRow, Record memory record) private { // 위치가 달라야 합니다. require(fromCol != toCol || fromRow != toRow); // 범위 체크 require(fromCol < COL_RANGE && fromRow < ROW_RANGE); require(toCol < COL_RANGE && toRow < ROW_RANGE); // 부대의 소유주인지 확인합니다. require(msg.sender == armyManager.getPositionOwner(fromCol, fromRow)); address enemy = armyManager.getPositionOwner(toCol, toRow); // Cannot attack friendly force. // 아군은 공격할 수 없습니다. require(enemy != msg.sender); // Calculates the distance. // 거리 계산 uint distance = (fromCol < toCol ? toCol - fromCol : fromCol - toCol) + (fromRow < toRow ? toRow - fromRow : fromRow - toRow); uint totalDamage = getTotalRangedDamage(distance, armyManager.getPositionArmyIds(fromCol, fromRow), buildingManager.getBuildingBuffDamage(fromCol, fromRow)); uint totalEnemyDamage = getTotalRangedDamage(distance, armyManager.getPositionArmyIds(toCol, toRow), buildingManager.getBuildingBuffDamage(toCol, toRow)); // 원거리 공격합니다. record.enemy = enemy; record.kill = armyManager.attack(0, totalDamage, 0, toCol, toRow); record.death = armyManager.attack(0, totalEnemyDamage, 0, fromCol, fromRow); } // Executes the order que. // 명령 큐를 실행합니다. function runOrderQueue(uint[] calldata orders, uint[] calldata params1, uint[] calldata params2, uint[] calldata params3, uint[] calldata params4) external { require(orders.length > 0); for (uint i = 0; i < orders.length; i += 1) { Record memory record = Record({ order : orders[i], account : msg.sender, enemy : address(0), param1 : params1[i], param2 : params2[i], param3 : params3[i], param4 : params4[i], kill : 0, death : 0, isWin : false, time : now }); // Build buildings. // 건물을 짓습니다. if (orders[i] == ORDER_BUILD) { buildingManager.build(msg.sender, params1[i], params2[i], params3[i]); } // Upgrades headquarters // 본부를 업그레이드합니다. else if (orders[i] == ORDER_UPGRADE_HQ) { buildingManager.upgradeHQ(msg.sender, params1[i]); } // Creates armies. // 부대를 생산합니다. else if (orders[i] == ORDER_CREATE_ARMY) { buildingManager.createArmy(msg.sender, params1[i], params2[i]); } // Creates items. // 아이템을 생산합니다. else if (orders[i] == ORDER_CREATE_ITEM) { itemManager.createItem(msg.sender, params1[i], params2[i]); } // Equips items. // 아이템을 장착합니다. else if (orders[i] == ORDER_ATTACH_ITEM) { armyManager.attachItem(msg.sender, params1[i], params2[i], params3[i]); } // Equips knight items. // 아이템을 장착합니다. else if (orders[i] == ORDER_ATTACH_KNIGHT_ITEM) { armyManager.attachKnightItem(msg.sender, params1[i], params2[i]); } // 단일 부대를 이동시킵니다. else if (orders[i] == ORDER_MOVE_ONE) { moveOne(params1[i], params2[i], params3[i], params4[i]); } // Armies move and attack. // 부대를 이동시키고, 해당 지역에 적이 있으면 공격합니다. else if (orders[i] == ORDER_MOVE_AND_ATTACK) { // 거리 계산 (재전투 시 중복 계산을 방지하기 위해 여기서 계산합니다.) uint distance = (params1[i] < params3[i] ? params3[i] - params1[i] : params1[i] - params3[i]) + (params2[i] < params4[i] ? params4[i] - params2[i] : params2[i] - params4[i]); record.enemy = armyManager.getPositionOwner(params3[i], params4[i]); moveAndAttack(params1[i], params2[i], params3[i], params4[i], record, distance, 0); } // Ranged units attack given tiles. // 원거리 유닛으로 특정 지역을 공격합니다. else if (orders[i] == ORDER_RANGED_ATTACK) { // 이미 원거리 공격 명령이 내려진 부대라면 거부합니다. for (uint j = 0; j < i; j += 1) { if (orders[j] == ORDER_RANGED_ATTACK && params1[j] == params1[i] && params2[j] == params2[i]) { revert(); } } rangedAttack(params1[i], params2[i], params3[i], params4[i], record); } else { revert(); } // Adds a record. // 기록을 추가합니다. uint recordId = history.push(record).sub(1); // Emits the event. // 이벤트 발생 emit NewRecord(msg.sender, recordId); } } // 마지막 공격 위치를 가져옵니다. function getLastAttackPosition() view external returns (uint col, uint row) { return ( lastAttackCol, lastAttackRow ); } }
Gets the total damage of an army. 전체 데미지를 가져옵니다. Calculates the total damage. 총 데미지를 계산합니다. The number of units must be bigger than 0. 유닛의 개수는 0보다 커야합니다. Checks if the unit can reach the distance. 이동이 가능한 거리인지 확인합니다. Adds the total damage from the friendly army. 아군의 데미지 추가 If the unit's a knight, add the knight item's damage . 기사인 경우 기사 아이템의 데미지를 추가합니다. If the unit's not a knight, add a knight's buff damage . 기사가 아닌 경우 기사의 버프 데미지를 추가합니다. 이동 거리가 0일때만 병사 위치의 건물의 버프 데미지를 가져옵니다.
function getTotalDamage(uint distance, uint[] memory armyIds, uint buildingBuffDamage) view public returns (uint totalDamage) { ( , , uint knightItemId, , , , ) = armyManager.getArmyInfo(armyIds[UNIT_KNIGHT]); for (uint i = 0; i < UNIT_KIND_COUNT; i += 1) { ( uint armyUnitKind, uint armyUnitCount, uint armyKnightItemId, , , , ) = armyManager.getArmyInfo(armyIds[i]); if ( armyUnitCount > 0 && distance <= info.getUnitMovableDistance(armyUnitKind)) { totalDamage = totalDamage.add( info.getUnitDamage(armyUnitKind).add( i == UNIT_KNIGHT ? knightItem.getItemDamage(armyKnightItemId) : ( armyIds[UNIT_KNIGHT] != 0 && distance <= info.getUnitMovableDistance(UNIT_KNIGHT) ? KNIGHT_DEFAULT_BUFF_DAMAGE + knightItem.getItemBuffDamage(knightItemId) : 0 ) ).add( distance == 0 ? buildingBuffDamage : 0 ).mul(armyUnitCount) ); } } return totalDamage; }
12,739,325
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; /* ██████ ██████ ██ ██ ███ ██ ██████ ██ ██ ██ ██ ██ ████ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███████ ██████ ██████ ██ ████ ██████ */ import {IERC2981Upgradeable, IERC165Upgradeable} from '@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol'; import {ERC721Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import {LibUintToString} from './LibUintToString.sol'; import {CountersUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol'; import {ArtistCreator} from './ArtistCreator.sol'; import {ECDSA} from '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; /// @title Artist /// @author SoundXYZ - @gigamesh & @vigneshka /// @notice This contract is used to create & sell song NFTs for the artist who owns the contract. /// @dev Started as a fork of Mirror's Editions.sol https://github.com/mirror-xyz/editions-v1/blob/main/contracts/Editions.sol contract ArtistV3 is ERC721Upgradeable, IERC2981Upgradeable, OwnableUpgradeable { // ================================ // TYPES // ================================ using LibUintToString for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; using ECDSA for bytes32; enum TimeType { START, END } // ============ Structs ============ struct Edition { // The account that will receive sales revenue. address payable fundingRecipient; // The price at which each token will be sold, in ETH. uint256 price; // The number of tokens sold so far. uint32 numSold; // The maximum number of tokens that can be sold. uint32 quantity; // Royalty amount in bps uint32 royaltyBPS; // start timestamp of auction (in seconds since unix epoch) uint32 startTime; // end timestamp of auction (in seconds since unix epoch) uint32 endTime; // quantity of permissioned tokens uint32 permissionedQuantity; // whitelist signer address address signerAddress; } // ================================ // STORAGE // ================================ string internal baseURI; CountersUpgradeable.Counter private atTokenId; // DEPRECATED IN V3 CountersUpgradeable.Counter private atEditionId; // Mapping of edition id to descriptive data. mapping(uint256 => Edition) public editions; // <DEPRECATED IN V3> Mapping of token id to edition id. mapping(uint256 => uint256) private _tokenToEdition; // The amount of funds that have been deposited for a given edition. mapping(uint256 => uint256) public depositedForEdition; // The amount of funds that have already been withdrawn for a given edition. mapping(uint256 => uint256) public withdrawnForEdition; // The permissioned typehash (used for checking signature validity) bytes32 private constant PERMISSIONED_SALE_TYPEHASH = keccak256('EditionInfo(address contractAddress,address buyerAddress,uint256 editionId)'); bytes32 private immutable DOMAIN_SEPARATOR; // ================================ // EVENTS // ================================ event EditionCreated( uint256 indexed editionId, address fundingRecipient, uint256 price, uint32 quantity, uint32 royaltyBPS, uint32 startTime, uint32 endTime, uint32 permissionedQuantity, address signerAddress ); event EditionPurchased( uint256 indexed editionId, uint256 indexed tokenId, // `numSold` at time of purchase represents the "serial number" of the NFT. uint32 numSold, // The account that paid for and received the NFT. address indexed buyer ); event AuctionTimeSet(TimeType timeType, uint256 editionId, uint32 indexed newTime); event SignerAddressSet(uint256 editionId, address indexed signerAddress); event PermissionedQuantitySet(uint256 editionId, uint32 permissionedQuantity); // ================================ // PUBLIC & EXTERNAL WRITABLE FUNCTIONS // ================================ /// @notice Contract constructor constructor() { DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256('EIP712Domain(uint256 chainId)'), block.chainid)); } /// @notice Initializes the contract /// @param _owner Owner of edition /// @param _name Name of artist function initialize( address _owner, uint256 _artistId, string memory _name, string memory _symbol, string memory _baseURI ) public initializer { __ERC721_init(_name, _symbol); __Ownable_init(); // Set ownership to original sender of contract call transferOwnership(_owner); // E.g. https://sound.xyz/api/metadata/[artistId]/ baseURI = string(abi.encodePacked(_baseURI, _artistId.toString(), '/')); // Set edition id start to be 1 not 0 atEditionId.increment(); } /// @notice Creates a new edition. /// @param _fundingRecipient The account that will receive sales revenue. /// @param _price The price at which each token will be sold, in ETH. /// @param _quantity The maximum number of tokens that can be sold. /// @param _royaltyBPS The royalty amount in bps. /// @param _startTime The start time of the auction, in seconds since unix epoch. /// @param _endTime The end time of the auction, in seconds since unix epoch. /// @param _permissionedQuantity The quantity of tokens that require a signature to buy. /// @param _signerAddress signer address. function createEdition( address payable _fundingRecipient, uint256 _price, uint32 _quantity, uint32 _royaltyBPS, uint32 _startTime, uint32 _endTime, uint32 _permissionedQuantity, address _signerAddress ) external onlyOwner { require(_permissionedQuantity < _quantity + 1, 'Permissioned quantity too big'); require(_quantity > 0, 'Must set quantity'); require(_fundingRecipient != address(0), 'Must set fundingRecipient'); require(_endTime > _startTime, 'End time must be greater than start time'); if (_permissionedQuantity > 0) { require(_signerAddress != address(0), 'Signer address cannot be 0'); } editions[atEditionId.current()] = Edition({ fundingRecipient: _fundingRecipient, price: _price, numSold: 0, quantity: _quantity, royaltyBPS: _royaltyBPS, startTime: _startTime, endTime: _endTime, permissionedQuantity: _permissionedQuantity, signerAddress: _signerAddress }); emit EditionCreated( atEditionId.current(), _fundingRecipient, _price, _quantity, _royaltyBPS, _startTime, _endTime, _permissionedQuantity, _signerAddress ); atEditionId.increment(); } /// @notice Creates a new token for the given edition, and assigns it to the buyer /// @param _editionId The id of the edition to purchase /// @param _signature A signed message for authorizing permissioned purchases function buyEdition(uint256 _editionId, bytes calldata _signature) external payable { // Caching variables locally to reduce reads uint256 price = editions[_editionId].price; uint32 quantity = editions[_editionId].quantity; uint32 numSold = editions[_editionId].numSold; uint32 startTime = editions[_editionId].startTime; uint32 endTime = editions[_editionId].endTime; uint32 permissionedQuantity = editions[_editionId].permissionedQuantity; // Check that the edition exists. Note: this is redundant // with the next check, but it is useful for clearer error messaging. require(quantity > 0, 'Edition does not exist'); // Check that there are still tokens available to purchase. require(numSold < quantity, 'This edition is already sold out.'); // Check that the sender is paying the correct amount. require(msg.value >= price, 'Must send enough to purchase the edition.'); // If the open auction hasn't started... if (startTime > block.timestamp) { // Check that permissioned tokens are still available require( permissionedQuantity > 0 && numSold < permissionedQuantity, 'No permissioned tokens available & open auction not started' ); // Check that the signature is valid. require(getSigner(_signature, _editionId) == editions[_editionId].signerAddress, 'Invalid signer'); } // Don't allow purchases after the end time require(endTime > block.timestamp, 'Auction has ended'); // Create the token id by packing editionId in the top bits uint256 tokenId; unchecked { tokenId = (_editionId << 128) | (numSold + 1); // Increment the number of tokens sold for this edition. editions[_editionId].numSold = numSold + 1; } // If fundingRecipient is the owner (artist's wallet), update the edition's balance & don't send the funds if (editions[_editionId].fundingRecipient == owner()) { // Update the deposited total for the edition depositedForEdition[_editionId] += msg.value; } else { // Send funds to the funding recipient. _sendFunds(editions[_editionId].fundingRecipient, msg.value); } // Mint a new token for the sender, using the `tokenId`. _mint(msg.sender, tokenId); emit EditionPurchased(_editionId, tokenId, editions[_editionId].numSold, msg.sender); } function withdrawFunds(uint256 _editionId) external { // Compute the amount available for withdrawing from this edition. uint256 remainingForEdition = depositedForEdition[_editionId] - withdrawnForEdition[_editionId]; // Set the amount withdrawn to the amount deposited. withdrawnForEdition[_editionId] = depositedForEdition[_editionId]; // Send the amount that was remaining for the edition, to the funding recipient. _sendFunds(editions[_editionId].fundingRecipient, remainingForEdition); } /// @notice Sets the start time for an edition function setStartTime(uint256 _editionId, uint32 _startTime) external onlyOwner { editions[_editionId].startTime = _startTime; emit AuctionTimeSet(TimeType.START, _editionId, _startTime); } /// @notice Sets the end time for an edition function setEndTime(uint256 _editionId, uint32 _endTime) external onlyOwner { editions[_editionId].endTime = _endTime; emit AuctionTimeSet(TimeType.END, _editionId, _endTime); } /// @notice Sets the signature address of an edition function setSignerAddress(uint256 _editionId, address _newSignerAddress) external onlyOwner { require(_newSignerAddress != address(0), 'Signer address cannot be 0'); editions[_editionId].signerAddress = _newSignerAddress; emit SignerAddressSet(_editionId, _newSignerAddress); } /// @notice Sets the permissioned quantity for an edition function setPermissionedQuantity(uint256 _editionId, uint32 _permissionedQuantity) external onlyOwner { // Check that the permissioned quantity is less than the total quantity require(_permissionedQuantity < editions[_editionId].quantity + 1, 'Must not exceed quantity'); // Prevent setting to permissioned quantity when there is no signer address require(editions[_editionId].signerAddress != address(0), 'Edition must have a signer'); editions[_editionId].permissionedQuantity = _permissionedQuantity; emit PermissionedQuantitySet(_editionId, _permissionedQuantity); } // ================================ // VIEW FUNCTIONS // ================================ /// @notice Returns token URI (metadata URL). e.g. https://sound.xyz/api/metadata/[artistId]/[editionId]/[tokenId] /// @dev Concatenate the baseURI, editionId and tokenId, to create URI. function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token'); uint256 editionId = tokenToEdition(_tokenId); return string(abi.encodePacked(baseURI, editionId.toString(), '/', _tokenId.toString())); } /// @notice Returns contract URI used by Opensea. e.g. https://sound.xyz/api/metadata/[artistId]/storefront function contractURI() public view returns (string memory) { return string(abi.encodePacked(baseURI, 'storefront')); } /// @notice Get royalty information for token /// @param _tokenId token id /// @param _salePrice Sale price for the token function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override returns (address fundingRecipient, uint256 royaltyAmount) { uint256 editionId = tokenToEdition(_tokenId); Edition memory edition = editions[editionId]; if (edition.fundingRecipient == address(0x0)) { return (edition.fundingRecipient, 0); } uint256 royaltyBPS = uint256(edition.royaltyBPS); return (edition.fundingRecipient, (_salePrice * royaltyBPS) / 10_000); } /// @notice The total number of tokens created by this contract function totalSupply() external view returns (uint256) { uint256 total = 0; for (uint256 id = 1; id < atEditionId.current(); id++) { total += editions[id].numSold; } return total; } /// @notice Informs other contracts which interfaces this contract supports /// @dev https://eips.ethereum.org/EIPS/eip-165 function supportsInterface(bytes4 _interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) { return type(IERC2981Upgradeable).interfaceId == _interfaceId || ERC721Upgradeable.supportsInterface(_interfaceId); } /// @notice returns the number of editions for this artist function editionCount() external view returns (uint256) { return atEditionId.current() - 1; // because atEditionId is incremented after each edition is created } function tokenToEdition(uint256 _tokenId) public view returns (uint256) { // Check the top bits to see if the edition id is there uint256 editionId = _tokenId >> 128; // If edition ID is 0, then this edition was created before the V3 upgrade if (editionId == 0) { // get edition ID from storage return _tokenToEdition[_tokenId]; } return editionId; } function ownersOfTokenIds(uint256[] calldata _tokenIds) external view returns (address[] memory) { address[] memory owners = new address[](_tokenIds.length); for (uint256 i = 0; i < _tokenIds.length; i++) { owners[i] = ownerOf(_tokenIds[i]); } return owners; } // ================================ // FUNCTIONS - PRIVATE // ================================ /// @notice Sends funds to an address /// @param _recipient The address to send funds to /// @param _amount The amount of funds to send function _sendFunds(address payable _recipient, uint256 _amount) private { require(address(this).balance >= _amount, 'Insufficient balance for send'); (bool success, ) = _recipient.call{value: _amount}(''); require(success, 'Unable to send value: recipient may have reverted'); } /// @notice Gets signer address to validate permissioned purchase /// @param _signature signed message /// @param _editionId edition id /// @return address of signer /// @dev https://eips.ethereum.org/EIPS/eip-712 function getSigner(bytes calldata _signature, uint256 _editionId) private view returns (address) { bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMISSIONED_SALE_TYPEHASH, address(this), msg.sender, _editionId)) ) ); address recoveredAddress = digest.recover(_signature); return recoveredAddress; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981Upgradeable is IERC165Upgradeable { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev 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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 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 onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _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); } uint256[49] private __gap; } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; library LibUintToString { uint256 private constant MAX_UINT256_STRING_LENGTH = 78; uint8 private constant ASCII_DIGIT_OFFSET = 48; /// @dev Converts a `uint256` value to a string. /// @param n The integer to convert. /// @return nstr `n` as a decimal string. function toString(uint256 n) internal pure returns (string memory nstr) { if (n == 0) { return '0'; } // Overallocate memory nstr = new string(MAX_UINT256_STRING_LENGTH); uint256 k = MAX_UINT256_STRING_LENGTH; // Populate string from right to left (lsb to msb). while (n != 0) { assembly { let char := add(ASCII_DIGIT_OFFSET, mod(n, 10)) mstore(add(nstr, k), char) k := sub(k, 1) n := div(n, 10) } } assembly { // Shift pointer over to actual start of string. nstr := add(nstr, k) // Store actual string length. mstore(nstr, sub(MAX_UINT256_STRING_LENGTH, k)) } return nstr; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; /* ██████ ██████ ██ ██ ███ ██ ██████ ██ ██ ██ ██ ██ ████ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███████ ██████ ██████ ██ ████ ██████ */ import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol'; import '@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol'; import '@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol'; import './Artist.sol'; contract ArtistCreator is Initializable, UUPSUpgradeable, OwnableUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; using ECDSAUpgradeable for bytes32; // ============ Storage ============ bytes32 public constant MINTER_TYPEHASH = keccak256('Deployer(address artistWallet)'); CountersUpgradeable.Counter private atArtistId; // address used for signature verification, changeable by owner address public admin; bytes32 public DOMAIN_SEPARATOR; address public beaconAddress; // registry of created contracts address[] public artistContracts; // ============ Events ============ /// Emitted when an Artist is created event CreatedArtist(uint256 artistId, string name, string symbol, address indexed artistAddress); // ============ Functions ============ /// Initializes factory function initialize() public initializer { __Ownable_init_unchained(); // set admin for artist deployment authorization admin = msg.sender; DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256('EIP712Domain(uint256 chainId)'), block.chainid)); // set up beacon with msg.sender as the owner UpgradeableBeacon _beacon = new UpgradeableBeacon(address(new Artist())); _beacon.transferOwnership(msg.sender); beaconAddress = address(_beacon); // Set artist id start to be 1 not 0 atArtistId.increment(); } /// Creates a new artist contract as a factory with a deterministic address /// Important: None of these fields (except the Url fields with the same hash) can be changed after calling /// @param _name Name of the artist function createArtist( bytes calldata signature, string memory _name, string memory _symbol, string memory _baseURI ) public returns (address) { require((getSigner(signature) == admin), 'invalid authorization signature'); BeaconProxy proxy = new BeaconProxy( beaconAddress, abi.encodeWithSelector( Artist(address(0)).initialize.selector, msg.sender, atArtistId.current(), _name, _symbol, _baseURI ) ); // add to registry artistContracts.push(address(proxy)); emit CreatedArtist(atArtistId.current(), _name, _symbol, address(proxy)); atArtistId.increment(); return address(proxy); } /// Get signer address of signature function getSigner(bytes calldata signature) public view returns (address) { require(admin != address(0), 'whitelist not enabled'); // Verify EIP-712 signature by recreating the data structure // that we signed on the client side, and then using that to recover // the address that signed the signature for this data. bytes32 digest = keccak256( abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(MINTER_TYPEHASH, msg.sender))) ); // Use the recover method to see what address was used to create // the signature on this data. // Note that if the digest doesn't exactly match what was signed we'll // get a random recovered address. address recoveredAddress = digest.recover(signature); return recoveredAddress; } /// Sets the admin for authorizing artist deployment /// @param _newAdmin address of new admin function setAdmin(address _newAdmin) external { require(owner() == _msgSender() || admin == _msgSender(), 'invalid authorization'); admin = _newAdmin; } function _authorizeUpgrade(address) internal override onlyOwner {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; 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 Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165Upgradeable.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) 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 // 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 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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol) 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 onlyInitializing { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @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 // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library 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 Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/BeaconProxy.sol) pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../Proxy.sol"; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract BeaconProxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the proxy with `beacon`. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity * constructor. * * Requirements: * * - `beacon` must be a contract with the interface {IBeacon}. */ constructor(address beacon, bytes memory data) payable { assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)); _upgradeBeaconToAndCall(beacon, data, false); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address) { return _getBeacon(); } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_getBeacon()).implementation(); } /** * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { _upgradeBeaconToAndCall(beacon, data, false); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol) pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../../access/Ownable.sol"; import "../../utils/Address.sol"; /** * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their * implementation contract, which is where they will delegate all function calls. * * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon. */ contract UpgradeableBeacon is IBeacon, Ownable { address private _implementation; /** * @dev Emitted when the implementation returned by the beacon is changed. */ event Upgraded(address indexed implementation); /** * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the * beacon. */ constructor(address implementation_) { _setImplementation(implementation_); } /** * @dev Returns the current implementation address. */ function implementation() public view virtual override returns (address) { return _implementation; } /** * @dev Upgrades the beacon to a new implementation. * * Emits an {Upgraded} event. * * Requirements: * * - msg.sender must be the owner of the contract. * - `newImplementation` must be a contract. */ function upgradeTo(address newImplementation) public virtual onlyOwner { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation contract address for this beacon * * Requirements: * * - `newImplementation` must be a contract. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract"); _implementation = newImplementation; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; /* ██████ ██████ ██ ██ ███ ██ ██████ ██ ██ ██ ██ ██ ████ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███████ ██████ ██████ ██ ████ ██████ */ import {IERC2981Upgradeable, IERC165Upgradeable} from '@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol'; import {ERC721Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import {Strings} from './Strings.sol'; import {CountersUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol'; // This contract is a combination of Mirror.xyz's Editions.sol and Zora's SingleEditionMintable.sol /** * @title Artist * @author SoundXYZ */ contract Artist is ERC721Upgradeable, IERC2981Upgradeable, OwnableUpgradeable { // todo (optimization): link Strings as a deployed library using Strings for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; // ============ Structs ============ struct Edition { // The account that will receive sales revenue. address payable fundingRecipient; // The price at which each token will be sold, in ETH. uint256 price; // The number of tokens sold so far. uint32 numSold; // The maximum number of tokens that can be sold. uint32 quantity; // Royalty amount in bps uint32 royaltyBPS; // start timestamp of auction (in seconds since unix epoch) uint32 startTime; // end timestamp of auction (in seconds since unix epoch) uint32 endTime; } // ============ Storage ============ string internal baseURI; CountersUpgradeable.Counter private atTokenId; CountersUpgradeable.Counter private atEditionId; // Mapping of edition id to descriptive data. mapping(uint256 => Edition) public editions; // Mapping of token id to edition id. mapping(uint256 => uint256) public tokenToEdition; // The amount of funds that have been deposited for a given edition. mapping(uint256 => uint256) public depositedForEdition; // The amount of funds that have already been withdrawn for a given edition. mapping(uint256 => uint256) public withdrawnForEdition; // ============ Events ============ event EditionCreated( uint256 indexed editionId, address fundingRecipient, uint256 price, uint32 quantity, uint32 royaltyBPS, uint32 startTime, uint32 endTime ); event EditionPurchased( uint256 indexed editionId, uint256 indexed tokenId, // `numSold` at time of purchase represents the "serial number" of the NFT. uint32 numSold, // The account that paid for and received the NFT. address indexed buyer ); // ============ Methods ============ /** @param _owner Owner of edition @param _name Name of artist */ function initialize( address _owner, uint256 _artistId, string memory _name, string memory _symbol, string memory _baseURI ) public initializer { __ERC721_init(_name, _symbol); __Ownable_init(); // Set ownership to original sender of contract call transferOwnership(_owner); // E.g. https://sound.xyz/api/metadata/[artistId]/ baseURI = string(abi.encodePacked(_baseURI, _artistId.toString(), '/')); // Set token id start to be 1 not 0 atTokenId.increment(); // Set edition id start to be 1 not 0 atEditionId.increment(); } function createEdition( address payable _fundingRecipient, uint256 _price, uint32 _quantity, uint32 _royaltyBPS, uint32 _startTime, uint32 _endTime ) external onlyOwner { editions[atEditionId.current()] = Edition({ fundingRecipient: _fundingRecipient, price: _price, numSold: 0, quantity: _quantity, royaltyBPS: _royaltyBPS, startTime: _startTime, endTime: _endTime }); emit EditionCreated( atEditionId.current(), _fundingRecipient, _price, _quantity, _royaltyBPS, _startTime, _endTime ); atEditionId.increment(); } function buyEdition(uint256 _editionId) external payable { // Check that the edition exists. Note: this is redundant // with the next check, but it is useful for clearer error messaging. require(editions[_editionId].quantity > 0, 'Edition does not exist'); // Check that there are still tokens available to purchase. require(editions[_editionId].numSold < editions[_editionId].quantity, 'This edition is already sold out.'); // Check that the sender is paying the correct amount. require(msg.value >= editions[_editionId].price, 'Must send enough to purchase the edition.'); // Don't allow purchases before the start time require(editions[_editionId].startTime < block.timestamp, "Auction hasn't started"); // Don't allow purchases after the end time require(editions[_editionId].endTime > block.timestamp, 'Auction has ended'); // Mint a new token for the sender, using the `tokenId`. _mint(msg.sender, atTokenId.current()); // Update the deposited total for the edition depositedForEdition[_editionId] += msg.value; // Increment the number of tokens sold for this edition. editions[_editionId].numSold++; // Store the mapping of token id to the edition being purchased. tokenToEdition[atTokenId.current()] = _editionId; emit EditionPurchased(_editionId, atTokenId.current(), editions[_editionId].numSold, msg.sender); atTokenId.increment(); } // ============ Operational Methods ============ function withdrawFunds(uint256 _editionId) external { // Compute the amount available for withdrawing from this edition. uint256 remainingForEdition = depositedForEdition[_editionId] - withdrawnForEdition[_editionId]; // Set the amount withdrawn to the amount deposited. withdrawnForEdition[_editionId] = depositedForEdition[_editionId]; // Send the amount that was remaining for the edition, to the funding recipient. _sendFunds(editions[_editionId].fundingRecipient, remainingForEdition); } function setStartTime(uint256 _editionId, uint32 _startTime) external onlyOwner { editions[_editionId].startTime = _startTime; } function setEndTime(uint256 _editionId, uint32 _endTime) external onlyOwner { editions[_editionId].endTime = _endTime; } // ============ NFT Methods ============ // Returns e.g. https://sound.xyz/api/metadata/[artistId]/[editionId]/[tokenId] function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token'); // Concatenate the components, baseURI, editionId and tokenId, to create URI. return string(abi.encodePacked(baseURI, tokenToEdition[_tokenId].toString(), '/', _tokenId.toString())); } // Returns e.g. https://sound.xyz/api/metadata/[artistId]/storefront function contractURI() public view returns (string memory) { // Concatenate the components, baseURI, editionId and tokenId, to create URI. return string(abi.encodePacked(baseURI, 'storefront')); } // ============ Extensions ================= /** @dev Get token ids for a given edition id @param _editionId edition id */ function getTokenIdsOfEdition(uint256 _editionId) public view returns (uint256[] memory) { uint256[] memory tokenIdsOfEdition = new uint256[](editions[_editionId].numSold); uint256 index = 0; for (uint256 id = 1; id < atTokenId.current(); id++) { if (tokenToEdition[id] == _editionId) { tokenIdsOfEdition[index] = id; index++; } } return tokenIdsOfEdition; } /** @dev Get owners of a given edition id @param _editionId edition id */ function getOwnersOfEdition(uint256 _editionId) public view returns (address[] memory) { address[] memory ownersOfEdition = new address[](editions[_editionId].numSold); uint256 index = 0; for (uint256 id = 1; id < atTokenId.current(); id++) { if (tokenToEdition[id] == _editionId) { ownersOfEdition[index] = ERC721Upgradeable.ownerOf(id); index++; } } return ownersOfEdition; } /** @dev Get royalty information for token @param _editionId edition id @param _salePrice Sale price for the token */ function royaltyInfo(uint256 _editionId, uint256 _salePrice) external view override returns (address fundingRecipient, uint256 royaltyAmount) { Edition memory edition = editions[_editionId]; if (edition.fundingRecipient == address(0x0)) { return (edition.fundingRecipient, 0); } uint256 royaltyBPS = uint256(edition.royaltyBPS); return (edition.fundingRecipient, (_salePrice * royaltyBPS) / 10_000); } function totalSupply() external view returns (uint256) { return atTokenId.current() - 1; // because atTokenId is 1-indexed } function supportsInterface(bytes4 _interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) { return type(IERC2981Upgradeable).interfaceId == _interfaceId || ERC721Upgradeable.supportsInterface(_interfaceId); } // ============ Private Methods ============ function _sendFunds(address payable _recipient, uint256 _amount) private { require(address(this).balance >= _amount, 'Insufficient balance for send'); (bool success, ) = _recipient.call{value: _amount}(''); require(success, 'Unable to send value: recipient may have reverted'); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol) 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 onlyInitializing { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // 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 // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @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 // OpenZeppelin Contracts v4.4.1 (proxy/Proxy.sol) pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.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 ERC1967Upgrade { // 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 StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.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) { Address.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) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.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 StorageSlot.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"); StorageSlot.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 StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.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) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) 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 StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; // This contract is a combination of Mirror.xyz's Editions.sol and Zora's SingleEditionMintable.sol /** * @title Utils * @author SoundXYZ */ library Strings { // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol 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); } } // 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); } }
returns the number of editions for this artist
function editionCount() external view returns (uint256) { }
5,724,114
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; pragma experimental ABIEncoderV2; // File: witnet-ethereum-bridge/contracts/Request.sol /** * @title The serialized form of a Witnet data request */ contract Request { bytes public bytecode; /** * @dev A `Request` is constructed around a `bytes memory` value containing a well-formed Witnet data request serialized * using Protocol Buffers. However, we cannot verify its validity at this point. This implies that contracts using * the WRB should not be considered trustless before a valid Proof-of-Inclusion has been posted for the requests. * The hash of the request is computed in the constructor to guarantee consistency. Otherwise there could be a * mismatch and a data request could be resolved with the result of another. * @param _bytecode Witnet request in bytes. */ constructor(bytes memory _bytecode) { bytecode = _bytecode; } } // File: witnet-ethereum-bridge/contracts/BufferLib.sol /** * @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface * @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will * start with the byte that goes right after the last one in the previous read. * @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some * theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded. */ library BufferLib { struct Buffer { bytes data; uint32 cursor; } // Ensures we access an existing index in an array modifier notOutOfBounds(uint32 index, uint256 length) { require(index < length, "Tried to read from a consumed Buffer (must rewind it first)"); _; } /** * @notice Read and consume a certain amount of bytes from the buffer. * @param _buffer An instance of `BufferLib.Buffer`. * @param _length How many bytes to read and consume from the buffer. * @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position. */ function read(Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) { // Make sure not to read out of the bounds of the original bytes require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading"); // Create a new `bytes memory destination` value bytes memory destination = new bytes(_length); // Early return in case that bytes length is 0 if (_length != 0) { bytes memory source = _buffer.data; uint32 offset = _buffer.cursor; // Get raw pointers for source and destination uint sourcePointer; uint destinationPointer; assembly { sourcePointer := add(add(source, 32), offset) destinationPointer := add(destination, 32) } // Copy `_length` bytes from source to destination memcpy(destinationPointer, sourcePointer, uint(_length)); // Move the cursor forward by `_length` bytes seek(_buffer, _length, true); } return destination; } /** * @notice Read and consume the next byte from the buffer. * @param _buffer An instance of `BufferLib.Buffer`. * @return The next byte in the buffer counting from the cursor position. */ function next(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (bytes1) { // Return the byte at the position marked by the cursor and advance the cursor all at once return _buffer.data[_buffer.cursor++]; } /** * @notice Move the inner cursor of the buffer to a relative or absolute position. * @param _buffer An instance of `BufferLib.Buffer`. * @param _offset How many bytes to move the cursor forward. * @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the * buffer (`true`). * @return The final position of the cursor (will equal `_offset` if `_relative` is `false`). */ // solium-disable-next-line security/no-assign-params function seek(Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) { // Deal with relative offsets if (_relative) { require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking"); _offset += _buffer.cursor; } // Make sure not to read out of the bounds of the original bytes require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking"); _buffer.cursor = _offset; return _buffer.cursor; } /** * @notice Move the inner cursor a number of bytes forward. * @dev This is a simple wrapper around the relative offset case of `seek()`. * @param _buffer An instance of `BufferLib.Buffer`. * @param _relativeOffset How many bytes to move the cursor forward. * @return The final position of the cursor. */ function seek(Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) { return seek(_buffer, _relativeOffset, true); } /** * @notice Move the inner cursor back to the first byte in the buffer. * @param _buffer An instance of `BufferLib.Buffer`. */ function rewind(Buffer memory _buffer) internal pure { _buffer.cursor = 0; } /** * @notice Read and consume the next byte from the buffer as an `uint8`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint8` value of the next byte in the buffer counting from the cursor position. */ function readUint8(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint8 value; assembly { value := mload(add(add(bytesValue, 1), offset)) } _buffer.cursor++; return value; } /** * @notice Read and consume the next 2 bytes from the buffer as an `uint16`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position. */ function readUint16(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint16 value; assembly { value := mload(add(add(bytesValue, 2), offset)) } _buffer.cursor += 2; return value; } /** * @notice Read and consume the next 4 bytes from the buffer as an `uint32`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. */ function readUint32(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint32 value; assembly { value := mload(add(add(bytesValue, 4), offset)) } _buffer.cursor += 4; return value; } /** * @notice Read and consume the next 8 bytes from the buffer as an `uint64`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position. */ function readUint64(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint64 value; assembly { value := mload(add(add(bytesValue, 8), offset)) } _buffer.cursor += 8; return value; } /** * @notice Read and consume the next 16 bytes from the buffer as an `uint128`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position. */ function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint128 value; assembly { value := mload(add(add(bytesValue, 16), offset)) } _buffer.cursor += 16; return value; } /** * @notice Read and consume the next 32 bytes from the buffer as an `uint256`. * @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position. * @param _buffer An instance of `BufferLib.Buffer`. */ function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint256 value; assembly { value := mload(add(add(bytesValue, 32), offset)) } _buffer.cursor += 32; return value; } /** * @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an * `int32`. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16` * use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are * expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. */ function readFloat16(Buffer memory _buffer) internal pure returns (int32) { uint32 bytesValue = readUint16(_buffer); // Get bit at position 0 uint32 sign = bytesValue & 0x8000; // Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15; // Get bits 6 to 15 int32 significand = int32(bytesValue & 0x03ff); // Add 1024 to the fraction if the exponent is 0 if (exponent == 15) { significand |= 0x400; } // Compute `2 ^ exponent · (1 + fraction / 1024)` int32 result = 0; if (exponent >= 0) { result = int32((int256(1 << uint256(int256(exponent))) * 10000 * int256(uint256(int256(significand)) | 0x400)) >> 10); } else { result = int32(((int256(uint256(int256(significand)) | 0x400) * 10000) / int256(1 << uint256(int256(- exponent)))) >> 10); } // Make the result negative if the sign bit is not 0 if (sign != 0) { result *= - 1; } return result; } /** * @notice Copy bytes from one memory address into another. * @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms * of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE). * @param _dest Address of the destination memory. * @param _src Address to the source memory. * @param _len How many bytes to copy. */ // solium-disable-next-line security/no-assign-params function memcpy(uint _dest, uint _src, uint _len) private pure { require(_len > 0, "Cannot copy 0 bytes"); // 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: witnet-ethereum-bridge/contracts/CBOR.sol /** * @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation” * @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize * the gas cost of decoding them into a useful native type. * @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js * TODO: add support for Array (majorType = 4) * TODO: add support for Map (majorType = 5) * TODO: add support for Float32 (majorType = 7, additionalInformation = 26) * TODO: add support for Float64 (majorType = 7, additionalInformation = 27) */ library CBOR { using BufferLib for BufferLib.Buffer; uint32 constant internal UINT32_MAX = type(uint32).max; uint64 constant internal UINT64_MAX = type(uint64).max; struct Value { BufferLib.Buffer buffer; uint8 initialByte; uint8 majorType; uint8 additionalInformation; uint64 len; uint64 tag; } /** * @notice Decode a `CBOR.Value` structure into a native `bool` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `bool` value. */ function decodeBool(Value memory _cborValue) public pure returns(bool) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(_cborValue.majorType == 7, "Tried to read a `bool` value from a `CBOR.Value` with majorType != 7"); if (_cborValue.len == 20) { return false; } else if (_cborValue.len == 21) { return true; } else { revert("Tried to read `bool` from a `CBOR.Value` with len different than 20 or 21"); } } /** * @notice Decode a `CBOR.Value` structure into a native `bytes` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `bytes` value. */ function decodeBytes(Value memory _cborValue) public pure returns(bytes memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT32_MAX) { bytes memory bytesData; // These checks look repetitive but the equivalent loop would be more expensive. uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < UINT32_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < UINT32_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); } } return bytesData; } else { return _cborValue.buffer.read(uint32(_cborValue.len)); } } /** * @notice Decode a `CBOR.Value` structure into a `fixed16` value. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16` * use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128` value. */ function decodeFixed16(Value memory _cborValue) public pure returns(int32) { require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `CBOR.Value` with majorType != 7"); require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `CBOR.Value` with additionalInformation != 25"); return _cborValue.buffer.readFloat16(); } /** * @notice Decode a `CBOR.Value` structure into a native `int128[]` value whose inner values follow the same convention. * as explained in `decodeFixed16`. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128[]` value. */ function decodeFixed16Array(Value memory _cborValue) external pure returns(int32[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int32[] memory array = new int32[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeFixed16(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `int128` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128` value. */ function decodeInt128(Value memory _cborValue) public pure returns(int128) { if (_cborValue.majorType == 1) { uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); return int128(-1) - int128(uint128(length)); } else if (_cborValue.majorType == 0) { // Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer // a uniform API for positive and negative numbers return int128(uint128(decodeUint64(_cborValue))); } revert("Tried to read `int128` from a `CBOR.Value` with majorType not 0 or 1"); } /** * @notice Decode a `CBOR.Value` structure into a native `int128[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128[]` value. */ function decodeInt128Array(Value memory _cborValue) external pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeInt128(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `string` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `string` value. */ function decodeString(Value memory _cborValue) public pure returns(string memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT64_MAX) { bytes memory textData; bool done; while (!done) { uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType); if (itemLength < UINT64_MAX) { textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4)); } else { done = true; } } return string(textData); } else { return string(readText(_cborValue.buffer, _cborValue.len)); } } /** * @notice Decode a `CBOR.Value` structure into a native `string[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `string[]` value. */ function decodeStringArray(Value memory _cborValue) external pure returns(string[] memory) { require(_cborValue.majorType == 4, "Tried to read `string[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); string[] memory array = new string[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeString(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `uint64` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `uint64` value. */ function decodeUint64(Value memory _cborValue) public pure returns(uint64) { require(_cborValue.majorType == 0, "Tried to read `uint64` from a `CBOR.Value` with majorType != 0"); return readLength(_cborValue.buffer, _cborValue.additionalInformation); } /** * @notice Decode a `CBOR.Value` structure into a native `uint64[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `uint64[]` value. */ function decodeUint64Array(Value memory _cborValue) external pure returns(uint64[] memory) { require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); uint64[] memory array = new uint64[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeUint64(item); } return array; } /** * @notice Decode a CBOR.Value structure from raw bytes. * @dev This is the main factory for CBOR.Value instances, which can be later decoded into native EVM types. * @param _cborBytes Raw bytes representing a CBOR-encoded value. * @return A `CBOR.Value` instance containing a partially decoded value. */ function valueFromBytes(bytes memory _cborBytes) external pure returns(Value memory) { BufferLib.Buffer memory buffer = BufferLib.Buffer(_cborBytes, 0); return valueFromBuffer(buffer); } /** * @notice Decode a CBOR.Value structure from raw bytes. * @dev This is an alternate factory for CBOR.Value instances, which can be later decoded into native EVM types. * @param _buffer A Buffer structure representing a CBOR-encoded value. * @return A `CBOR.Value` instance containing a partially decoded value. */ function valueFromBuffer(BufferLib.Buffer memory _buffer) public pure returns(Value memory) { require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value"); uint8 initialByte; uint8 majorType = 255; uint8 additionalInformation; uint64 tag = UINT64_MAX; bool isTagged = true; while (isTagged) { // Extract basic CBOR properties from input bytes initialByte = _buffer.readUint8(); majorType = initialByte >> 5; additionalInformation = initialByte & 0x1f; // Early CBOR tag parsing. if (majorType == 6) { tag = readLength(_buffer, additionalInformation); } else { isTagged = false; } } require(majorType <= 7, "Invalid CBOR major type"); return CBOR.Value( _buffer, initialByte, majorType, additionalInformation, 0, tag); } // Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the // value of the `additionalInformation` argument. function readLength(BufferLib.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) { if (additionalInformation < 24) { return additionalInformation; } if (additionalInformation == 24) { return _buffer.readUint8(); } if (additionalInformation == 25) { return _buffer.readUint16(); } if (additionalInformation == 26) { return _buffer.readUint32(); } if (additionalInformation == 27) { return _buffer.readUint64(); } if (additionalInformation == 31) { return UINT64_MAX; } revert("Invalid length encoding (non-existent additionalInformation value)"); } // Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming // as many bytes as specified by the first byte. function readIndefiniteStringLength(BufferLib.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) { uint8 initialByte = _buffer.readUint8(); if (initialByte == 0xff) { return UINT64_MAX; } uint64 length = readLength(_buffer, initialByte & 0x1f); require(length < UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length"); return length; } // Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness, // but it can be easily casted into a string with `string(result)`. // solium-disable-next-line security/no-assign-params function readText(BufferLib.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) { bytes memory result; for (uint64 index = 0; index < _length; index++) { uint8 value = _buffer.readUint8(); if (value & 0x80 != 0) { if (value < 0xe0) { value = (value & 0x1f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 1; } else if (value < 0xf0) { value = (value & 0x0f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 2; } else { value = (value & 0x0f) << 18 | (_buffer.readUint8() & 0x3f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 3; } } result = abi.encodePacked(result, value); } return result; } } // File: witnet-ethereum-bridge/contracts/Witnet.sol /** * @title A library for decoding Witnet request results * @notice The library exposes functions to check the Witnet request success. * and retrieve Witnet results from CBOR values into solidity types. */ library Witnet { using CBOR for CBOR.Value; /* * STRUCTS */ struct Result { bool success; CBOR.Value cborValue; } /* * ENUMS */ enum ErrorCodes { // 0x00: Unknown error. Something went really bad! Unknown, // Script format errors /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value. SourceScriptNotCBOR, /// 0x02: The CBOR value decoded from a source script is not an Array. SourceScriptNotArray, /// 0x03: The Array value decoded form a source script is not a valid RADON script. SourceScriptNotRADON, /// Unallocated ScriptFormat0x04, ScriptFormat0x05, ScriptFormat0x06, ScriptFormat0x07, ScriptFormat0x08, ScriptFormat0x09, ScriptFormat0x0A, ScriptFormat0x0B, ScriptFormat0x0C, ScriptFormat0x0D, ScriptFormat0x0E, ScriptFormat0x0F, // Complexity errors /// 0x10: The request contains too many sources. RequestTooManySources, /// 0x11: The script contains too many calls. ScriptTooManyCalls, /// Unallocated Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18, Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F, // Operator errors /// 0x20: The operator does not exist. UnsupportedOperator, /// Unallocated Operator0x21, Operator0x22, Operator0x23, Operator0x24, Operator0x25, Operator0x26, Operator0x27, Operator0x28, Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F, // Retrieval-specific errors /// 0x30: At least one of the sources could not be retrieved, but returned HTTP error. HTTP, /// 0x31: Retrieval of at least one of the sources timed out. RetrievalTimeout, /// Unallocated Retrieval0x32, Retrieval0x33, Retrieval0x34, Retrieval0x35, Retrieval0x36, Retrieval0x37, Retrieval0x38, Retrieval0x39, Retrieval0x3A, Retrieval0x3B, Retrieval0x3C, Retrieval0x3D, Retrieval0x3E, Retrieval0x3F, // Math errors /// 0x40: Math operator caused an underflow. Underflow, /// 0x41: Math operator caused an overflow. Overflow, /// 0x42: Tried to divide by zero. DivisionByZero, /// Unallocated Math0x43, Math0x44, Math0x45, Math0x46, Math0x47, Math0x48, Math0x49, Math0x4A, Math0x4B, Math0x4C, Math0x4D, Math0x4E, Math0x4F, // Other errors /// 0x50: Received zero reveals NoReveals, /// 0x51: Insufficient consensus in tally precondition clause InsufficientConsensus, /// 0x52: Received zero commits InsufficientCommits, /// 0x53: Generic error during tally execution TallyExecution, /// Unallocated OtherError0x54, OtherError0x55, OtherError0x56, OtherError0x57, OtherError0x58, OtherError0x59, OtherError0x5A, OtherError0x5B, OtherError0x5C, OtherError0x5D, OtherError0x5E, OtherError0x5F, /// 0x60: Invalid reveal serialization (malformed reveals are converted to this value) MalformedReveal, /// Unallocated OtherError0x61, OtherError0x62, OtherError0x63, OtherError0x64, OtherError0x65, OtherError0x66, OtherError0x67, OtherError0x68, OtherError0x69, OtherError0x6A, OtherError0x6B, OtherError0x6C, OtherError0x6D, OtherError0x6E, OtherError0x6F, // Access errors /// 0x70: Tried to access a value from an index using an index that is out of bounds ArrayIndexOutOfBounds, /// 0x71: Tried to access a value from a map using a key that does not exist MapKeyNotFound, /// Unallocated OtherError0x72, OtherError0x73, OtherError0x74, OtherError0x75, OtherError0x76, OtherError0x77, OtherError0x78, OtherError0x79, OtherError0x7A, OtherError0x7B, OtherError0x7C, OtherError0x7D, OtherError0x7E, OtherError0x7F, OtherError0x80, OtherError0x81, OtherError0x82, OtherError0x83, OtherError0x84, OtherError0x85, OtherError0x86, OtherError0x87, OtherError0x88, OtherError0x89, OtherError0x8A, OtherError0x8B, OtherError0x8C, OtherError0x8D, OtherError0x8E, OtherError0x8F, OtherError0x90, OtherError0x91, OtherError0x92, OtherError0x93, OtherError0x94, OtherError0x95, OtherError0x96, OtherError0x97, OtherError0x98, OtherError0x99, OtherError0x9A, OtherError0x9B, OtherError0x9C, OtherError0x9D, OtherError0x9E, OtherError0x9F, OtherError0xA0, OtherError0xA1, OtherError0xA2, OtherError0xA3, OtherError0xA4, OtherError0xA5, OtherError0xA6, OtherError0xA7, OtherError0xA8, OtherError0xA9, OtherError0xAA, OtherError0xAB, OtherError0xAC, OtherError0xAD, OtherError0xAE, OtherError0xAF, OtherError0xB0, OtherError0xB1, OtherError0xB2, OtherError0xB3, OtherError0xB4, OtherError0xB5, OtherError0xB6, OtherError0xB7, OtherError0xB8, OtherError0xB9, OtherError0xBA, OtherError0xBB, OtherError0xBC, OtherError0xBD, OtherError0xBE, OtherError0xBF, OtherError0xC0, OtherError0xC1, OtherError0xC2, OtherError0xC3, OtherError0xC4, OtherError0xC5, OtherError0xC6, OtherError0xC7, OtherError0xC8, OtherError0xC9, OtherError0xCA, OtherError0xCB, OtherError0xCC, OtherError0xCD, OtherError0xCE, OtherError0xCF, OtherError0xD0, OtherError0xD1, OtherError0xD2, OtherError0xD3, OtherError0xD4, OtherError0xD5, OtherError0xD6, OtherError0xD7, OtherError0xD8, OtherError0xD9, OtherError0xDA, OtherError0xDB, OtherError0xDC, OtherError0xDD, OtherError0xDE, OtherError0xDF, // Bridge errors: errors that only belong in inter-client communication /// 0xE0: Requests that cannot be parsed must always get this error as their result. /// However, this is not a valid result in a Tally transaction, because invalid requests /// are never included into blocks and therefore never get a Tally in response. BridgeMalformedRequest, /// 0xE1: Witnesses exceeds 100 BridgePoorIncentives, /// 0xE2: The request is rejected on the grounds that it may cause the submitter to spend or stake an /// amount of value that is unjustifiably high when compared with the reward they will be getting BridgeOversizedResult, /// Unallocated OtherError0xE3, OtherError0xE4, OtherError0xE5, OtherError0xE6, OtherError0xE7, OtherError0xE8, OtherError0xE9, OtherError0xEA, OtherError0xEB, OtherError0xEC, OtherError0xED, OtherError0xEE, OtherError0xEF, OtherError0xF0, OtherError0xF1, OtherError0xF2, OtherError0xF3, OtherError0xF4, OtherError0xF5, OtherError0xF6, OtherError0xF7, OtherError0xF8, OtherError0xF9, OtherError0xFA, OtherError0xFB, OtherError0xFC, OtherError0xFD, OtherError0xFE, // This should not exist: /// 0xFF: Some tally error is not intercepted but should UnhandledIntercept } /* * Result impl's */ /** * @notice Decode raw CBOR bytes into a Result instance. * @param _cborBytes Raw bytes representing a CBOR-encoded value. * @return A `Result` instance. */ function resultFromCborBytes(bytes calldata _cborBytes) external pure returns(Result memory) { CBOR.Value memory cborValue = CBOR.valueFromBytes(_cborBytes); return resultFromCborValue(cborValue); } /** * @notice Decode a CBOR value into a Result instance. * @param _cborValue An instance of `CBOR.Value`. * @return A `Result` instance. */ function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) { // Witnet uses CBOR tag 39 to represent RADON error code identifiers. // [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md bool success = _cborValue.tag != 39; return Result(success, _cborValue); } /** * @notice Tell if a Result is successful. * @param _result An instance of Result. * @return `true` if successful, `false` if errored. */ function isOk(Result memory _result) external pure returns(bool) { return _result.success; } /** * @notice Tell if a Result is errored. * @param _result An instance of Result. * @return `true` if errored, `false` if successful. */ function isError(Result memory _result) external pure returns(bool) { return !_result.success; } /** * @notice Decode a bytes value from a Result as a `bytes` value. * @param _result An instance of Result. * @return The `bytes` decoded from the Result. */ function asBytes(Result memory _result) external pure returns(bytes memory) { require(_result.success, "Tried to read bytes value from errored Result"); return _result.cborValue.decodeBytes(); } /** * @notice Decode an error code from a Result as a member of `ErrorCodes`. * @param _result An instance of `Result`. * @return The `CBORValue.Error memory` decoded from the Result. */ function asErrorCode(Result memory _result) external pure returns(ErrorCodes) { uint64[] memory error = asRawError(_result); if (error.length == 0) { return ErrorCodes.Unknown; } return supportedErrorOrElseUnknown(error[0]); } /** * @notice Generate a suitable error message for a member of `ErrorCodes` and its corresponding arguments. * @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function * @param _result An instance of `Result`. * @return A tuple containing the `CBORValue.Error memory` decoded from the `Result`, plus a loggable error message. */ function asErrorMessage(Result memory _result) public pure returns (ErrorCodes, string memory) { uint64[] memory error = asRawError(_result); if (error.length == 0) { return (ErrorCodes.Unknown, "Unknown error (no error code)"); } ErrorCodes errorCode = supportedErrorOrElseUnknown(error[0]); bytes memory errorMessage; if (errorCode == ErrorCodes.SourceScriptNotCBOR && error.length >= 2) { errorMessage = abi.encodePacked("Source script #", utoa(error[1]), " was not a valid CBOR value"); } else if (errorCode == ErrorCodes.SourceScriptNotArray && error.length >= 2) { errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not an Array of calls"); } else if (errorCode == ErrorCodes.SourceScriptNotRADON && error.length >= 2) { errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not a valid RADON script"); } else if (errorCode == ErrorCodes.RequestTooManySources && error.length >= 2) { errorMessage = abi.encodePacked("The request contained too many sources (", utoa(error[1]), ")"); } else if (errorCode == ErrorCodes.ScriptTooManyCalls && error.length >= 4) { errorMessage = abi.encodePacked( "Script #", utoa(error[2]), " from the ", stageName(error[1]), " stage contained too many calls (", utoa(error[3]), ")" ); } else if (errorCode == ErrorCodes.UnsupportedOperator && error.length >= 5) { errorMessage = abi.encodePacked( "Operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage is not supported" ); } else if (errorCode == ErrorCodes.HTTP && error.length >= 3) { errorMessage = abi.encodePacked( "Source #", utoa(error[1]), " could not be retrieved. Failed with HTTP error code: ", utoa(error[2] / 100), utoa(error[2] % 100 / 10), utoa(error[2] % 10) ); } else if (errorCode == ErrorCodes.RetrievalTimeout && error.length >= 2) { errorMessage = abi.encodePacked( "Source #", utoa(error[1]), " could not be retrieved because of a timeout." ); } else if (errorCode == ErrorCodes.Underflow && error.length >= 5) { errorMessage = abi.encodePacked( "Underflow at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.Overflow && error.length >= 5) { errorMessage = abi.encodePacked( "Overflow at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.DivisionByZero && error.length >= 5) { errorMessage = abi.encodePacked( "Division by zero at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.BridgeMalformedRequest) { errorMessage = "The structure of the request is invalid and it cannot be parsed"; } else if (errorCode == ErrorCodes.BridgePoorIncentives) { errorMessage = "The request has been rejected by the bridge node due to poor incentives"; } else if (errorCode == ErrorCodes.BridgeOversizedResult) { errorMessage = "The request result length exceeds a bridge contract defined limit"; } else { errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")"); } return (errorCode, string(errorMessage)); } /** * @notice Decode a raw error from a `Result` as a `uint64[]`. * @param _result An instance of `Result`. * @return The `uint64[]` raw error as decoded from the `Result`. */ function asRawError(Result memory _result) public pure returns(uint64[] memory) { require(!_result.success, "Tried to read error code from successful Result"); return _result.cborValue.decodeUint64Array(); } /** * @notice Decode a boolean value from a Result as an `bool` value. * @param _result An instance of Result. * @return The `bool` decoded from the Result. */ function asBool(Result memory _result) external pure returns(bool) { require(_result.success, "Tried to read `bool` value from errored Result"); return _result.cborValue.decodeBool(); } /** * @notice Decode a fixed16 (half-precision) numeric value from a Result as an `int32` value. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. * use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. * @param _result An instance of Result. * @return The `int128` decoded from the Result. */ function asFixed16(Result memory _result) external pure returns(int32) { require(_result.success, "Tried to read `fixed16` value from errored Result"); return _result.cborValue.decodeFixed16(); } /** * @notice Decode an array of fixed16 values from a Result as an `int128[]` value. * @param _result An instance of Result. * @return The `int128[]` decoded from the Result. */ function asFixed16Array(Result memory _result) external pure returns(int32[] memory) { require(_result.success, "Tried to read `fixed16[]` value from errored Result"); return _result.cborValue.decodeFixed16Array(); } /** * @notice Decode a integer numeric value from a Result as an `int128` value. * @param _result An instance of Result. * @return The `int128` decoded from the Result. */ function asInt128(Result memory _result) external pure returns(int128) { require(_result.success, "Tried to read `int128` value from errored Result"); return _result.cborValue.decodeInt128(); } /** * @notice Decode an array of integer numeric values from a Result as an `int128[]` value. * @param _result An instance of Result. * @return The `int128[]` decoded from the Result. */ function asInt128Array(Result memory _result) external pure returns(int128[] memory) { require(_result.success, "Tried to read `int128[]` value from errored Result"); return _result.cborValue.decodeInt128Array(); } /** * @notice Decode a string value from a Result as a `string` value. * @param _result An instance of Result. * @return The `string` decoded from the Result. */ function asString(Result memory _result) external pure returns(string memory) { require(_result.success, "Tried to read `string` value from errored Result"); return _result.cborValue.decodeString(); } /** * @notice Decode an array of string values from a Result as a `string[]` value. * @param _result An instance of Result. * @return The `string[]` decoded from the Result. */ function asStringArray(Result memory _result) external pure returns(string[] memory) { require(_result.success, "Tried to read `string[]` value from errored Result"); return _result.cborValue.decodeStringArray(); } /** * @notice Decode a natural numeric value from a Result as a `uint64` value. * @param _result An instance of Result. * @return The `uint64` decoded from the Result. */ function asUint64(Result memory _result) external pure returns(uint64) { require(_result.success, "Tried to read `uint64` value from errored Result"); return _result.cborValue.decodeUint64(); } /** * @notice Decode an array of natural numeric values from a Result as a `uint64[]` value. * @param _result An instance of Result. * @return The `uint64[]` decoded from the Result. */ function asUint64Array(Result memory _result) external pure returns(uint64[] memory) { require(_result.success, "Tried to read `uint64[]` value from errored Result"); return _result.cborValue.decodeUint64Array(); } /** * @notice Convert a stage index number into the name of the matching Witnet request stage. * @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages. * @return The name of the matching stage. */ function stageName(uint64 _stageIndex) public pure returns(string memory) { if (_stageIndex == 0) { return "retrieval"; } else if (_stageIndex == 1) { return "aggregation"; } else if (_stageIndex == 2) { return "tally"; } else { return "unknown"; } } /** * @notice Get an `ErrorCodes` item from its `uint64` discriminant. * @param _discriminant The numeric identifier of an error. * @return A member of `ErrorCodes`. */ function supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns(ErrorCodes) { return ErrorCodes(_discriminant); } /** * @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its. * three less significant decimal values. * @param _u A `uint64` value. * @return The `string` representing its decimal value. */ function utoa(uint64 _u) private pure returns(string memory) { if (_u < 10) { bytes memory b1 = new bytes(1); b1[0] = bytes1(uint8(_u) + 48); return string(b1); } else if (_u < 100) { bytes memory b2 = new bytes(2); b2[0] = bytes1(uint8(_u / 10) + 48); b2[1] = bytes1(uint8(_u % 10) + 48); return string(b2); } else { bytes memory b3 = new bytes(3); b3[0] = bytes1(uint8(_u / 100) + 48); b3[1] = bytes1(uint8(_u % 100 / 10) + 48); b3[2] = bytes1(uint8(_u % 10) + 48); return string(b3); } } /** * @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values. * @param _u A `uint64` value. * @return The `string` representing its hexadecimal value. */ function utohex(uint64 _u) private pure returns(string memory) { bytes memory b2 = new bytes(2); uint8 d0 = uint8(_u / 16) + 48; uint8 d1 = uint8(_u % 16) + 48; if (d0 > 57) d0 += 7; if (d1 > 57) d1 += 7; b2[0] = bytes1(d0); b2[1] = bytes1(d1); return string(b2); } } // File: witnet-ethereum-bridge/contracts/WitnetRequestBoardInterface.sol /** * @title Witnet Requests Board Interface * @notice Interface of a Witnet Request Board (WRB) * It defines how to interact with the WRB in order to support: * - Post and upgrade a data request * - Read the result of a dr * @author Witnet Foundation */ interface WitnetRequestBoardInterface { // Event emitted when a new DR is posted event PostedRequest(uint256 _id); // Event emitted when a result is reported event PostedResult(uint256 _id); /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _requestAddress The request contract address which includes the request bytecode. /// @return The unique identifier of the data request. function postDataRequest(address _requestAddress) external payable returns(uint256); /// @dev Increments the reward of a data request by adding the transaction value to it. /// @param _id The unique identifier of the data request. function upgradeDataRequest(uint256 _id) external payable; /// @dev Retrieves the DR transaction hash of the id from the WRB. /// @param _id The unique identifier of the data request. /// @return The hash of the DR transaction function readDrTxHash (uint256 _id) external view returns(uint256); /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR function readResult (uint256 _id) external view returns(bytes memory); /// @notice Verifies if the Witnet Request Board can be upgraded. /// @return true if contract is upgradable. function isUpgradable(address _address) external view returns(bool); /// @dev Estimate the amount of reward we need to insert for a given gas price. /// @param _gasPrice The gas price for which we need to calculate the rewards. /// @return The reward to be included for the given gas price. function estimateGasCost(uint256 _gasPrice) external view returns(uint256); } // File: witnet-ethereum-bridge/contracts/UsingWitnet.sol /** * @title The UsingWitnet contract * @notice Contract writers can inherit this contract in order to create Witnet data requests. */ abstract contract UsingWitnet { using Witnet for Witnet.Result; WitnetRequestBoardInterface internal immutable wrb; /** * @notice Include an address to specify the WitnetRequestBoard. * @param _wrb WitnetRequestBoard address. */ constructor(address _wrb) { wrb = WitnetRequestBoardInterface(_wrb); } // Provides a convenient way for client contracts extending this to block the execution of the main logic of the // contract until a particular request has been successfully resolved by Witnet modifier witnetRequestResolved(uint256 _id) { require(witnetCheckRequestResolved(_id), "Witnet request is not yet resolved by the Witnet network"); _; } /** * @notice Send a new request to the Witnet network with transaction value as result report reward. * @dev Call to `post_dr` function in the WitnetRequestBoard contract. * @param _request An instance of the `Request` contract. * @return Sequencial identifier for the request included in the WitnetRequestBoard. */ function witnetPostRequest(Request _request) internal returns (uint256) { return wrb.postDataRequest{value: msg.value}(address(_request)); } /** * @notice Check if a request has been resolved by Witnet. * @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third. * parties) before this method returns `true`. * @param _id The unique identifier of a request that has been previously sent to the WitnetRequestBoard. * @return A boolean telling if the request has been already resolved or not. */ function witnetCheckRequestResolved(uint256 _id) internal view returns (bool) { // If the result of the data request in Witnet is not the default, then it means that it has been reported as resolved. return wrb.readDrTxHash(_id) != 0; } /** * @notice Upgrade the reward for a Data Request previously included. * @dev Call to `upgrade_dr` function in the WitnetRequestBoard contract. * @param _id The unique identifier of a request that has been previously sent to the WitnetRequestBoard. */ function witnetUpgradeRequest(uint256 _id) internal { wrb.upgradeDataRequest{value: msg.value}(_id); } /** * @notice Read the result of a resolved request. * @dev Call to `read_result` function in the WitnetRequestBoard contract. * @param _id The unique identifier of a request that was posted to Witnet. * @return The result of the request as an instance of `Result`. */ function witnetReadResult(uint256 _id) internal view returns (Witnet.Result memory) { return Witnet.resultFromCborBytes(wrb.readResult(_id)); } /** * @notice Estimate the reward amount. * @dev Call to `estimate_gas_cost` function in the WitnetRequestBoard contract. * @param _gasPrice The gas price for which we want to retrieve the estimation. * @return The reward to be included for the given gas price. */ function witnetEstimateGasCost(uint256 _gasPrice) internal view returns (uint256) { return wrb.estimateGasCost(_gasPrice); } } // File: adomedianizer/contracts/interfaces/IERC2362.sol /** * @dev EIP2362 Interface for pull oracles * https://github.com/adoracles/EIPs/blob/erc-2362/EIPS/eip-2362.md */ interface IERC2362 { /** * @dev Exposed function pertaining to EIP standards * @param _id bytes32 ID of the query * @return int,uint,uint returns the value, timestamp, and status code of query */ function valueFor(bytes32 _id) external view returns(int256,uint256,uint256); } // File: contracts/requests/BitcoinPrice.sol // The bytecode of the BitcoinPrice request that will be sent to Witnet contract BitcoinPriceRequest is Request { constructor () Request(hex"0abf0108e38eb18706123b122468747470733a2f2f7777772e6269747374616d702e6e65742f6170692f7469636b65722f1a13841877821864646c6173748218571903e8185b125c123168747470733a2f2f6170692e636f696e6465736b2e636f6d2f76312f6270692f63757272656e7470726963652e6a736f6e1a2786187782186663627069821866635553448218646a726174655f666c6f61748218571903e8185b1a0d0a0908051205fa3fc000001003220d0a0908051205fa3fc000001003100a186420012846308094ebdc03") { } } // File: contracts/BtcUsdPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the BitcoinPrice request that you created before // Your contract needs to inherit from UsingWitnet contract BtcUsdPriceFeed is UsingWitnet, IERC2362 { using Witnet for Witnet.Result; // The public Bitcoin price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event PriceUpdated(uint64); // Emits when found an error decoding request result event ResultError(string); // This is `keccak256("Price-BTC/USD-3")` bytes32 constant public BTCUSD3ID = bytes32(hex"637b7efb6b620736c247aaa282f3898914c0bef6c12faff0d3fe9d4bea783020"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) { // Instantiate the Witnet request request = new BitcoinPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "Complete pending request before requesting a new one"); // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestResolved(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); // solhint-disable-next-line not-rely-on-time timestamp = block.timestamp; emit PriceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit ResultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != BTCUSD3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(uint256(lastPrice)); return(value, timestamp, 200); } }
Check if a request has been resolved by Witnet. Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third. parties) before this method returns `true`. _id The unique identifier of a request that has been previously sent to the WitnetRequestBoard. return A boolean telling if the request has been already resolved or not./ If the result of the data request in Witnet is not the default, then it means that it has been reported as resolved.
function witnetCheckRequestResolved(uint256 _id) internal view returns (bool) { return wrb.readDrTxHash(_id) != 0; }
997,862
pragma solidity ^0.4.2; /** * @notice Declares a contract that can have an owner. */ contract OwnedI { event LogOwnerChanged(address indexed previousOwner, address indexed newOwner); function getOwner() constant returns (address); function setOwner(address newOwner) returns (bool success); } /** * @notice Defines a contract that can have an owner. */ contract Owned is OwnedI { /** * @dev Made private to protect against child contract setting it to 0 by mistake. */ address private owner; function Owned() { owner = msg.sender; } modifier fromOwner { if (msg.sender != owner) { throw; } _; } function getOwner() constant returns (address) { return owner; } function setOwner(address newOwner) fromOwner returns (bool success) { if (newOwner == 0) { throw; } if (owner != newOwner) { LogOwnerChanged(owner, newOwner); owner = newOwner; } success = true; } } contract WithBeneficiary is Owned { /** * @notice Address that is forwarded all value. * @dev Made private to protect against child contract setting it to 0 by mistake. */ address private beneficiary; event LogBeneficiarySet(address indexed previousBeneficiary, address indexed newBeneficiary); function WithBeneficiary(address _beneficiary) payable { if (_beneficiary == 0) { throw; } beneficiary = _beneficiary; if (msg.value > 0) { asyncSend(beneficiary, msg.value); } } function asyncSend(address dest, uint amount) internal; function getBeneficiary() constant returns (address) { return beneficiary; } function setBeneficiary(address newBeneficiary) fromOwner returns (bool success) { if (newBeneficiary == 0) { throw; } if (beneficiary != newBeneficiary) { LogBeneficiarySet(beneficiary, newBeneficiary); beneficiary = newBeneficiary; } success = true; } function () payable { asyncSend(beneficiary, msg.value); } } contract WithFee is WithBeneficiary { // @notice Contracts asking for a confirmation of a certification need to pass this fee. uint256 private queryFee; event LogQueryFeeSet(uint256 previousQueryFee, uint256 newQueryFee); function WithFee( address beneficiary, uint256 _queryFee) WithBeneficiary(beneficiary) { queryFee = _queryFee; } modifier requestFeePaid { if (msg.value < queryFee) { throw; } asyncSend(getBeneficiary(), msg.value); _; } function getQueryFee() constant returns (uint256) { return queryFee; } function setQueryFee(uint256 newQueryFee) fromOwner returns (bool success) { if (queryFee != newQueryFee) { LogQueryFeeSet(queryFee, newQueryFee); queryFee = newQueryFee; } success = true; } } /* * @notice Base contract supporting async send for pull payments. * Inherit from this contract and use asyncSend instead of send. * https://github.com/OpenZeppelin/zep-solidity/blob/master/contracts/PullPaymentCapable.sol */ contract PullPaymentCapable { uint256 private totalBalance; mapping(address => uint256) private payments; event LogPaymentReceived(address indexed dest, uint256 amount); function PullPaymentCapable() { if (0 < this.balance) { asyncSend(msg.sender, this.balance); } } // store sent amount as credit to be pulled, called by payer function asyncSend(address dest, uint256 amount) internal { if (amount > 0) { totalBalance += amount; payments[dest] += amount; LogPaymentReceived(dest, amount); } } function getTotalBalance() constant returns (uint256) { return totalBalance; } function getPaymentOf(address beneficiary) constant returns (uint256) { return payments[beneficiary]; } // withdraw accumulated balance, called by payee function withdrawPayments() external returns (bool success) { uint256 payment = payments[msg.sender]; payments[msg.sender] = 0; totalBalance -= payment; if (!msg.sender.call.value(payment)()) { throw; } success = true; } function fixBalance() returns (bool success); function fixBalanceInternal(address dest) internal returns (bool success) { if (totalBalance < this.balance) { uint256 amount = this.balance - totalBalance; payments[dest] += amount; LogPaymentReceived(dest, amount); } return true; } } // @notice Interface for a certifier database contract CertifierDbI { event LogCertifierAdded(address indexed certifier); event LogCertifierRemoved(address indexed certifier); function addCertifier(address certifier) returns (bool success); function removeCertifier(address certifier) returns (bool success); function getCertifiersCount() constant returns (uint count); function getCertifierStatus(address certifierAddr) constant returns (bool authorised, uint256 index); function getCertifierAtIndex(uint256 index) constant returns (address); function isCertifier(address certifier) constant returns (bool isIndeed); } contract CertificationDbI { event LogCertifierDbChanged( address indexed previousCertifierDb, address indexed newCertifierDb); event LogStudentCertified( address indexed student, uint timestamp, address indexed certifier, bytes32 indexed document); event LogStudentUncertified( address indexed student, uint timestamp, address indexed certifier); event LogCertificationDocumentAdded( address indexed student, bytes32 indexed document); event LogCertificationDocumentRemoved( address indexed student, bytes32 indexed document); function getCertifierDb() constant returns (address); function setCertifierDb(address newCertifierDb) returns (bool success); function certify(address student, bytes32 document) returns (bool success); function uncertify(address student) returns (bool success); function addCertificationDocument(address student, bytes32 document) returns (bool success); function addCertificationDocumentToSelf(bytes32 document) returns (bool success); function removeCertificationDocument(address student, bytes32 document) returns (bool success); function removeCertificationDocumentFromSelf(bytes32 document) returns (bool success); function getCertifiedStudentsCount() constant returns (uint count); function getCertifiedStudentAtIndex(uint index) payable returns (address student); function getCertification(address student) payable returns (bool certified, uint timestamp, address certifier, uint documentCount); function isCertified(address student) payable returns (bool isIndeed); function getCertificationDocumentAtIndex(address student, uint256 index) payable returns (bytes32 document); function isCertification(address student, bytes32 document) payable returns (bool isIndeed); } contract CertificationDb is CertificationDbI, WithFee, PullPaymentCapable { // @notice Where we check for certifiers. CertifierDbI private certifierDb; struct DocumentStatus { bool isValid; uint256 index; } struct Certification { bool certified; uint256 timestamp; address certifier; mapping(bytes32 => DocumentStatus) documentStatuses; bytes32[] documents; uint256 index; } // @notice Address of certified students. mapping(address => Certification) studentCertifications; // @notice The potentially long list of all certified students. address[] certifiedStudents; function CertificationDb( address beneficiary, uint256 certificationQueryFee, address _certifierDb) WithFee(beneficiary, certificationQueryFee) { if (msg.value > 0) { throw; } if (_certifierDb == 0) { throw; } certifierDb = CertifierDbI(_certifierDb); } modifier fromCertifier { if (!certifierDb.isCertifier(msg.sender)) { throw; } _; } function getCertifierDb() constant returns (address) { return certifierDb; } function setCertifierDb(address newCertifierDb) fromOwner returns (bool success) { if (newCertifierDb == 0) { throw; } if (certifierDb != newCertifierDb) { LogCertifierDbChanged(certifierDb, newCertifierDb); certifierDb = CertifierDbI(newCertifierDb); } success = true; } function certify(address student, bytes32 document) fromCertifier returns (bool success) { if (student == 0 || studentCertifications[student].certified) { throw; } bool documentExists = document != 0; studentCertifications[student] = Certification({ certified: true, timestamp: now, certifier: msg.sender, documents: new bytes32[](0), index: certifiedStudents.length }); if (documentExists) { studentCertifications[student].documentStatuses[document] = DocumentStatus({ isValid: true, index: studentCertifications[student].documents.length }); studentCertifications[student].documents.push(document); } certifiedStudents.push(student); LogStudentCertified(student, now, msg.sender, document); success = true; } function uncertify(address student) fromCertifier returns (bool success) { if (!studentCertifications[student].certified // You need to uncertify all documents first || studentCertifications[student].documents.length > 0) { throw; } uint256 index = studentCertifications[student].index; delete studentCertifications[student]; if (certifiedStudents.length > 1) { certifiedStudents[index] = certifiedStudents[certifiedStudents.length - 1]; studentCertifications[certifiedStudents[index]].index = index; } certifiedStudents.length--; LogStudentUncertified(student, now, msg.sender); success = true; } function addCertificationDocument(address student, bytes32 document) fromCertifier returns (bool success) { success = addCertificationDocumentInternal(student, document); } function addCertificationDocumentToSelf(bytes32 document) returns (bool success) { success = addCertificationDocumentInternal(msg.sender, document); } function addCertificationDocumentInternal(address student, bytes32 document) internal returns (bool success) { if (!studentCertifications[student].certified || document == 0) { throw; } Certification certification = studentCertifications[student]; if (!certification.documentStatuses[document].isValid) { certification.documentStatuses[document] = DocumentStatus({ isValid: true, index: certification.documents.length }); certification.documents.push(document); LogCertificationDocumentAdded(student, document); } success = true; } function removeCertificationDocument(address student, bytes32 document) fromCertifier returns (bool success) { success = removeCertificationDocumentInternal(student, document); } function removeCertificationDocumentFromSelf(bytes32 document) returns (bool success) { success = removeCertificationDocumentInternal(msg.sender, document); } function removeCertificationDocumentInternal(address student, bytes32 document) internal returns (bool success) { if (!studentCertifications[student].certified) { throw; } Certification certification = studentCertifications[student]; if (certification.documentStatuses[document].isValid) { uint256 index = certification.documentStatuses[document].index; delete certification.documentStatuses[document]; if (certification.documents.length > 1) { certification.documents[index] = certification.documents[certification.documents.length - 1]; certification.documentStatuses[certification.documents[index]].index = index; } certification.documents.length--; LogCertificationDocumentRemoved(student, document); } success = true; } function getCertifiedStudentsCount() constant returns (uint256 count) { count = certifiedStudents.length; } function getCertifiedStudentAtIndex(uint256 index) payable requestFeePaid returns (address student) { student = certifiedStudents[index]; } /** * @notice Requesting a certification is a paying feature. */ function getCertification(address student) payable requestFeePaid returns (bool certified, uint256 timestamp, address certifier, uint256 documentCount) { Certification certification = studentCertifications[student]; return (certification.certified, certification.timestamp, certification.certifier, certification.documents.length); } /** * @notice Requesting a certification confirmation is a paying feature. */ function isCertified(address student) payable requestFeePaid returns (bool isIndeed) { isIndeed = studentCertifications[student].certified; } /** * @notice Requesting a certification document by index is a paying feature. */ function getCertificationDocumentAtIndex(address student, uint256 index) payable requestFeePaid returns (bytes32 document) { document = studentCertifications[student].documents[index]; } /** * @notice Requesting a confirmation that a document is a certification is a paying feature. */ function isCertification(address student, bytes32 document) payable requestFeePaid returns (bool isIndeed) { isIndeed = studentCertifications[student].documentStatuses[document].isValid; } function fixBalance() returns (bool success) { return fixBalanceInternal(getBeneficiary()); } }
Requesting a confirmation that a document is a certification is a paying feature./
function isCertification(address student, bytes32 document) payable requestFeePaid returns (bool isIndeed) { isIndeed = studentCertifications[student].documentStatuses[document].isValid; }
7,290,875
pragma solidity 0.6.6; /** * @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; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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 IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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 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 override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public 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 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 sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub( amount, 'ERC20: transfer amount exceeds allowance' ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][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'); _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'); _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'); _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 Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, msg.sender).sub( amount, 'ERC20: burn amount exceeds allowance' ); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } } /* * @dev Implementation of a token compliant with the ERC20 Token protocol; * The token has additional burn functionality. */ contract Token is ERC20Burnable { using SafeMath for uint256; /* * @dev Initialization of the token, * following arguments are provided via the constructor: name, symbol, recipient, totalSupply. * The total supply of tokens is minted to the specified recipient. */ constructor( string memory name, string memory symbol, address recipient, uint256 totalSupply ) public ERC20(name, symbol) { _mint(recipient, totalSupply); } } /* * @dev Implementation of the Initial Stake Offering (ISO). * The ISO is a decentralized token offering with trustless liquidity provisioning, * dividend accumulation and bonus rewards from staking. */ contract UnistakeTokenSale { using SafeMath for uint256; struct Contributor { uint256 phase; uint256 remainder; uint256 fromTotalDivs; } address payable public immutable wallet; uint256 public immutable totalSupplyR1; uint256 public immutable totalSupplyR2; uint256 public immutable totalSupplyR3; uint256 public immutable totalSupplyUniswap; uint256 public immutable rateR1; uint256 public immutable rateR2; uint256 public immutable rateR3; uint256 public immutable periodDurationR3; uint256 public immutable timeDelayR1; uint256 public immutable timeDelayR2; uint256 public immutable stakingPeriodR1; uint256 public immutable stakingPeriodR2; uint256 public immutable stakingPeriodR3; Token public immutable token; IUniswapV2Router02 public immutable uniswapRouter; uint256 public immutable decreasingPctToken; uint256 public immutable decreasingPctETH; uint256 public immutable decreasingPctRate; uint256 public immutable decreasingPctBonus; uint256 public immutable listingRate; address public immutable platformStakingContract; mapping(address => bool) private _contributor; mapping(address => Contributor) private _contributors; mapping(address => uint256)[3] private _contributions; bool[3] private _hasEnded; uint256[3] private _actualSupply; uint256 private _startTimeR2 = 2**256 - 1; uint256 private _startTimeR3 = 2**256 - 1; uint256 private _endTimeR3 = 2**256 - 1; mapping(address => bool)[3] private _hasWithdrawn; bool private _bonusOfferingActive; uint256 private _bonusOfferingActivated; uint256 private _bonusTotal; uint256 private _contributionsTotal; uint256 private _contributorsTotal; uint256 private _contributedFundsTotal; uint256 private _bonusReductionFactor; uint256 private _fundsWithdrawn; uint256 private _endedDayR3; uint256 private _latestStakingPlatformPayment; uint256 private _totalDividends; uint256 private _scaledRemainder; uint256 private _scaling = uint256(10) ** 12; uint256 private _phase = 1; uint256 private _totalRestakedDividends; mapping(address => uint256) private _restkedDividends; mapping(uint256 => uint256) private _payouts; event Staked( address indexed account, uint256 amount); event Claimed( address indexed account, uint256 amount); event Reclaimed( address indexed account, uint256 amount); event Withdrawn( address indexed account, uint256 amount); event Penalized( address indexed account, uint256 amount); event Ended( address indexed account, uint256 amount, uint256 time); event Splitted( address indexed account, uint256 amount1, uint256 amount2); event Bought( uint8 indexed round, address indexed account, uint256 amount); event Activated( bool status, uint256 time); /* * @dev Initialization of the ISO, * following arguments are provided via the constructor: * ---------------------------------------------------- * tokenArg - token offered in the ISO. * totalSupplyArg - total amount of tokens allocated for each round. * totalSupplyUniswapArg - amount of tokens that will be sent to uniswap. * ratesArg - contribution ratio ETH:Token for each round. * periodDurationR3 - duration of a day during round 3. * timeDelayR1Arg - time delay between round 1 and round 2. * timeDelayR2Arg - time delay between round 2 and round 3. * stakingPeriodArg - staking duration required to get bonus tokens for each round. * uniswapRouterArg - contract address of the uniswap router object. * decreasingPctArg - decreasing percentages associated with: token, ETH, rate, and bonus. * listingRateArg - initial listing rate of the offered token. * platformStakingContractArg - contract address of the timed distribution contract. * walletArg - account address of the team wallet. * */ constructor( address tokenArg, uint256[3] memory totalSupplyArg, uint256 totalSupplyUniswapArg, uint256[3] memory ratesArg, uint256 periodDurationR3Arg, uint256 timeDelayR1Arg, uint256 timeDelayR2Arg, uint256[3] memory stakingPeriodArg, address uniswapRouterArg, uint256[4] memory decreasingPctArg, uint256 listingRateArg, address platformStakingContractArg, address payable walletArg ) public { for (uint256 j = 0; j < 3; j++) { require(totalSupplyArg[j] > 0, "The 'totalSupplyArg' argument must be larger than zero"); require(ratesArg[j] > 0, "The 'ratesArg' argument must be larger than zero"); require(stakingPeriodArg[j] > 0, "The 'stakingPeriodArg' argument must be larger than zero"); } for (uint256 j = 0; j < 4; j++) { require(decreasingPctArg[j] < 10000, "The 'decreasingPctArg' arguments must be less than 100 percent"); } require(totalSupplyUniswapArg > 0, "The 'totalSupplyUniswapArg' argument must be larger than zero"); require(periodDurationR3Arg > 0, "The 'slotDurationR3Arg' argument must be larger than zero"); require(tokenArg != address(0), "The 'tokenArg' argument cannot be the zero address"); require(uniswapRouterArg != address(0), "The 'uniswapRouterArg' argument cannot be the zero addresss"); require(listingRateArg > 0, "The 'listingRateArg' argument must be larger than zero"); require(platformStakingContractArg != address(0), "The 'vestingContractArg' argument cannot be the zero address"); require(walletArg != address(0), "The 'walletArg' argument cannot be the zero address"); token = Token(tokenArg); totalSupplyR1 = totalSupplyArg[0]; totalSupplyR2 = totalSupplyArg[1]; totalSupplyR3 = totalSupplyArg[2]; totalSupplyUniswap = totalSupplyUniswapArg; periodDurationR3 = periodDurationR3Arg; timeDelayR1 = timeDelayR1Arg; timeDelayR2 = timeDelayR2Arg; rateR1 = ratesArg[0]; rateR2 = ratesArg[1]; rateR3 = ratesArg[2]; stakingPeriodR1 = stakingPeriodArg[0]; stakingPeriodR2 = stakingPeriodArg[1]; stakingPeriodR3 = stakingPeriodArg[2]; uniswapRouter = IUniswapV2Router02(uniswapRouterArg); decreasingPctToken = decreasingPctArg[0]; decreasingPctETH = decreasingPctArg[1]; decreasingPctRate = decreasingPctArg[2]; decreasingPctBonus = decreasingPctArg[3]; listingRate = listingRateArg; platformStakingContract = platformStakingContractArg; wallet = walletArg; } /** * @dev The fallback function is used for all contributions * during the ISO. The function monitors the current * round and manages token contributions accordingly. */ receive() external payable { if (token.balanceOf(address(this)) > 0) { uint8 currentRound = _calculateCurrentRound(); if (currentRound == 0) { _buyTokenR1(); } else if (currentRound == 1) { _buyTokenR2(); } else if (currentRound == 2) { _buyTokenR3(); } else { revert("The stake offering rounds are not active"); } } else { revert("The stake offering must be active"); } } /** * @dev Wrapper around the round 3 closing function. */ function closeR3() external { uint256 period = _calculatePeriod(block.timestamp); _closeR3(period); } /** * @dev This function prepares the staking and bonus reward settings * and it also provides liquidity to a freshly created uniswap pair. */ function activateStakesAndUniswapLiquidity() external { require(_hasEnded[0] && _hasEnded[1] && _hasEnded[2], "all rounds must have ended"); require(!_bonusOfferingActive, "the bonus offering and uniswap paring can only be done once per ISO"); uint256[3] memory bonusSupplies = [ (_actualSupply[0].mul(_bonusReductionFactor)).div(10000), (_actualSupply[1].mul(_bonusReductionFactor)).div(10000), (_actualSupply[2].mul(_bonusReductionFactor)).div(10000) ]; uint256 totalSupply = totalSupplyR1.add(totalSupplyR2).add(totalSupplyR3); uint256 soldSupply = _actualSupply[0].add(_actualSupply[1]).add(_actualSupply[2]); uint256 unsoldSupply = totalSupply.sub(soldSupply); uint256 exceededBonus = totalSupply .sub(bonusSupplies[0]) .sub(bonusSupplies[1]) .sub(bonusSupplies[2]); uint256 exceededUniswapAmount = _createUniswapPair(_endedDayR3); _bonusOfferingActive = true; _bonusOfferingActivated = block.timestamp; _bonusTotal = bonusSupplies[0].add(bonusSupplies[1]).add(bonusSupplies[2]); _contributionsTotal = soldSupply; _distribute(unsoldSupply.add(exceededBonus).add(exceededUniswapAmount)); emit Activated(true, block.timestamp); } /** * @dev This function allows the caller to stake claimable dividends. */ function restakeDividends() external { uint256 pending = _pendingDividends(msg.sender); pending = pending.add(_contributors[msg.sender].remainder); require(pending >= 0, "You do not have dividends to restake"); _restkedDividends[msg.sender] = _restkedDividends[msg.sender].add(pending); _totalRestakedDividends = _totalRestakedDividends.add(pending); _bonusTotal = _bonusTotal.sub(pending); _contributors[msg.sender].phase = _phase; _contributors[msg.sender].remainder = 0; _contributors[msg.sender].fromTotalDivs = _totalDividends; emit Staked(msg.sender, pending); } /** * @dev This function is called by contributors to * withdraw round 1 tokens. * ----------------------------------------------------- * Withdrawing tokens might result in bonus tokens, dividends, * or similar (based on the staking duration of the contributor). * */ function withdrawR1Tokens() external { require(_bonusOfferingActive, "The bonus offering is not active yet"); _withdrawTokens(0); } /** * @dev This function is called by contributors to * withdraw round 2 tokens. * ----------------------------------------------------- * Withdrawing tokens might result in bonus tokens, dividends, * or similar (based on the staking duration of the contributor). * */ function withdrawR2Tokens() external { require(_bonusOfferingActive, "The bonus offering is not active yet"); _withdrawTokens(1); } /** * @dev This function is called by contributors to * withdraw round 3 tokens. * ----------------------------------------------------- * Withdrawing tokens might result in bonus tokens, dividends, * or similar (based on the staking duration of the contributor). * */ function withdrawR3Tokens() external { require(_bonusOfferingActive, "The bonus offering is not active yet"); _withdrawTokens(2); } /** * @dev wrapper around the withdrawal of funds function. */ function withdrawFunds() external { uint256 amount = ((address(this).balance).sub(_fundsWithdrawn)).div(2); _withdrawFunds(amount); } /** * @dev Returns the total amount of restaked dividends in the ISO. */ function getRestakedDividendsTotal() external view returns (uint256) { return _totalRestakedDividends; } /** * @dev Returns the total staking bonuses in the ISO. */ function getStakingBonusesTotal() external view returns (uint256) { return _bonusTotal; } /** * @dev Returns the latest amount of tokens sent to the timed distribution contract. */ function getLatestStakingPlatformPayment() external view returns (uint256) { return _latestStakingPlatformPayment; } /** * @dev Returns the current day of round 3. */ function getCurrentDayR3() external view returns (uint256) { if (_endedDayR3 != 0) { return _endedDayR3; } return _calculatePeriod(block.timestamp); } /** * @dev Returns the ending day of round 3. */ function getEndedDayR3() external view returns (uint256) { return _endedDayR3; } /** * @dev Returns the start time of round 2. */ function getR2Start() external view returns (uint256) { return _startTimeR2; } /** * @dev Returns the start time of round 3. */ function getR3Start() external view returns (uint256) { return _startTimeR3; } /** * @dev Returns the end time of round 3. */ function getR3End() external view returns (uint256) { return _endTimeR3; } /** * @dev Returns the total amount of contributors in the ISO. */ function getContributorsTotal() external view returns (uint256) { return _contributorsTotal; } /** * @dev Returns the total amount of contributed funds (ETH) in the ISO */ function getContributedFundsTotal() external view returns (uint256) { return _contributedFundsTotal; } /** * @dev Returns the current round of the ISO. */ function getCurrentRound() external view returns (uint8) { uint8 round = _calculateCurrentRound(); if (round == 0 && !_hasEnded[0]) { return 1; } if (round == 1 && !_hasEnded[1] && _hasEnded[0]) { if (block.timestamp <= _startTimeR2) { return 0; } return 2; } if (round == 2 && !_hasEnded[2] && _hasEnded[1]) { if (block.timestamp <= _startTimeR3) { return 0; } return 3; } else { return 0; } } /** * @dev Returns whether round 1 has ended or not. */ function hasR1Ended() external view returns (bool) { return _hasEnded[0]; } /** * @dev Returns whether round 2 has ended or not. */ function hasR2Ended() external view returns (bool) { return _hasEnded[1]; } /** * @dev Returns whether round 3 has ended or not. */ function hasR3Ended() external view returns (bool) { return _hasEnded[2]; } /** * @dev Returns the remaining time delay between round 1 and round 2. */ function getRemainingTimeDelayR1R2() external view returns (uint256) { if (timeDelayR1 > 0) { if (_hasEnded[0] && !_hasEnded[1]) { if (_startTimeR2.sub(block.timestamp) > 0) { return _startTimeR2.sub(block.timestamp); } else { return 0; } } else { return 0; } } else { return 0; } } /** * @dev Returns the remaining time delay between round 2 and round 3. */ function getRemainingTimeDelayR2R3() external view returns (uint256) { if (timeDelayR2 > 0) { if (_hasEnded[0] && _hasEnded[1] && !_hasEnded[2]) { if (_startTimeR3.sub(block.timestamp) > 0) { return _startTimeR3.sub(block.timestamp); } else { return 0; } } else { return 0; } } else { return 0; } } /** * @dev Returns the total sales for round 1. */ function getR1Sales() external view returns (uint256) { return _actualSupply[0]; } /** * @dev Returns the total sales for round 2. */ function getR2Sales() external view returns (uint256) { return _actualSupply[1]; } /** * @dev Returns the total sales for round 3. */ function getR3Sales() external view returns (uint256) { return _actualSupply[2]; } /** * @dev Returns whether the staking- and bonus functionality has been activated or not. */ function getStakingActivationStatus() external view returns (bool) { return _bonusOfferingActive; } /** * @dev This function allows the caller to withdraw claimable dividends. */ function claimDividends() public { if (_totalDividends > _contributors[msg.sender].fromTotalDivs) { uint256 pending = _pendingDividends(msg.sender); pending = pending.add(_contributors[msg.sender].remainder); require(pending >= 0, "You do not have dividends to claim"); _contributors[msg.sender].phase = _phase; _contributors[msg.sender].remainder = 0; _contributors[msg.sender].fromTotalDivs = _totalDividends; _bonusTotal = _bonusTotal.sub(pending); require(token.transfer(msg.sender, pending), "Error in sending reward from contract"); emit Claimed(msg.sender, pending); } } /** * @dev This function allows the caller to withdraw restaked dividends. */ function withdrawRestakedDividends() public { uint256 amount = _restkedDividends[msg.sender]; require(amount >= 0, "You do not have restaked dividends to withdraw"); claimDividends(); _restkedDividends[msg.sender] = 0; _totalRestakedDividends = _totalRestakedDividends.sub(amount); token.transfer(msg.sender, amount); emit Reclaimed(msg.sender, amount); } /** * @dev Returns claimable dividends. */ function getDividends(address accountArg) public view returns (uint256) { uint256 amount = ((_totalDividends.sub(_payouts[_contributors[accountArg].phase - 1])).mul(getContributionTotal(accountArg))).div(_scaling); amount += ((_totalDividends.sub(_payouts[_contributors[accountArg].phase - 1])).mul(getContributionTotal(accountArg))) % _scaling ; return (amount.add(_contributors[msg.sender].remainder)); } /** * @dev Returns restaked dividends. */ function getRestakedDividends(address accountArg) public view returns (uint256) { return _restkedDividends[accountArg]; } /** * @dev Returns round 1 contributions of an account. */ function getR1Contribution(address accountArg) public view returns (uint256) { return _contributions[0][accountArg]; } /** * @dev Returns round 2 contributions of an account. */ function getR2Contribution(address accountArg) public view returns (uint256) { return _contributions[1][accountArg]; } /** * @dev Returns round 3 contributions of an account. */ function getR3Contribution(address accountArg) public view returns (uint256) { return _contributions[2][accountArg]; } /** * @dev Returns the total contributions of an account. */ function getContributionTotal(address accountArg) public view returns (uint256) { uint256 contributionR1 = getR1Contribution(accountArg); uint256 contributionR2 = getR2Contribution(accountArg); uint256 contributionR3 = getR3Contribution(accountArg); uint256 restaked = getRestakedDividends(accountArg); return contributionR1.add(contributionR2).add(contributionR3).add(restaked); } /** * @dev Returns the total contributions in the ISO (including restaked dividends). */ function getContributionsTotal() public view returns (uint256) { return _contributionsTotal.add(_totalRestakedDividends); } /** * @dev Returns expected round 1 staking bonus for an account. */ function getStakingBonusR1(address accountArg) public view returns (uint256) { uint256 contribution = _contributions[0][accountArg]; return (contribution.mul(_bonusReductionFactor)).div(10000); } /** * @dev Returns expected round 2 staking bonus for an account. */ function getStakingBonusR2(address accountArg) public view returns (uint256) { uint256 contribution = _contributions[1][accountArg]; return (contribution.mul(_bonusReductionFactor)).div(10000); } /** * @dev Returns expected round 3 staking bonus for an account. */ function getStakingBonusR3(address accountArg) public view returns (uint256) { uint256 contribution = _contributions[2][accountArg]; return (contribution.mul(_bonusReductionFactor)).div(10000); } /** * @dev Returns the total expected staking bonuses for an account. */ function getStakingBonusTotal(address accountArg) public view returns (uint256) { uint256 stakeR1 = getStakingBonusR1(accountArg); uint256 stakeR2 = getStakingBonusR2(accountArg); uint256 stakeR3 = getStakingBonusR3(accountArg); return stakeR1.add(stakeR2).add(stakeR3); } /** * @dev This function handles distribution of extra supply. */ function _distribute(uint256 amountArg) private { uint256 vested = amountArg.div(2); uint256 burned = amountArg.sub(vested); token.transfer(platformStakingContract, vested); token.burn(burned); } /** * @dev This function handles calculation of token withdrawals * (it also withdraws dividends and restaked dividends * during certain circumstances). */ function _withdrawTokens(uint8 indexArg) private { require(_hasEnded[0] && _hasEnded[1] && _hasEnded[2], "The rounds must be inactive before any tokens can be withdrawn"); require(!_hasWithdrawn[indexArg][msg.sender], "The caller must have withdrawable tokens available from this round"); claimDividends(); uint256 amount = _contributions[indexArg][msg.sender]; uint256 amountBonus = (amount.mul(_bonusReductionFactor)).div(10000); _contributions[indexArg][msg.sender] = _contributions[indexArg][msg.sender].sub(amount); _contributionsTotal = _contributionsTotal.sub(amount); uint256 contributions = getContributionTotal(msg.sender); uint256 restaked = getRestakedDividends(msg.sender); if (contributions.sub(restaked) == 0) withdrawRestakedDividends(); uint pending = _pendingDividends(msg.sender); _contributors[msg.sender].remainder = (_contributors[msg.sender].remainder).add(pending); _contributors[msg.sender].fromTotalDivs = _totalDividends; _contributors[msg.sender].phase = _phase; _hasWithdrawn[indexArg][msg.sender] = true; token.transfer(msg.sender, amount); _endStake(indexArg, msg.sender, amountBonus); } /** * @dev This function handles fund withdrawals. */ function _withdrawFunds(uint256 amountArg) private { require(msg.sender == wallet, "The caller must be the specified funds wallet of the team"); require(amountArg <= ((address(this).balance.sub(_fundsWithdrawn)).div(2)), "The 'amountArg' argument exceeds the limit"); require(!_hasEnded[2], "The third round is not active"); _fundsWithdrawn = _fundsWithdrawn.add(amountArg); wallet.transfer(amountArg); } /** * @dev This function handles token purchases for round 1. */ function _buyTokenR1() private { if (token.balanceOf(address(this)) > 0) { require(!_hasEnded[0], "The first round must be active"); bool isRoundEnded = _buyToken(0, rateR1, totalSupplyR1); if (isRoundEnded == true) { _startTimeR2 = block.timestamp.add(timeDelayR1); } } else { revert("The stake offering must be active"); } } /** * @dev This function handles token purchases for round 2. */ function _buyTokenR2() private { require(_hasEnded[0] && !_hasEnded[1], "The first round one must not be active while the second round must be active"); require(block.timestamp >= _startTimeR2, "The time delay between the first round and the second round must be surpassed"); bool isRoundEnded = _buyToken(1, rateR2, totalSupplyR2); if (isRoundEnded == true) { _startTimeR3 = block.timestamp.add(timeDelayR2); } } /** * @dev This function handles token purchases for round 3. */ function _buyTokenR3() private { require(_hasEnded[1] && !_hasEnded[2], "The second round one must not be active while the third round must be active"); require(block.timestamp >= _startTimeR3, "The time delay between the first round and the second round must be surpassed"); uint256 period = _calculatePeriod(block.timestamp); (bool isRoundClosed, uint256 actualPeriodTotalSupply) = _closeR3(period); if (!isRoundClosed) { bool isRoundEnded = _buyToken(2, rateR3, actualPeriodTotalSupply); if (isRoundEnded == true) { _endTimeR3 = block.timestamp; uint256 endingPeriod = _calculateEndingPeriod(); uint256 reductionFactor = _calculateBonusReductionFactor(endingPeriod); _bonusReductionFactor = reductionFactor; _endedDayR3 = endingPeriod; } } } /** * @dev This function handles bonus payouts and the split of forfeited bonuses. */ function _endStake(uint256 indexArg, address accountArg, uint256 amountArg) private { uint256 elapsedTime = (block.timestamp).sub(_bonusOfferingActivated); uint256 payout; uint256 duration = _getDuration(indexArg); if (elapsedTime >= duration) { payout = amountArg; } else if (elapsedTime >= duration.mul(3).div(4) && elapsedTime < duration) { payout = amountArg.mul(3).div(4); } else if (elapsedTime >= duration.div(2) && elapsedTime < duration.mul(3).div(4)) { payout = amountArg.div(2); } else if (elapsedTime >= duration.div(4) && elapsedTime < duration.div(2)) { payout = amountArg.div(4); } else { payout = 0; } _split(amountArg.sub(payout)); if (payout != 0) { token.transfer(accountArg, payout); } emit Ended(accountArg, amountArg, block.timestamp); } /** * @dev This function splits forfeited bonuses into dividends * and to timed distribution contract accordingly. */ function _split(uint256 amountArg) private { if (amountArg == 0) { return; } uint256 dividends = amountArg.div(2); uint256 platformStakingShare = amountArg.sub(dividends); _bonusTotal = _bonusTotal.sub(platformStakingShare); _latestStakingPlatformPayment = platformStakingShare; token.transfer(platformStakingContract, platformStakingShare); _addDividends(_latestStakingPlatformPayment); emit Splitted(msg.sender, dividends, platformStakingShare); } /** * @dev this function handles addition of new dividends. */ function _addDividends(uint256 bonusArg) private { uint256 latest = (bonusArg.mul(_scaling)).add(_scaledRemainder); uint256 dividendPerToken = latest.div(_contributionsTotal.add(_totalRestakedDividends)); _scaledRemainder = latest.mod(_contributionsTotal.add(_totalRestakedDividends)); _totalDividends = _totalDividends.add(dividendPerToken); _payouts[_phase] = _payouts[_phase-1].add(dividendPerToken); _phase++; } /** * @dev returns pending dividend rewards. */ function _pendingDividends(address accountArg) private returns (uint256) { uint256 amount = ((_totalDividends.sub(_payouts[_contributors[accountArg].phase - 1])).mul(getContributionTotal(accountArg))).div(_scaling); _contributors[accountArg].remainder += ((_totalDividends.sub(_payouts[_contributors[accountArg].phase - 1])).mul(getContributionTotal(accountArg))) % _scaling ; return amount; } /** * @dev This function creates a uniswap pair and handles liquidity provisioning. * Returns the uniswap token leftovers. */ function _createUniswapPair(uint256 endingPeriodArg) private returns (uint256) { uint256 listingPrice = endingPeriodArg.mul(decreasingPctRate); uint256 ethDecrease = uint256(5000).sub(endingPeriodArg.mul(decreasingPctETH)); uint256 ethOnUniswap = (_contributedFundsTotal.mul(ethDecrease)).div(10000); ethOnUniswap = ethOnUniswap <= (address(this).balance) ? ethOnUniswap : (address(this).balance); uint256 tokensOnUniswap = ethOnUniswap .mul(listingRate) .mul(10000) .div(uint256(10000).sub(listingPrice)) .div(100000); token.approve(address(uniswapRouter), tokensOnUniswap); uniswapRouter.addLiquidityETH.value(ethOnUniswap)( address(token), tokensOnUniswap, 0, 0, wallet, block.timestamp ); wallet.transfer(address(this).balance); return (totalSupplyUniswap.sub(tokensOnUniswap)); } /** * @dev this function will close round 3 if based on day and sold supply. * Returns whether a particular round has ended or not and * the max supply of a particular day during round 3. */ function _closeR3(uint256 periodArg) private returns (bool isRoundEnded, uint256 maxPeriodSupply) { require(_hasEnded[0] && _hasEnded[1] && !_hasEnded[2], 'Round 3 has ended or Round 1 or 2 have not ended yet'); require(block.timestamp >= _startTimeR3, 'Pause period between Round 2 and 3'); uint256 decreasingTokenNumber = totalSupplyR3.mul(decreasingPctToken).div(10000); maxPeriodSupply = totalSupplyR3.sub(periodArg.mul(decreasingTokenNumber)); if (maxPeriodSupply <= _actualSupply[2]) { msg.sender.transfer(msg.value); _hasEnded[2] = true; _endTimeR3 = block.timestamp; uint256 endingPeriod = _calculateEndingPeriod(); uint256 reductionFactor = _calculateBonusReductionFactor(endingPeriod); _endedDayR3 = endingPeriod; _bonusReductionFactor = reductionFactor; return (true, maxPeriodSupply); } else { return (false, maxPeriodSupply); } } /** * @dev this function handles low level token purchases. * Returns whether a particular round has ended or not. */ function _buyToken(uint8 indexArg, uint256 rateArg, uint256 totalSupplyArg) private returns (bool isRoundEnded) { uint256 tokensNumber = msg.value.mul(rateArg).div(100000); uint256 actualTotalBalance = _actualSupply[indexArg]; uint256 newTotalRoundBalance = actualTotalBalance.add(tokensNumber); if (!_contributor[msg.sender]) { _contributor[msg.sender] = true; _contributorsTotal++; } if (newTotalRoundBalance < totalSupplyArg) { _contributions[indexArg][msg.sender] = _contributions[indexArg][msg.sender].add(tokensNumber); _actualSupply[indexArg] = newTotalRoundBalance; _contributedFundsTotal = _contributedFundsTotal.add(msg.value); emit Bought(uint8(indexArg + 1), msg.sender, tokensNumber); return false; } else { uint256 availableTokens = totalSupplyArg.sub(actualTotalBalance); uint256 availableEth = availableTokens.mul(100000).div(rateArg); _contributions[indexArg][msg.sender] = _contributions[indexArg][msg.sender].add(availableTokens); _actualSupply[indexArg] = totalSupplyArg; _contributedFundsTotal = _contributedFundsTotal.add(availableEth); _hasEnded[indexArg] = true; msg.sender.transfer(msg.value.sub(availableEth)); emit Bought(uint8(indexArg + 1), msg.sender, availableTokens); return true; } } /** * @dev Returns the staking duration of a particular round. */ function _getDuration(uint256 indexArg) private view returns (uint256) { if (indexArg == 0) { return stakingPeriodR1; } if (indexArg == 1) { return stakingPeriodR2; } if (indexArg == 2) { return stakingPeriodR3; } } /** * @dev Returns the bonus reduction factor. */ function _calculateBonusReductionFactor(uint256 periodArg) private view returns (uint256) { uint256 reductionFactor = uint256(10000).sub(periodArg.mul(decreasingPctBonus)); return reductionFactor; } /** * @dev Returns the current round. */ function _calculateCurrentRound() private view returns (uint8) { if (!_hasEnded[0]) { return 0; } else if (_hasEnded[0] && !_hasEnded[1] && !_hasEnded[2]) { return 1; } else if (_hasEnded[0] && _hasEnded[1] && !_hasEnded[2]) { return 2; } else { return 2**8 - 1; } } /** * @dev Returns the current day. */ function _calculatePeriod(uint256 timeArg) private view returns (uint256) { uint256 period = ((timeArg.sub(_startTimeR3)).div(periodDurationR3)); uint256 maxPeriods = uint256(10000).div(decreasingPctToken); if (period > maxPeriods) { return maxPeriods; } return period; } /** * @dev Returns the ending day of round 3. */ function _calculateEndingPeriod() private view returns (uint256) { require(_endTimeR3 != (2**256) - 1, "The third round must be active"); uint256 endingPeriod = _calculatePeriod(_endTimeR3); return endingPeriod; } }
This function prepares the staking and bonus reward settings and it also provides liquidity to a freshly created uniswap pair./
function activateStakesAndUniswapLiquidity() external { require(_hasEnded[0] && _hasEnded[1] && _hasEnded[2], "all rounds must have ended"); require(!_bonusOfferingActive, "the bonus offering and uniswap paring can only be done once per ISO"); uint256[3] memory bonusSupplies = [ (_actualSupply[0].mul(_bonusReductionFactor)).div(10000), (_actualSupply[1].mul(_bonusReductionFactor)).div(10000), (_actualSupply[2].mul(_bonusReductionFactor)).div(10000) ]; uint256 totalSupply = totalSupplyR1.add(totalSupplyR2).add(totalSupplyR3); uint256 soldSupply = _actualSupply[0].add(_actualSupply[1]).add(_actualSupply[2]); uint256 unsoldSupply = totalSupply.sub(soldSupply); uint256 exceededBonus = totalSupply .sub(bonusSupplies[0]) .sub(bonusSupplies[1]) .sub(bonusSupplies[2]); uint256 exceededUniswapAmount = _createUniswapPair(_endedDayR3); _bonusOfferingActive = true; _bonusOfferingActivated = block.timestamp; _bonusTotal = bonusSupplies[0].add(bonusSupplies[1]).add(bonusSupplies[2]); _contributionsTotal = soldSupply; _distribute(unsoldSupply.add(exceededBonus).add(exceededUniswapAmount)); emit Activated(true, block.timestamp); }
12,816,390
./full_match/80001/0xE56bB093Be2A9fa554c8693aA32068becCCfc97E/sources/contracts/pack-plugin/extension/PackVRFDirectLogic.sol
See {ERC1155-_beforeTokenTransfer}./
function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); PackVRFDirectStorage.Data storage packVrfData = PackVRFDirectStorage.packVRFStorage(); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { packVrfData.totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { packVrfData.totalSupply[ids[i]] -= amounts[i]; } } }
5,559,910
// SPDX-License-Identifier: MIT pragma solidity >=0.8.9; /// @notice Emitted when the result overflows uint256. error PRBMath__MulDivFixedPointOverflow(uint256 prod1); /// @notice Emitted when the result overflows uint256. error PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator); /// @notice Emitted when one of the inputs is type(int256).min. error PRBMath__MulDivSignedInputTooSmall(); /// @notice Emitted when the intermediary absolute result overflows int256. error PRBMath__MulDivSignedOverflow(uint256 rAbs); /// @notice Emitted when the input is MIN_SD59x18. error PRBMathSD59x18__AbsInputTooSmall(); /// @notice Emitted when ceiling a number overflows SD59x18. error PRBMathSD59x18__CeilOverflow(int256 x); /// @notice Emitted when one of the inputs is MIN_SD59x18. error PRBMathSD59x18__DivInputTooSmall(); /// @notice Emitted when one of the intermediary unsigned results overflows SD59x18. error PRBMathSD59x18__DivOverflow(uint256 rAbs); /// @notice Emitted when the input is greater than 133.084258667509499441. error PRBMathSD59x18__ExpInputTooBig(int256 x); /// @notice Emitted when the input is greater than 192. error PRBMathSD59x18__Exp2InputTooBig(int256 x); /// @notice Emitted when flooring a number underflows SD59x18. error PRBMathSD59x18__FloorUnderflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18. error PRBMathSD59x18__FromIntOverflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18. error PRBMathSD59x18__FromIntUnderflow(int256 x); /// @notice Emitted when the product of the inputs is negative. error PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y); /// @notice Emitted when multiplying the inputs overflows SD59x18. error PRBMathSD59x18__GmOverflow(int256 x, int256 y); /// @notice Emitted when the input is less than or equal to zero. error PRBMathSD59x18__LogInputTooSmall(int256 x); /// @notice Emitted when one of the inputs is MIN_SD59x18. error PRBMathSD59x18__MulInputTooSmall(); /// @notice Emitted when the intermediary absolute result overflows SD59x18. error PRBMathSD59x18__MulOverflow(uint256 rAbs); /// @notice Emitted when the intermediary absolute result overflows SD59x18. error PRBMathSD59x18__PowuOverflow(uint256 rAbs); /// @notice Emitted when the input is negative. error PRBMathSD59x18__SqrtNegativeInput(int256 x); /// @notice Emitted when the calculating the square root overflows SD59x18. error PRBMathSD59x18__SqrtOverflow(int256 x); /// @notice Emitted when addition overflows UD60x18. error PRBMathUD60x18__AddOverflow(uint256 x, uint256 y); /// @notice Emitted when ceiling a number overflows UD60x18. error PRBMathUD60x18__CeilOverflow(uint256 x); /// @notice Emitted when the input is greater than 133.084258667509499441. error PRBMathUD60x18__ExpInputTooBig(uint256 x); /// @notice Emitted when the input is greater than 192. error PRBMathUD60x18__Exp2InputTooBig(uint256 x); /// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18. error PRBMathUD60x18__FromUintOverflow(uint256 x); /// @notice Emitted when multiplying the inputs overflows UD60x18. error PRBMathUD60x18__GmOverflow(uint256 x, uint256 y); /// @notice Emitted when the input is less than 1. error PRBMathUD60x18__LogInputTooSmall(uint256 x); /// @notice Emitted when the calculating the square root overflows UD60x18. error PRBMathUD60x18__SqrtOverflow(uint256 x); /// @notice Emitted when subtraction underflows UD60x18. error PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y); /// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library /// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point /// representation. When it does not, it is explicitly mentioned in the NatSpec documentation. library PRBMath { /// STRUCTS /// struct SD59x18 { int256 value; } struct UD60x18 { uint256 value; } /// STORAGE /// /// @dev How many trailing decimals can be represented. uint256 internal constant SCALE = 1e18; /// @dev Largest power of two divisor of SCALE. uint256 internal constant SCALE_LPOTD = 262144; /// @dev SCALE inverted mod 2^256. uint256 internal constant SCALE_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281; /// FUNCTIONS /// /// @notice Calculates the binary exponent of x using the binary fraction method. /// @dev Has to use 192.64-bit fixed-point numbers. /// See https://ethereum.stackexchange.com/a/96594/24693. /// @param x The exponent as an unsigned 192.64-bit fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp2(uint256 x) internal pure returns (uint256 result) { unchecked { // Start from 0.5 in the 192.64-bit fixed-point format. result = 0x800000000000000000000000000000000000000000000000; // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows // because the initial result is 2^191 and all magic factors are less than 2^65. if (x & 0x8000000000000000 > 0) { result = (result * 0x16A09E667F3BCC909) >> 64; } if (x & 0x4000000000000000 > 0) { result = (result * 0x1306FE0A31B7152DF) >> 64; } if (x & 0x2000000000000000 > 0) { result = (result * 0x1172B83C7D517ADCE) >> 64; } if (x & 0x1000000000000000 > 0) { result = (result * 0x10B5586CF9890F62A) >> 64; } if (x & 0x800000000000000 > 0) { result = (result * 0x1059B0D31585743AE) >> 64; } if (x & 0x400000000000000 > 0) { result = (result * 0x102C9A3E778060EE7) >> 64; } if (x & 0x200000000000000 > 0) { result = (result * 0x10163DA9FB33356D8) >> 64; } if (x & 0x100000000000000 > 0) { result = (result * 0x100B1AFA5ABCBED61) >> 64; } if (x & 0x80000000000000 > 0) { result = (result * 0x10058C86DA1C09EA2) >> 64; } if (x & 0x40000000000000 > 0) { result = (result * 0x1002C605E2E8CEC50) >> 64; } if (x & 0x20000000000000 > 0) { result = (result * 0x100162F3904051FA1) >> 64; } if (x & 0x10000000000000 > 0) { result = (result * 0x1000B175EFFDC76BA) >> 64; } if (x & 0x8000000000000 > 0) { result = (result * 0x100058BA01FB9F96D) >> 64; } if (x & 0x4000000000000 > 0) { result = (result * 0x10002C5CC37DA9492) >> 64; } if (x & 0x2000000000000 > 0) { result = (result * 0x1000162E525EE0547) >> 64; } if (x & 0x1000000000000 > 0) { result = (result * 0x10000B17255775C04) >> 64; } if (x & 0x800000000000 > 0) { result = (result * 0x1000058B91B5BC9AE) >> 64; } if (x & 0x400000000000 > 0) { result = (result * 0x100002C5C89D5EC6D) >> 64; } if (x & 0x200000000000 > 0) { result = (result * 0x10000162E43F4F831) >> 64; } if (x & 0x100000000000 > 0) { result = (result * 0x100000B1721BCFC9A) >> 64; } if (x & 0x80000000000 > 0) { result = (result * 0x10000058B90CF1E6E) >> 64; } if (x & 0x40000000000 > 0) { result = (result * 0x1000002C5C863B73F) >> 64; } if (x & 0x20000000000 > 0) { result = (result * 0x100000162E430E5A2) >> 64; } if (x & 0x10000000000 > 0) { result = (result * 0x1000000B172183551) >> 64; } if (x & 0x8000000000 > 0) { result = (result * 0x100000058B90C0B49) >> 64; } if (x & 0x4000000000 > 0) { result = (result * 0x10000002C5C8601CC) >> 64; } if (x & 0x2000000000 > 0) { result = (result * 0x1000000162E42FFF0) >> 64; } if (x & 0x1000000000 > 0) { result = (result * 0x10000000B17217FBB) >> 64; } if (x & 0x800000000 > 0) { result = (result * 0x1000000058B90BFCE) >> 64; } if (x & 0x400000000 > 0) { result = (result * 0x100000002C5C85FE3) >> 64; } if (x & 0x200000000 > 0) { result = (result * 0x10000000162E42FF1) >> 64; } if (x & 0x100000000 > 0) { result = (result * 0x100000000B17217F8) >> 64; } if (x & 0x80000000 > 0) { result = (result * 0x10000000058B90BFC) >> 64; } if (x & 0x40000000 > 0) { result = (result * 0x1000000002C5C85FE) >> 64; } if (x & 0x20000000 > 0) { result = (result * 0x100000000162E42FF) >> 64; } if (x & 0x10000000 > 0) { result = (result * 0x1000000000B17217F) >> 64; } if (x & 0x8000000 > 0) { result = (result * 0x100000000058B90C0) >> 64; } if (x & 0x4000000 > 0) { result = (result * 0x10000000002C5C860) >> 64; } if (x & 0x2000000 > 0) { result = (result * 0x1000000000162E430) >> 64; } if (x & 0x1000000 > 0) { result = (result * 0x10000000000B17218) >> 64; } if (x & 0x800000 > 0) { result = (result * 0x1000000000058B90C) >> 64; } if (x & 0x400000 > 0) { result = (result * 0x100000000002C5C86) >> 64; } if (x & 0x200000 > 0) { result = (result * 0x10000000000162E43) >> 64; } if (x & 0x100000 > 0) { result = (result * 0x100000000000B1721) >> 64; } if (x & 0x80000 > 0) { result = (result * 0x10000000000058B91) >> 64; } if (x & 0x40000 > 0) { result = (result * 0x1000000000002C5C8) >> 64; } if (x & 0x20000 > 0) { result = (result * 0x100000000000162E4) >> 64; } if (x & 0x10000 > 0) { result = (result * 0x1000000000000B172) >> 64; } if (x & 0x8000 > 0) { result = (result * 0x100000000000058B9) >> 64; } if (x & 0x4000 > 0) { result = (result * 0x10000000000002C5D) >> 64; } if (x & 0x2000 > 0) { result = (result * 0x1000000000000162E) >> 64; } if (x & 0x1000 > 0) { result = (result * 0x10000000000000B17) >> 64; } if (x & 0x800 > 0) { result = (result * 0x1000000000000058C) >> 64; } if (x & 0x400 > 0) { result = (result * 0x100000000000002C6) >> 64; } if (x & 0x200 > 0) { result = (result * 0x10000000000000163) >> 64; } if (x & 0x100 > 0) { result = (result * 0x100000000000000B1) >> 64; } if (x & 0x80 > 0) { result = (result * 0x10000000000000059) >> 64; } if (x & 0x40 > 0) { result = (result * 0x1000000000000002C) >> 64; } if (x & 0x20 > 0) { result = (result * 0x10000000000000016) >> 64; } if (x & 0x10 > 0) { result = (result * 0x1000000000000000B) >> 64; } if (x & 0x8 > 0) { result = (result * 0x10000000000000006) >> 64; } if (x & 0x4 > 0) { result = (result * 0x10000000000000003) >> 64; } if (x & 0x2 > 0) { result = (result * 0x10000000000000001) >> 64; } if (x & 0x1 > 0) { result = (result * 0x10000000000000001) >> 64; } // We're doing two things at the same time: // // 1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for // the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191 // rather than 192. // 2. Convert the result to the unsigned 60.18-decimal fixed-point format. // // This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n". result *= SCALE; result >>= (191 - (x >> 64)); } } /// @notice Finds the zero-based index of the first one in the binary representation of x. /// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set /// @param x The uint256 number for which to find the index of the most significant bit. /// @return msb The index of the most significant bit as an uint256. function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) { if (x >= 2**128) { x >>= 128; msb += 128; } if (x >= 2**64) { x >>= 64; msb += 64; } if (x >= 2**32) { x >>= 32; msb += 32; } if (x >= 2**16) { x >>= 16; msb += 16; } if (x >= 2**8) { x >>= 8; msb += 8; } if (x >= 2**4) { x >>= 4; msb += 4; } if (x >= 2**2) { x >>= 2; msb += 2; } if (x >= 2**1) { // No need to shift x any more. msb += 1; } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv. /// /// Requirements: /// - The denominator cannot be zero. /// - The result must fit within uint256. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The multiplicand as an uint256. /// @param y The multiplier as an uint256. /// @param denominator The divisor as an uint256. /// @return result The result as an uint256. function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { unchecked { result = prod0 / denominator; } return result; } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (prod1 >= denominator) { revert PRBMath__MulDivOverflow(prod1, denominator); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. unchecked { // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 lpotdod = denominator & (~denominator + 1); assembly { // Divide denominator by lpotdod. denominator := div(denominator, lpotdod) // Divide [prod1 prod0] by lpotdod. prod0 := div(prod0, lpotdod) // Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one. lpotdod := add(div(sub(0, lpotdod), lpotdod), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * lpotdod; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /// @notice Calculates floor(x*y÷1e18) with full precision. /// /// @dev Variant of "mulDiv" with constant folding, i.e. in which the denominator is always 1e18. Before returning the /// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of /// being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717. /// /// Requirements: /// - The result must fit within uint256. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works. /// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations: /// 1. x * y = type(uint256).max * SCALE /// 2. (x * y) % SCALE >= SCALE / 2 /// /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) { uint256 prod0; uint256 prod1; assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 >= SCALE) { revert PRBMath__MulDivFixedPointOverflow(prod1); } uint256 remainder; uint256 roundUpUnit; assembly { remainder := mulmod(x, y, SCALE) roundUpUnit := gt(remainder, 499999999999999999) } if (prod1 == 0) { unchecked { result = (prod0 / SCALE) + roundUpUnit; return result; } } assembly { result := add( mul( or( div(sub(prod0, remainder), SCALE_LPOTD), mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1)) ), SCALE_INVERSE ), roundUpUnit ) } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev An extension of "mulDiv" for signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - None of the inputs can be type(int256).min. /// - The result must fit within int256. /// /// @param x The multiplicand as an int256. /// @param y The multiplier as an int256. /// @param denominator The divisor as an int256. /// @return result The result as an int256. function mulDivSigned( int256 x, int256 y, int256 denominator ) internal pure returns (int256 result) { if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) { revert PRBMath__MulDivSignedInputTooSmall(); } // Get hold of the absolute values of x, y and the denominator. uint256 ax; uint256 ay; uint256 ad; unchecked { ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); ad = denominator < 0 ? uint256(-denominator) : uint256(denominator); } // Compute the absolute value of (x*y)÷denominator. The result must fit within int256. uint256 rAbs = mulDiv(ax, ay, ad); if (rAbs > uint256(type(int256).max)) { revert PRBMath__MulDivSignedOverflow(rAbs); } // Get the signs of x, y and the denominator. uint256 sx; uint256 sy; uint256 sd; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) sd := sgt(denominator, sub(0, 1)) } // XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs. // If yes, the result should be negative. result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs); } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The uint256 number for which to calculate the square root. /// @return result The result as an uint256. function sqrt(uint256 x) internal pure returns (uint256 result) { if (x == 0) { return 0; } // Set the initial guess to the least power of two that is greater than or equal to sqrt(x). uint256 xAux = uint256(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; } if (xAux >= 0x10000000000000000) { xAux >>= 64; result <<= 32; } if (xAux >= 0x100000000) { xAux >>= 32; result <<= 16; } if (xAux >= 0x10000) { xAux >>= 16; result <<= 8; } if (xAux >= 0x100) { xAux >>= 8; result <<= 4; } if (xAux >= 0x10) { xAux >>= 4; result <<= 2; } if (xAux >= 0x8) { result <<= 1; } // The operations can never overflow because the result is max 2^127 when it enters this block. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // Seven iterations should be enough uint256 roundedDownResult = x / result; return result >= roundedDownResult ? roundedDownResult : result; } } } /// @title PRBMathSD59x18 /// @author Paul Razvan Berg /// @notice Smart contract library for advanced fixed-point math that works with int256 numbers considered to have 18 /// trailing decimals. We call this number representation signed 59.18-decimal fixed-point, since the numbers can have /// a sign and there can be up to 59 digits in the integer part and up to 18 decimals in the fractional part. The numbers /// are bound by the minimum and the maximum values permitted by the Solidity type int256. library PRBMathSD59x18 { /// @dev log2(e) as a signed 59.18-decimal fixed-point number. int256 internal constant LOG2_E = 1_442695040888963407; /// @dev Half the SCALE number. int256 internal constant HALF_SCALE = 5e17; /// @dev The maximum value a signed 59.18-decimal fixed-point number can have. int256 internal constant MAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967; /// @dev The maximum whole value a signed 59.18-decimal fixed-point number can have. int256 internal constant MAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000; /// @dev The minimum value a signed 59.18-decimal fixed-point number can have. int256 internal constant MIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968; /// @dev The minimum whole value a signed 59.18-decimal fixed-point number can have. int256 internal constant MIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000; /// @dev How many trailing decimals can be represented. int256 internal constant SCALE = 1e18; /// INTERNAL FUNCTIONS /// /// @notice Calculate the absolute value of x. /// /// @dev Requirements: /// - x must be greater than MIN_SD59x18. /// /// @param x The number to calculate the absolute value for. /// @param result The absolute value of x. function abs(int256 x) internal pure returns (int256 result) { unchecked { if (x == MIN_SD59x18) { revert PRBMathSD59x18__AbsInputTooSmall(); } result = x < 0 ? -x : x; } } /// @notice Calculates the arithmetic average of x and y, rounding down. /// @param x The first operand as a signed 59.18-decimal fixed-point number. /// @param y The second operand as a signed 59.18-decimal fixed-point number. /// @return result The arithmetic average as a signed 59.18-decimal fixed-point number. function avg(int256 x, int256 y) internal pure returns (int256 result) { // The operations can never overflow. unchecked { int256 sum = (x >> 1) + (y >> 1); if (sum < 0) { // If at least one of x and y is odd, we add 1 to the result. This is because shifting negative numbers to the // right rounds down to infinity. assembly { result := add(sum, and(or(x, y), 1)) } } else { // If both x and y are odd, we add 1 to the result. This is because if both numbers are odd, the 0.5 // remainder gets truncated twice. result = sum + (x & y & 1); } } } /// @notice Yields the least greatest signed 59.18 decimal fixed-point number greater than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be less than or equal to MAX_WHOLE_SD59x18. /// /// @param x The signed 59.18-decimal fixed-point number to ceil. /// @param result The least integer greater than or equal to x, as a signed 58.18-decimal fixed-point number. function ceil(int256 x) internal pure returns (int256 result) { if (x > MAX_WHOLE_SD59x18) { revert PRBMathSD59x18__CeilOverflow(x); } unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; } else { // Solidity uses C fmod style, which returns a modulus with the same sign as x. result = x - remainder; if (x > 0) { result += SCALE; } } } } /// @notice Divides two signed 59.18-decimal fixed-point numbers, returning a new signed 59.18-decimal fixed-point number. /// /// @dev Variant of "mulDiv" that works with signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - All from "PRBMath.mulDiv". /// - None of the inputs can be MIN_SD59x18. /// - The denominator cannot be zero. /// - The result must fit within int256. /// /// Caveats: /// - All from "PRBMath.mulDiv". /// /// @param x The numerator as a signed 59.18-decimal fixed-point number. /// @param y The denominator as a signed 59.18-decimal fixed-point number. /// @param result The quotient as a signed 59.18-decimal fixed-point number. function div(int256 x, int256 y) internal pure returns (int256 result) { if (x == MIN_SD59x18 || y == MIN_SD59x18) { revert PRBMathSD59x18__DivInputTooSmall(); } // Get hold of the absolute values of x and y. uint256 ax; uint256 ay; unchecked { ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); } // Compute the absolute value of (x*SCALE)÷y. The result must fit within int256. uint256 rAbs = PRBMath.mulDiv(ax, uint256(SCALE), ay); if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__DivOverflow(rAbs); } // Get the signs of x and y. uint256 sx; uint256 sy; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) } // XOR over sx and sy. This is basically checking whether the inputs have the same sign. If yes, the result // should be positive. Otherwise, it should be negative. result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs); } /// @notice Returns Euler's number as a signed 59.18-decimal fixed-point number. /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant). function e() internal pure returns (int256 result) { result = 2_718281828459045235; } /// @notice Calculates the natural exponent of x. /// /// @dev Based on the insight that e^x = 2^(x * log2(e)). /// /// Requirements: /// - All from "log2". /// - x must be less than 133.084258667509499441. /// /// Caveats: /// - All from "exp2". /// - For any x less than -41.446531673892822322, the result is zero. /// /// @param x The exponent as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function exp(int256 x) internal pure returns (int256 result) { // Without this check, the value passed to "exp2" would be less than -59.794705707972522261. if (x < -41_446531673892822322) { return 0; } // Without this check, the value passed to "exp2" would be greater than 192. if (x >= 133_084258667509499441) { revert PRBMathSD59x18__ExpInputTooBig(x); } // Do the fixed-point multiplication inline to save gas. unchecked { int256 doubleScaleProduct = x * LOG2_E; result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE); } } /// @notice Calculates the binary exponent of x using the binary fraction method. /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693. /// /// Requirements: /// - x must be 192 or less. /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - For any x less than -59.794705707972522261, the result is zero. /// /// @param x The exponent as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function exp2(int256 x) internal pure returns (int256 result) { // This works because 2^(-x) = 1/2^x. if (x < 0) { // 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero. if (x < -59_794705707972522261) { return 0; } // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. unchecked { result = 1e36 / exp2(-x); } } else { // 2^192 doesn't fit within the 192.64-bit format used internally in this function. if (x >= 192e18) { revert PRBMathSD59x18__Exp2InputTooBig(x); } unchecked { // Convert x to the 192.64-bit fixed-point format. uint256 x192x64 = (uint256(x) << 64) / uint256(SCALE); // Safe to convert the result to int256 directly because the maximum input allowed is 192. result = int256(PRBMath.exp2(x192x64)); } } } /// @notice Yields the greatest signed 59.18 decimal fixed-point number less than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be greater than or equal to MIN_WHOLE_SD59x18. /// /// @param x The signed 59.18-decimal fixed-point number to floor. /// @param result The greatest integer less than or equal to x, as a signed 58.18-decimal fixed-point number. function floor(int256 x) internal pure returns (int256 result) { if (x < MIN_WHOLE_SD59x18) { revert PRBMathSD59x18__FloorUnderflow(x); } unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; } else { // Solidity uses C fmod style, which returns a modulus with the same sign as x. result = x - remainder; if (x < 0) { result -= SCALE; } } } } /// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right /// of the radix point for negative numbers. /// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part /// @param x The signed 59.18-decimal fixed-point number to get the fractional part of. /// @param result The fractional part of x as a signed 59.18-decimal fixed-point number. function frac(int256 x) internal pure returns (int256 result) { unchecked { result = x % SCALE; } } /// @notice Converts a number from basic integer form to signed 59.18-decimal fixed-point representation. /// /// @dev Requirements: /// - x must be greater than or equal to MIN_SD59x18 divided by SCALE. /// - x must be less than or equal to MAX_SD59x18 divided by SCALE. /// /// @param x The basic integer to convert. /// @param result The same number in signed 59.18-decimal fixed-point representation. function fromInt(int256 x) internal pure returns (int256 result) { unchecked { if (x < MIN_SD59x18 / SCALE) { revert PRBMathSD59x18__FromIntUnderflow(x); } if (x > MAX_SD59x18 / SCALE) { revert PRBMathSD59x18__FromIntOverflow(x); } result = x * SCALE; } } /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down. /// /// @dev Requirements: /// - x * y must fit within MAX_SD59x18, lest it overflows. /// - x * y cannot be negative. /// /// @param x The first operand as a signed 59.18-decimal fixed-point number. /// @param y The second operand as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function gm(int256 x, int256 y) internal pure returns (int256 result) { if (x == 0) { return 0; } unchecked { // Checking for overflow this way is faster than letting Solidity do it. int256 xy = x * y; if (xy / x != y) { revert PRBMathSD59x18__GmOverflow(x, y); } // The product cannot be negative. if (xy < 0) { revert PRBMathSD59x18__GmNegativeProduct(x, y); } // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE // during multiplication. See the comments within the "sqrt" function. result = int256(PRBMath.sqrt(uint256(xy))); } } /// @notice Calculates 1 / x, rounding toward zero. /// /// @dev Requirements: /// - x cannot be zero. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the inverse. /// @return result The inverse as a signed 59.18-decimal fixed-point number. function inv(int256 x) internal pure returns (int256 result) { unchecked { // 1e36 is SCALE * SCALE. result = 1e36 / x; } } /// @notice Calculates the natural logarithm of x. /// /// @dev Based on the insight that ln(x) = log2(x) / log2(e). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// - This doesn't return exactly 1 for 2718281828459045235, for that we would need more fine-grained precision. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the natural logarithm. /// @return result The natural logarithm as a signed 59.18-decimal fixed-point number. function ln(int256 x) internal pure returns (int256 result) { // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x) // can return is 195205294292027477728. unchecked { result = (log2(x) * SCALE) / LOG2_E; } } /// @notice Calculates the common logarithm of x. /// /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common /// logarithm based on the insight that log10(x) = log2(x) / log2(10). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the common logarithm. /// @return result The common logarithm as a signed 59.18-decimal fixed-point number. function log10(int256 x) internal pure returns (int256 result) { if (x <= 0) { revert PRBMathSD59x18__LogInputTooSmall(x); } // Note that the "mul" in this block is the assembly mul operation, not the "mul" function defined in this contract. // prettier-ignore assembly { switch x case 1 { result := mul(SCALE, sub(0, 18)) } case 10 { result := mul(SCALE, sub(1, 18)) } case 100 { result := mul(SCALE, sub(2, 18)) } case 1000 { result := mul(SCALE, sub(3, 18)) } case 10000 { result := mul(SCALE, sub(4, 18)) } case 100000 { result := mul(SCALE, sub(5, 18)) } case 1000000 { result := mul(SCALE, sub(6, 18)) } case 10000000 { result := mul(SCALE, sub(7, 18)) } case 100000000 { result := mul(SCALE, sub(8, 18)) } case 1000000000 { result := mul(SCALE, sub(9, 18)) } case 10000000000 { result := mul(SCALE, sub(10, 18)) } case 100000000000 { result := mul(SCALE, sub(11, 18)) } case 1000000000000 { result := mul(SCALE, sub(12, 18)) } case 10000000000000 { result := mul(SCALE, sub(13, 18)) } case 100000000000000 { result := mul(SCALE, sub(14, 18)) } case 1000000000000000 { result := mul(SCALE, sub(15, 18)) } case 10000000000000000 { result := mul(SCALE, sub(16, 18)) } case 100000000000000000 { result := mul(SCALE, sub(17, 18)) } case 1000000000000000000 { result := 0 } case 10000000000000000000 { result := SCALE } case 100000000000000000000 { result := mul(SCALE, 2) } case 1000000000000000000000 { result := mul(SCALE, 3) } case 10000000000000000000000 { result := mul(SCALE, 4) } case 100000000000000000000000 { result := mul(SCALE, 5) } case 1000000000000000000000000 { result := mul(SCALE, 6) } case 10000000000000000000000000 { result := mul(SCALE, 7) } case 100000000000000000000000000 { result := mul(SCALE, 8) } case 1000000000000000000000000000 { result := mul(SCALE, 9) } case 10000000000000000000000000000 { result := mul(SCALE, 10) } case 100000000000000000000000000000 { result := mul(SCALE, 11) } case 1000000000000000000000000000000 { result := mul(SCALE, 12) } case 10000000000000000000000000000000 { result := mul(SCALE, 13) } case 100000000000000000000000000000000 { result := mul(SCALE, 14) } case 1000000000000000000000000000000000 { result := mul(SCALE, 15) } case 10000000000000000000000000000000000 { result := mul(SCALE, 16) } case 100000000000000000000000000000000000 { result := mul(SCALE, 17) } case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) } case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) } case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) } case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) } case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) } case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) } case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) } case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) } case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) } case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) } case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) } case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) } case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) } case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) } case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) } case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) } case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) } case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) } case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) } case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) } case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) } case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) } case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) } case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) } default { result := MAX_SD59x18 } } if (result == MAX_SD59x18) { // Do the fixed-point division inline to save gas. The denominator is log2(10). unchecked { result = (log2(x) * SCALE) / 3_321928094887362347; } } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than zero. /// /// Caveats: /// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm. /// @return result The binary logarithm as a signed 59.18-decimal fixed-point number. function log2(int256 x) internal pure returns (int256 result) { if (x <= 0) { revert PRBMathSD59x18__LogInputTooSmall(x); } unchecked { // This works because log2(x) = -log2(1/x). int256 sign; if (x >= SCALE) { sign = 1; } else { sign = -1; // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. assembly { x := div(1000000000000000000000000000000000000, x) } } // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n). uint256 n = PRBMath.mostSignificantBit(uint256(x / SCALE)); // The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow // because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1. result = int256(n) * SCALE; // This is y = x * 2^(-n). int256 y = x >> n; // If y = 1, the fractional part is zero. if (y == SCALE) { return result * sign; } // Calculate the fractional part via the iterative approximation. // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster. for (int256 delta = int256(HALF_SCALE); delta > 0; delta >>= 1) { y = (y * y) / SCALE; // Is y^2 > 2 and so in the range [2,4)? if (y >= 2 * SCALE) { // Add the 2^(-m) factor to the logarithm. result += delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } result *= sign; } } /// @notice Multiplies two signed 59.18-decimal fixed-point numbers together, returning a new signed 59.18-decimal /// fixed-point number. /// /// @dev Variant of "mulDiv" that works with signed numbers and employs constant folding, i.e. the denominator is /// always 1e18. /// /// Requirements: /// - All from "PRBMath.mulDivFixedPoint". /// - None of the inputs can be MIN_SD59x18 /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works. /// /// @param x The multiplicand as a signed 59.18-decimal fixed-point number. /// @param y The multiplier as a signed 59.18-decimal fixed-point number. /// @return result The product as a signed 59.18-decimal fixed-point number. function mul(int256 x, int256 y) internal pure returns (int256 result) { if (x == MIN_SD59x18 || y == MIN_SD59x18) { revert PRBMathSD59x18__MulInputTooSmall(); } unchecked { uint256 ax; uint256 ay; ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); uint256 rAbs = PRBMath.mulDivFixedPoint(ax, ay); if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__MulOverflow(rAbs); } uint256 sx; uint256 sy; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) } result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs); } } /// @notice Returns PI as a signed 59.18-decimal fixed-point number. function pi() internal pure returns (int256 result) { result = 3_141592653589793238; } /// @notice Raises x to the power of y. /// /// @dev Based on the insight that x^y = 2^(log2(x) * y). /// /// Requirements: /// - All from "exp2", "log2" and "mul". /// - z cannot be zero. /// /// Caveats: /// - All from "exp2", "log2" and "mul". /// - Assumes 0^0 is 1. /// /// @param x Number to raise to given power y, as a signed 59.18-decimal fixed-point number. /// @param y Exponent to raise x to, as a signed 59.18-decimal fixed-point number. /// @return result x raised to power y, as a signed 59.18-decimal fixed-point number. function pow(int256 x, int256 y) internal pure returns (int256 result) { if (x == 0) { result = y == 0 ? SCALE : int256(0); } else { result = exp2(mul(log2(x), y)); } } /// @notice Raises x (signed 59.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the /// famous algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring /// /// Requirements: /// - All from "abs" and "PRBMath.mulDivFixedPoint". /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - All from "PRBMath.mulDivFixedPoint". /// - Assumes 0^0 is 1. /// /// @param x The base as a signed 59.18-decimal fixed-point number. /// @param y The exponent as an uint256. /// @return result The result as a signed 59.18-decimal fixed-point number. function powu(int256 x, uint256 y) internal pure returns (int256 result) { uint256 xAbs = uint256(abs(x)); // Calculate the first iteration of the loop in advance. uint256 rAbs = y & 1 > 0 ? xAbs : uint256(SCALE); // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster. uint256 yAux = y; for (yAux >>= 1; yAux > 0; yAux >>= 1) { xAbs = PRBMath.mulDivFixedPoint(xAbs, xAbs); // Equivalent to "y % 2 == 1" but faster. if (yAux & 1 > 0) { rAbs = PRBMath.mulDivFixedPoint(rAbs, xAbs); } } // The result must fit within the 59.18-decimal fixed-point representation. if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__PowuOverflow(rAbs); } // Is the base negative and the exponent an odd number? bool isNegative = x < 0 && y & 1 == 1; result = isNegative ? -int256(rAbs) : int256(rAbs); } /// @notice Returns 1 as a signed 59.18-decimal fixed-point number. function scale() internal pure returns (int256 result) { result = SCALE; } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Requirements: /// - x cannot be negative. /// - x must be less than MAX_SD59x18 / SCALE. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the square root. /// @return result The result as a signed 59.18-decimal fixed-point . function sqrt(int256 x) internal pure returns (int256 result) { unchecked { if (x < 0) { revert PRBMathSD59x18__SqrtNegativeInput(x); } if (x > MAX_SD59x18 / SCALE) { revert PRBMathSD59x18__SqrtOverflow(x); } // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two signed // 59.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root). result = int256(PRBMath.sqrt(uint256(x * SCALE))); } } /// @notice Converts a signed 59.18-decimal fixed-point number to basic integer form, rounding down in the process. /// @param x The signed 59.18-decimal fixed-point number to convert. /// @return result The same number in basic integer form. function toInt(int256 x) internal pure returns (int256 result) { unchecked { result = x / SCALE; } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev 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 VORSafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function safeAdd(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 safeSub(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 safeMul(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 saveDiv(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 safeMod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20_Ex { /** * @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 Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool); /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IVORCoordinator { function getProviderAddress(bytes32 _keyHash) external view returns (address); function getProviderFee(bytes32 _keyHash) external view returns (uint96); function getProviderGranularFee(bytes32 _keyHash, address _consumer) external view returns (uint96); function randomnessRequest(bytes32 keyHash, uint256 consumerSeed, uint256 feePaid) external; } /** * @title VORRequestIDBase */ contract VORRequestIDBase { /** * @notice returns the seed which is actually input to the VOR coordinator * * @dev To prevent repetition of VOR 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 VOR seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVORInputSeed( 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 _vORInputSeed The seed to be passed directly to the VOR * @return The id for this request * * @dev Note that _vORInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVORInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vORInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vORInputSeed)); } } /** * @title VORConsumerBase * @notice Interface for contracts using VOR randomness * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * to Vera the verifier in such a way that Vera can be sure he's not * making his output up to suit himself. Reggie provides Vera a public key * to which he knows the secret key. Each time Vera provides a seed to * Reggie, he gives back a value which is computed completely * deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * correctly computed once Reggie tells it to her, but without that proof, * the output is indistinguishable to her from a uniform random sample * from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * to talk to Vera the verifier about the work Reggie is doing, to provide * simple access to a verifiable source of randomness. * * @dev USAGE * * @dev Calling contracts must inherit from VORConsumerBase, and can * initialize VORConsumerBase's attributes in their constructor as * shown: * * ``` * contract VORConsumer { * constuctor(<other arguments>, address _vorCoordinator, address _xfund) * VORConsumerBase(_vorCoordinator, _xfund) public { * <initialization with other arguments goes here> * } * } * ``` * @dev The oracle will have given you an ID for the VOR keypair they have * committed to (let's call it keyHash), and have told you the minimum xFUND * price for VOR service. Make sure your contract has sufficient xFUND, and * call requestRandomness(keyHash, fee, seed), where seed is the input you * want to generate randomness from. * * @dev Once the VORCoordinator has received and validated the oracle's response * to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * makeRequestId(keyHash, seed). If your contract could have concurrent * requests open, you can use the requestId to track which seed is * associated with which randomness. See VORRequestIDBase.sol for more * details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * differ. (Which is critical to making unpredictable randomness! See the * next section.) * * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * could spoof a VOR response with any random value, so it's critical that * it cannot be directly called by anything other than this base contract * (specifically, by the VORConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * from malicious interference, it's best if you can write it so that all * behaviors implied by a VOR response are executed *during* your * fulfillRandomness method. If your contract must store the response (or * anything derived from it) and use it later, you must ensure that any * user-significant behavior which depends on that stored value cannot be * manipulated by a subsequent VOR request. * * @dev Similarly, both miners and the VOR oracle itself have some influence * over the order in which VOR responses appear on the blockchain, so if * your contract could have multiple VOR requests in flight simultaneously, * you must ensure that the order in which the VOR responses arrive cannot * be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VOR is mixed with the block hash of the * block in which the request is made, user-provided seeds have no impact * on its economic security properties. They are only included for API * compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * call is mixed into the input to the VOR *last*, a sufficiently powerful * miner could, in principle, fork the blockchain to evict the block * containing the request, forcing the request to be included in a * different block with a different hash, and therefore a different input * to the VOR. However, such an attack would incur a substantial economic * cost. This cost scales with the number of blocks the VOR oracle waits * until it calls responds to a request. */ abstract contract VORConsumerBase is VORRequestIDBase { using VORSafeMath for uint256; /** * @notice fulfillRandomness handles the VOR 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 VORConsumerBase expects its subcontracts to have a method with this * signature, and will call it once it has verified the proof * associated with the randomness. (It is triggered via a call to * rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VOR output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @notice requestRandomness initiates a request for VOR output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * by the Oracle, and verified by the vorCoordinator. * * @dev The _keyHash must already be registered with the VORCoordinator, and * the _fee must exceed the fee specified during registration of the * _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * compatibility with older versions. It can't *hurt* to mix in some of * your own randomness, here, but it's not necessary because the VOR * oracle will mix the hash of the block containing your request into the * VOR seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of xFUND to send with the request * @param _seed seed mixed into the input of the VOR. * * @return requestId unique ID for this request * * The returned requestId can be used to distinguish responses to * concurrent requests. It is passed as the first argument to * fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed) internal returns (bytes32 requestId) { IVORCoordinator(vorCoordinator).randomnessRequest(_keyHash, _seed, _fee); // This is the seed passed to VORCoordinator. 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 VOR cryptographic machinery. uint256 vORSeed = makeVORInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VORCoordinator.nonces[_keyHash][this], which was incremented by the above // successful VORCoordinator.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].safeAdd(1); return makeRequestId(_keyHash, vORSeed); } /** * @notice _increaseVorCoordinatorAllowance is a helper function to increase token allowance for * the VORCoordinator * Allows this contract to increase the xFUND allowance for the VORCoordinator contract * enabling it to pay request fees on behalf of this contract. * NOTE: it is hightly recommended to wrap this around a function that uses, * for example, OpenZeppelin's onlyOwner modifier * * @param _amount uint256 amount to increase allowance by */ function _increaseVorCoordinatorAllowance(uint256 _amount) internal returns (bool) { require(xFUND.increaseAllowance(vorCoordinator, _amount), "failed to increase allowance"); return true; } /** * @notice _setVORCoordinator is a helper function to enable setting the VORCoordinator address * NOTE: it is hightly recommended to wrap this around a function that uses, * for example, OpenZeppelin's onlyOwner modifier * * @param _vorCoordinator address new VORCoordinator address */ function _setVORCoordinator(address _vorCoordinator) internal { vorCoordinator = _vorCoordinator; } address internal immutable xFUNDAddress; IERC20_Ex internal immutable xFUND; address internal vorCoordinator; // Nonces for each VOR key from which randomness has been requested. // // Must stay in sync with VORCoordinator[_keyHash][this] /* keyHash */ /* nonce */ mapping(bytes32 => uint256) private nonces; /** * @param _vorCoordinator address of VORCoordinator contract * @param _xfund address of xFUND token contract */ constructor(address _vorCoordinator, address _xfund) internal { vorCoordinator = _vorCoordinator; xFUNDAddress = _xfund; xFUND = IERC20_Ex(_xfund); } /** * @notice rawFulfillRandomness is called by VORCoordinator when it receives a valid VOR * proof. rawFulfillRandomness then calls fulfillRandomness, after validating * the origin of the call */ function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vorCoordinator, "Only VORCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title 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); } /** * @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); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev 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 {} } /** * @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); } /** * @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(); } } // @title Base64 // @notice Provides a function for encoding some bytes in base64 // @author Brecht Devos <brecht@loopring.org> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } interface IPlayingCards { function getCardNumberAsUint(uint8 cardId) external view returns (uint8); function getCardSuitAsUint(uint8 cardId) external view returns (uint8); function getCardNumberAsStr(uint8 cardId) external view returns (string memory); function getCardSuitAsStr(uint8 cardId) external view returns (string memory); function getCardAsString(uint8 cardId) external view returns (string memory); function getCardAsSvg(uint8 cardId) external view returns (string memory); function getCardAsComponents(uint8 cardId) external view returns (uint8 number, uint8 suit); function getCardBody(uint8 numberId, uint8 suitId, uint256 fX, uint256 sX, uint256 rX) external pure returns (string memory); function getSuitPath(uint8 suitId) external pure returns (string memory); function getNumberPath(uint8 numberId) external pure returns (string memory); } contract HoldemHeroesBase is ERC721Enumerable, Ownable { // a start-hand combination struct Hand { uint8 card1; // 0 - 51 uint8 card2; // 0 - 51 } uint256 public constant MAX_NFT_SUPPLY = 1326; // final totalSupply of NFTs // sha256 hash of all generated and shuffled hands bytes32 public constant HAND_PROVENANCE = 0xbcd1a23f7cca99ec419590e58d82db68573d59d2cdf88a901c5c25edea2c075d; // start index for mapping tokenId on to handId - set during the distribution phase uint256 public startingIndex; // time after which hands are randomised and allocated to token Ids uint256 public REVEAL_TIMESTAMP; // hands have been revealed bool public REVEALED; // ranks uploaded - used only during uploadHandRanks function bool public RANKS_UPLOADED; // the block number in which the final hands were revealed uint256 public revealBlock; // IPFS hash for provenance JSON - will be set when the last hand batch is revealed string public PROVENANCE_IPFS; // array of 1326 possible start hand combinations Hand[1326] public hands; // used during reveal function to ensure batches are uploaded sequentially // according to provenance uint16 public handUploadId; uint8 public nextExpectedBatchId = 0; // mapping to ensure batch is not re-uploaded. Only used during reveal function mapping(bytes32 => bool) private isHandRevealed; // Mapping to hold hand ranks. Requires populating during contract initialisation mapping (bytes32 => uint8) public handRanks; // The playing cards contract on which HEH is built IPlayingCards public immutable playingCards; /* * EVENTS */ event BatchRevealed(uint16 startHandId, uint16 endHandId, bytes32 batchHash, uint8 batchId); event RanksInitialised(); /** * @dev constructor * @dev initialises some basic variables. * * @param _revealTimestamp uint256 - unix timestamp for when cards will be revealed and distributed * @param _playingCards address - address of Playing Cards contract */ constructor(uint256 _revealTimestamp, address _playingCards) ERC721("Holdem Heroes", "HEH") Ownable() { REVEAL_TIMESTAMP = _revealTimestamp; REVEALED = false; RANKS_UPLOADED = false; handUploadId = 0; playingCards = IPlayingCards(_playingCards); } /* * ADMIN FUNCTIONS */ /** * @dev uploadHandRanks upload the 169 start hand ranks, which are referenced * @dev by the hand getter functions. Hand ranks are stored as a mapping of a * @dev sha256 hash and the integer rank value. The hash is generated from a * @dev concatenation of the word "rank" and the hand's name. e.g. * keccak256("rankA5s") => 28 * * @param rankHashes bytes32[] array of sha256 hashes * @param ranks uint8[] array of corresponding ranks for rankHashes */ function uploadHandRanks(bytes32[] memory rankHashes, uint8[] memory ranks) external onlyOwner { require(!RANKS_UPLOADED, "uploaded"); for (uint8 i = 0; i < rankHashes.length; i++) { handRanks[rankHashes[i]] = ranks[i]; } RANKS_UPLOADED = true; emit RanksInitialised(); } /** * @dev withdrawETH allows contract owner to withdraw ether */ function withdrawETH() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } /** * @dev reveal is used to upload and reveal the generated start hand combinations. * @dev hands are uploaded in batches, with each batch containing n * @dev hands. each hand is a uint8[] array of card IDs, e.g. [2, 3] * @dev with each batch represented as a 2d array of hands, for example, [[2, 3], [3, 4], ...] * @dev Batches must be uploaded sequentially according to provenance. * * @param inputs uint8[2][] batch of hands * @param batchId uint8 id of the batch being revealed * @param ipfs string IPFS hash of provenance.json. Sent with final batch only */ function reveal(uint8[2][] memory inputs, uint8 batchId, string memory ipfs) public onlyOwner { require(block.timestamp >= REVEAL_TIMESTAMP, "not yet"); require(handUploadId < 1325, "revealed"); require(batchId == nextExpectedBatchId, "seq incorrect"); bytes32 dataHash = keccak256(abi.encodePacked(inputs)); require(!isHandRevealed[dataHash], "already added"); isHandRevealed[dataHash] = true; for (uint8 i = 0; i < inputs.length; i++) { hands[handUploadId] = Hand(inputs[i][0],inputs[i][1]); handUploadId = handUploadId + 1; } emit BatchRevealed(handUploadId - uint16(inputs.length), handUploadId - 1, dataHash, batchId); if (handUploadId == 1326) { REVEALED = true; PROVENANCE_IPFS = ipfs; revealBlock = block.number; } else { nextExpectedBatchId = nextExpectedBatchId + 1; } } /* * PUBLIC GETTERS */ /** * @dev getHandShape returns the shape for a given hand ID, for example "Suited" or "s" * * @param handId uint16 ID of the hand from 0 - 1325 * @param abbreviate bool whether or not to abbreviate ("s" instead of Suited" if true) * @return string shape of hand */ function getHandShape(uint16 handId, bool abbreviate) public validHandId(handId) view returns (string memory) { uint8 card1N = playingCards.getCardNumberAsUint(hands[handId].card1); uint8 card2N = playingCards.getCardNumberAsUint(hands[handId].card2); uint8 card1S = playingCards.getCardSuitAsUint(hands[handId].card1); uint8 card2S = playingCards.getCardSuitAsUint(hands[handId].card2); if (card1N == card2N) { return abbreviate ? "" : "Pair"; } else if (card1S == card2S) { return abbreviate ? "s" : "Suited"; } else { return abbreviate ? "o" : "Offsuit"; } } /** * @dev getHandAsCardIds returns the card IDs (0 - 51) for a given hand ID, for example 12,24 * * @param handId uint16 ID of the hand from 0 - 1325 * @return card1 uint8 ID of card 1 (0 - 51) * @return card2 uint8 ID of card 2 (0 - 51) */ function getHandAsCardIds(uint16 handId) public validHandId(handId) view returns (uint8 card1, uint8 card2) { Hand storage hand = hands[handId]; if (playingCards.getCardNumberAsUint(hand.card1) > playingCards.getCardNumberAsUint(hand.card2)) { return (hand.card1, hand.card2); } else { return (hand.card2, hand.card1); } } /** * @dev getHandName returns the canonical name for a given hand ID. This is a concatenation of * @dev Card1 + Card2 + Shape, with the cards ordered by card number in descending order. * @dev E.g. A5s * * @param handId uint16 ID of the hand from 0 - 1325 * @return string hand name */ function getHandName(uint16 handId) public validHandId(handId) view returns (string memory) { string memory shape = getHandShape(handId, true); (uint8 card1, uint8 card2) = getHandAsCardIds(handId); return string(abi.encodePacked(playingCards.getCardNumberAsStr(card1), playingCards.getCardNumberAsStr(card2), shape)); } /** * @dev getHandRank returns the canonical rank for a given hand ID. Lower is better * * @param handId uint16 ID of the hand from 0 - 1325 * @return string hand rank */ function getHandRank(uint16 handId) public validHandId(handId) view returns (uint8) { return handRanks[keccak256(abi.encodePacked("rank", getHandName(handId)))]; } /** * @dev getHandAsString returns a concatenation of the card names * * @param handId uint16 ID of the hand from 0 - 1325 * @return string hand - cards names concatenated, e.g. AsAc */ function getHandAsString(uint16 handId) public validHandId(handId) view returns (string memory) { (uint8 card1, uint8 card2) = getHandAsCardIds(handId); return string(abi.encodePacked(playingCards.getCardAsString(card1), playingCards.getCardAsString(card2))); } /** * @dev getHandAsSvg returns the SVG XML for a hand, which can be rendered as an img src in a UI * * @param handId uint16 ID of the hand from 0 - 1325 * @return string SVG XML of a hand of 2 cards */ function getHandAsSvg(uint16 handId) public validHandId(handId) view returns (string memory) { (uint8 card1, uint8 card2) = getHandAsCardIds(handId); string[4] memory parts; parts[0] = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 148 62\" width=\"5in\" height=\"2.147in\">"; parts[1] = playingCards.getCardBody(playingCards.getCardNumberAsUint(card1), playingCards.getCardSuitAsUint(card1), 7, 32, 2); parts[2] = playingCards.getCardBody(playingCards.getCardNumberAsUint(card2), playingCards.getCardSuitAsUint(card2), 82, 107, 76); parts[3] = "</svg>"; string memory output = string( abi.encodePacked(parts[0], parts[1], parts[2], parts[3]) ); return output; } /** * @dev getHandHash returns a hand's hash, which can be used to match against the * @dev published provenance. Hand hashes can be sequentially concatenated and the * @dev concatenation itself hashed (after removing each hand hash's 0x prefix) * @dev to get the provenance hash. This provenance hash should match both the published * @dev hash and the HAND_PROVENANCE constant in this contract * * @param handId uint16 ID of the hand from 0 - 1325 * @return string hash of the hand */ function getHandHash(uint16 handId) public validHandId(handId) view returns (bytes32) { (uint8 card1, uint8 card2) = getHandAsCardIds(handId); return keccak256(abi.encodePacked( toString(handId), getHandAsString(handId), toString(card1), toString(playingCards.getCardNumberAsUint(card1)), toString(playingCards.getCardSuitAsUint(card1)), toString(card2), toString(playingCards.getCardNumberAsUint(card2)), toString(playingCards.getCardSuitAsUint(card2)) ) ); } /** * @dev tokenIdToHandId maps a given token ID onto its distributed hand ID * @dev Note - this will only run after all hands have been revealed * @dev and distributed. * * @param _tokenId uint256 ID of the NFT token from 0 - 1325 * @return uint16 hand ID associate to the token */ function tokenIdToHandId(uint256 _tokenId) public view returns (uint16) { require(_tokenId >= 0 && _tokenId < 1326, "invalid id"); require(startingIndex > 0, "not distributed"); return uint16((_tokenId + startingIndex) % MAX_NFT_SUPPLY); } /** * @dev tokenURI generates the base64 encoded JSON of the NFT itself. tokenURI will first call * @dev tokenIdToHandId to find which hand the token is for. It will then generate * @dev and output the encoded JSON containing the SVG image, name, description and * @dev attributes. * @dev Note - this will only run after all hands have been revealed * @dev and distributed. * * @param _tokenId uint256 ID of the NFT token from 0 - 1325 * @return string the token's NFT JSON */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { // we need to map the token ID onto the assigned hand ID, // based on the distribution's startingIndex. This is only available // AFTER distribution has occurred, and will return an error otherwise uint16 handId = tokenIdToHandId(_tokenId); string memory handName = getHandAsString(handId); string memory shape = getHandShape(handId, false); string memory hand = getHandName(handId); string memory rank = toString(getHandRank(handId)); string memory json = Base64.encode( bytes( string( abi.encodePacked( "{\"name\": \"", handName, "\", \"description\": \"holdemheroes.com\",", getAttributes(shape, hand, rank), "\"image\": \"data:image/svg+xml;base64,", Base64.encode(bytes(getHandAsSvg(handId))), "\"}" ) ) ) ); string memory output = string(abi.encodePacked("data:application/json;base64,", json)); return output; } /* * PRIVATE FUNCTIONS */ /** * @dev getAttributes will generate the attributes JSON for embedding into the NFT JSON * * @param shape string shape * @param hand string hand * @param rank string rank * @return string attribute JSON */ function getAttributes(string memory shape, string memory hand, string memory rank) private pure returns (string memory) { return string( abi.encodePacked( "\"attributes\": [{ \"trait_type\": \"Shape\", \"value\": \"", shape, "\"},", "{ \"trait_type\": \"Hand\", \"value\": \"", hand, "\"},", "{ \"trait_type\": \"Rank\", \"value\": \"", rank, "\"}]," ) ); } /** * @dev toString converts a given uint256 to a string. Primarily used in SVG, JSON, string name, * @dev and hash generation * * @param value uint256 number to convert * @return string number as a string */ function toString(uint256 value) private pure returns (string memory) { // Inspired by OraclizeAPI"s implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol uint256 _tmpN = value; if (_tmpN == 0) { return "0"; } uint256 temp = _tmpN; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (_tmpN != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(_tmpN % 10))); _tmpN /= 10; } return string(buffer); } /* * MODIFIERS */ /** * @dev validHandId ensures a given hand Id is valid * * @param handId uint16 id of hand */ modifier validHandId(uint16 handId) { require(handId >= 0 && handId < 1326, "invalid handId"); require(REVEALED, "not revealed"); _; } } contract HoldemHeroes is Ownable, HoldemHeroesBase, VORConsumerBase { using PRBMathSD59x18 for int256; // max number of NFTs allowed per address uint256 public MAX_PER_ADDRESS_OR_TX; // block number for when public sale opens uint256 public SALE_START_BLOCK_NUM; uint256 public basePostRevealPrice = 1 ether; /// --------------------------- /// ------- CRISP STATE ------- /// --------------------------- ///@notice block on which last purchase occurred uint256 public lastPurchaseBlock; ///@notice block on which we start decaying price uint256 public priceDecayStartBlock; ///@notice Starting EMS, before time decay. 59.18-decimal fixed-point int256 public nextPurchaseStartingEMS; ///@notice Starting price for next purchase, before time decay. 59.18-decimal fixed-point int256 public nextPurchaseStartingPrice; /// --------------------------- /// ---- CRISP PARAMETERS ----- /// --------------------------- ///@notice EMS target. 59.18-decimal fixed-point int256 public immutable targetEMS; ///@notice controls decay of sales in EMS. 59.18-decimal fixed-point int256 public immutable saleHalflife; ///@notice controls upward price movement. 59.18-decimal fixed-point int256 public immutable priceSpeed; ///@notice controls price decay. 59.18-decimal fixed-point int256 public immutable priceHalflife; /* * EVENTS */ event DistributionBegun(bytes32 requestId, address sender); event DistributionResult(bytes32 requestId, uint256 randomness, uint256 startingIndex); /** * @dev constructor * @dev initialises some basic variables. * @dev CRISP implementation from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol * * @param _vorCoordinator address - address of VORCoordinator contract * @param _xfund address - address of xFUND contract * @param _playingCards address - address of Playing Cards contract * @param _saleStartBlockNum uint256 - block number for when pre-reveal sale starts. Allows time for card/rank init * @param _revealTimestamp uint256 - unix timestamp for when cards will be revealed and distributed * @param _maxNfts address - max number of NFTs a single wallet address can mint * @param _targetBlocksPerSale int256, e.g. 100 * @param _saleHalflife int256, e.g. 700 * @param _priceSpeed int256, e.g. 1 * @param _priceSpeedDenominator int256, e.g. 4. If _priceSpeed param is 1, final priceSpeed will be 0.25 * @param _priceHalflife int256, e.g. 100 * @param _startingPrice int256, e.g. 100 */ constructor( address _vorCoordinator, address _xfund, address _playingCards, uint256 _saleStartBlockNum, uint256 _revealTimestamp, uint256 _maxNfts, int256 _targetBlocksPerSale, int256 _saleHalflife, int256 _priceSpeed, int256 _priceSpeedDenominator, int256 _priceHalflife, int256 _startingPrice ) VORConsumerBase(_vorCoordinator, _xfund) HoldemHeroesBase(_revealTimestamp, _playingCards) { SALE_START_BLOCK_NUM = (_saleStartBlockNum > block.number) ? _saleStartBlockNum : block.number; MAX_PER_ADDRESS_OR_TX = _maxNfts; // CRISP lastPurchaseBlock = SALE_START_BLOCK_NUM; priceDecayStartBlock = SALE_START_BLOCK_NUM; // scale parameters - see https://github.com/FrankieIsLost/CRISP/blob/master/src/test/CRISP.t.sol int256 targetBlocksPerSale = PRBMathSD59x18.fromInt( _targetBlocksPerSale ); saleHalflife = PRBMathSD59x18.fromInt(_saleHalflife); priceSpeed = PRBMathSD59x18.fromInt(_priceSpeed).div(PRBMathSD59x18.fromInt(_priceSpeedDenominator)); priceHalflife = PRBMathSD59x18.fromInt(_priceHalflife); //calculate target EMS from target blocks per sale targetEMS = PRBMathSD59x18.fromInt(1).div( PRBMathSD59x18.fromInt(1) - PRBMathSD59x18.fromInt(2).pow( -targetBlocksPerSale.div(saleHalflife) ) ); nextPurchaseStartingEMS = targetEMS; nextPurchaseStartingPrice = PRBMathSD59x18.fromInt(int256(_startingPrice)); } /* * ADMIN */ /** * @dev setBasePostRevealPrice allows owner to adjust post-reveal price according to market * * @param newPrice uint256 new base price in wei */ function setBasePostRevealPrice(uint256 newPrice) external onlyOwner { basePostRevealPrice = newPrice; } /* * CRISP FUNCTIONS */ /** * @dev getCurrentEMS gets current EMS based on block number. * @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol * * @return result int256 59.18-decimal fixed-point */ function getCurrentEMS() public view returns (int256 result) { int256 blockInterval = int256(block.number - lastPurchaseBlock); blockInterval = blockInterval.fromInt(); int256 weightOnPrev = PRBMathSD59x18.fromInt(2).pow( -blockInterval.div(saleHalflife) ); result = nextPurchaseStartingEMS.mul(weightOnPrev); } /** * @dev _getNftPrice get quote for purchasing in current block, decaying price as needed. * @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol * * @return result int256 59.18-decimal fixed-point */ function _getNftPrice() internal view returns (int256 result) { if (block.number <= priceDecayStartBlock) { result = nextPurchaseStartingPrice; } //decay price if we are past decay start block else { int256 decayInterval = int256(block.number - priceDecayStartBlock) .fromInt(); int256 decay = (-decayInterval).div(priceHalflife).exp(); result = nextPurchaseStartingPrice.mul(decay); } } /** * @dev getNftPrice get quote for purchasing in current block, decaying price as needed * @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol * * @return result uint256 current price in wei */ function getNftPrice() public view returns (uint256 result) { int256 pricePerNft = _getNftPrice(); result = uint256(pricePerNft.toInt()); } /** * @dev getPostRevealNftPrice get mint price for revealed tokens, based on the hand Rank * @dev lower rank = better hand = higher price. e.g. AA = rank 1 = high price * @dev Note - this can only be used in the event that there are unminted tokens * @dev once the pre-reveal sale has ended. * * @return result uint256 price in wei */ function getPostRevealNftPrice(uint256 _tokenId) public view returns (uint256 result) { uint256 rank = uint256(getHandRank(tokenIdToHandId(_tokenId))); if(rank == 1) { result = basePostRevealPrice; } else { uint256 m = 100 - ((rank * 100) / 169); // get % as int m = (m < 10) ? 10 : m; result = (basePostRevealPrice * m) / 100; } } /** * @dev getNextStartingPriceGet starting price for next purchase before time decay * @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol * * @param lastPurchasePrice int256 last price as 59.18-decimal fixed-point * @return result int256 59.18-decimal fixed-point */ function getNextStartingPrice(int256 lastPurchasePrice) public view returns (int256 result) { int256 mismatchRatio = nextPurchaseStartingEMS.div(targetEMS); if (mismatchRatio > PRBMathSD59x18.fromInt(1)) { result = lastPurchasePrice.mul( PRBMathSD59x18.fromInt(1) + mismatchRatio.mul(priceSpeed) ); } else { result = lastPurchasePrice; } } /** * @dev getPriceDecayStartBlock Find block in which time based price decay should start * @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol * * @return result uint256 block number */ function getPriceDecayStartBlock() internal view returns (uint256 result) { int256 mismatchRatio = nextPurchaseStartingEMS.div(targetEMS); //if mismatch ratio above 1, decay should start in future if (mismatchRatio > PRBMathSD59x18.fromInt(1)) { uint256 decayInterval = uint256( saleHalflife.mul(mismatchRatio.log2()).ceil().toInt() ); result = block.number + decayInterval; } //else decay should start at the current block else { result = block.number; } } /* * MINT & DISTRIBUTION FUNCTIONS */ /** * @dev mintNFTPreReveal is a public payable function which any user can call during the pre-reveal * @dev sale phase. This allows a user to mint up to MAX_PER_ADDRESS_OR_TX tokens. Tokens are * @dev minted sequentially. Mapping of token IDs on to hand IDs (according to provenance) is * @dev executed during the reveal & distribution phase, via a call to VOR. * @dev Correct ether value is expected to pay for tokens. * * @param _numberOfNfts uint256 number of NFTs to mint in this Tx */ function mintNFTPreReveal(uint256 _numberOfNfts) external payable { uint256 numberOfNfts = (_numberOfNfts > 0) ? _numberOfNfts : 1; require(block.number >= SALE_START_BLOCK_NUM, "not started"); require(totalSupply() < MAX_NFT_SUPPLY, "sold out"); require(block.timestamp < REVEAL_TIMESTAMP, "ended"); require(numberOfNfts <= MAX_PER_ADDRESS_OR_TX, "> max per tx"); require(balanceOf(msg.sender) + numberOfNfts <= MAX_PER_ADDRESS_OR_TX, "> mint limit"); require(totalSupply() + numberOfNfts <= MAX_NFT_SUPPLY, "exceeds supply"); int256 pricePerNft = _getNftPrice(); uint256 pricePerNftScaled = uint256(pricePerNft.toInt()); uint256 totalCost = pricePerNftScaled * numberOfNfts; require(msg.value >= totalCost, "eth too low"); for (uint256 i = 0; i < numberOfNfts; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } //update CRISP state updateCrispState(pricePerNft, numberOfNfts); } /** * @dev mintNFTPostReveal is a public payable function which any user can call AFTER the pre-reveal * @dev sale phase. This allows a user to mint any available token ID that hasn't been sold yet. * @dev This function cannot be executed until hands have been revealed and distributed. * @dev Correct ether value is expected to pay for token. * * @param tokenId uint256 NFT Token ID to purchase */ function mintNFTPostReveal(uint256 tokenId) external payable { uint256 price = getPostRevealNftPrice(tokenId); require(msg.value >= price, "eth too low"); _safeMint(msg.sender, tokenId); } /** * @dev beginDistribution is called to initiate distribution and makes a VOR request to generate * @dev a random value. Can only be called after hands have been revealed according to provenance. * * @param _keyHash bytes32 key hash of the VOR Oracle that will handle the request * @param _fee uint256 xFUND fee to pay the VOR Oracle */ function beginDistribution(bytes32 _keyHash, uint256 _fee) public onlyOwner canDistribute { _increaseVorCoordinatorAllowance(_fee); bytes32 requestId = requestRandomness(_keyHash, _fee, uint256(blockhash(block.number-10))); emit DistributionBegun(requestId, msg.sender); } /** * @dev fallbackDistribution is an emergency fallback function which can be called in the event * @dev of the fulfillRandomness function failing. It can only be called by the contract owner * @dev and should only be called if beginDistribution failed. */ function fallbackDistribution() public onlyOwner canDistribute { uint256 sourceBlock = revealBlock; // Just a sanity check (EVM only stores last 256 block hashes) if (block.number - revealBlock > 255) { sourceBlock = block.number-1; } uint256 randomness = uint(blockhash(sourceBlock)); checkAndSetStartIdx(randomness); emit DistributionResult(0x0, 0, startingIndex); } /** * @dev checkAndSetStartIdx is an internal function which will take the generated randomness * @dev and calculate/set the startingIndex mapping value. * * @param _randomness uint256 generated randomness value from VOR etc. */ function checkAndSetStartIdx(uint256 _randomness) internal { // calculate based on randomness startingIndex = _randomness % (MAX_NFT_SUPPLY-1); // Prevent default sequence if (startingIndex == 0) { startingIndex = 1; } if (startingIndex > 1325) { startingIndex = 1325; } } /** * @dev fulfillRandomness is called by the VOR Oracle to fulfil the randomness request. * @dev The randomness value sent is used to calculate the start array Idx onto which * @dev hand IDs are mapped on to the NFT Token IDs. * @dev Can only be called by the correct VOR Oracle, and only via the VORCoordinator contract. * * @param _requestId bytes32 ID of the request fulfilled by the Oracle * @param _randomness uint256 the random number generated by the VOR Oracle */ function fulfillRandomness(bytes32 _requestId, uint256 _randomness) internal override { require(startingIndex == 0, "already done"); checkAndSetStartIdx(_randomness); emit DistributionResult(_requestId, _randomness, startingIndex); } /** * @dev updateCrispState updates the CRISP parameters for dynamic pricing * * @param price int256 current price per NFT paid by user * @param numMinted uint256 number minted in this Tx */ function updateCrispState(int256 price, uint256 numMinted) internal { nextPurchaseStartingEMS = getCurrentEMS() + PRBMathSD59x18.fromInt(int256(numMinted)); nextPurchaseStartingPrice = getNextStartingPrice(price); priceDecayStartBlock = getPriceDecayStartBlock(); lastPurchaseBlock = block.number; } /* * MODIFIERS */ /** * @dev canDistribute checks it's time to distribute */ modifier canDistribute() { require(startingIndex == 0, "already done"); require(REVEALED, "not revealed"); _; } }
getNftPrice get quote for purchasing in current block, decaying price as needed return result uint256 current price in wei/
function getNftPrice() public view returns (uint256 result) { int256 pricePerNft = _getNftPrice(); result = uint256(pricePerNft.toInt()); }
13,810,343
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "../utils/AuthorizableU.sol"; import "../token/XJoyToken.sol"; contract JoyPresale is ContextUpgradeable, AuthorizableU { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; //////////////////////////////////////////////////////////////////////// // State variables //////////////////////////////////////////////////////////////////////// // Info of each coin like USDT, USDC struct CoinInfo { address addr; uint256 rate; } // Info of each Vesting struct VestingInfo { uint8 initClaimablePercent; // Init Claimable Percent uint256 lockingDuration; // Locking Duration uint256 vestingDuration; // Vesting Duration } // Info of each Purchaser struct UserInfo { uint8 vestingIndex; // Index of VestingInfo uint256 depositedAmount; // How many Coins amount the user has deposited. uint256 purchasedAmount; // How many JOY tokens the user has purchased. uint256 withdrawnAmount; // Withdrawn amount uint256 firstDepositedTime; // Last Deposited time uint256 lastWithdrawnTime; // Last Withdrawn time } // The JOY Token IERC20Upgradeable public govToken; // The xJOY Token IERC20Upgradeable public xGovToken; // treasury addresses address[] public treasuryAddrs; uint16 public treasuryIndex; // Coin Info list CoinInfo[] public coinList; uint8 public COIN_DECIMALS; // Vesting Info VestingInfo[] public vestingList; // 0: Seed, 1: Presale A uint8 public VESTING_INDEX; // Sale flag and time. bool public SALE_FLAG; uint256 public SALE_START; uint256 public SALE_DURATION; // GovToken public flag bool public GOVTOKEN_PUBLIC_FLAG; // User address => UserInfo mapping(address => UserInfo) public userList; address[] public userAddrs; // total tokens amounts (all 18 decimals) uint256 public totalSaleAmount; uint256 public totalSoldAmount; uint256 public totalCoinAmount; //////////////////////////////////////////////////////////////////////// // Events & Modifiers //////////////////////////////////////////////////////////////////////// // Events. event TokensPurchased(address indexed purchaser, uint256 coinAmount, uint256 tokenAmount); event TokensWithdrawed(address indexed purchaser, uint256 tokenAmount); // Modifiers. modifier whenSale() { require(checkSalePeriod(), "This is not sale period."); _; } modifier whenVesting(address userAddr) { require(checkVestingPeriod(userAddr), "This is not vesting period."); _; } //////////////////////////////////////////////////////////////////////// // Initialization functions //////////////////////////////////////////////////////////////////////// function initialize( IERC20Upgradeable _govToken, IERC20Upgradeable _xGovToken, uint256 _totalSaleAmount, CoinInfo[] memory _coinList, VestingInfo[] memory _vestingList ) public virtual initializer { __Context_init(); __Authorizable_init(); govToken = _govToken; xGovToken = _xGovToken; treasuryIndex = 0; COIN_DECIMALS = 18; setCoinList(_coinList); setVestingList(_vestingList); VESTING_INDEX = 0; startSale(false); updateSaleDuration(60 days); setGovTokenPublicFlag(false); updateTotalSaleAmount(_totalSaleAmount); } //////////////////////////////////////////////////////////////////////// // External functions //////////////////////////////////////////////////////////////////////// // Update token function updateTokens(IERC20Upgradeable _govToken, IERC20Upgradeable _xGovToken) public onlyAuthorized { govToken = _govToken; xGovToken = _xGovToken; } // Update the treasury address function updateTreasuryAddrs(address[] memory _treasuryAddrs) public onlyOwner { delete treasuryAddrs; for (uint i=0; i<_treasuryAddrs.length; i++) { treasuryAddrs.push(_treasuryAddrs[i]); } treasuryIndex = 0; } function updateTreasuryIndex(uint16 _treasuryIndex) public onlyAuthorized { treasuryIndex = _treasuryIndex; if (treasuryAddrs.length > 0 && treasuryIndex >= treasuryAddrs.length) { treasuryIndex = 0; } } // Set coin list function setCoinList(CoinInfo[] memory _coinList) public onlyAuthorized { delete coinList; for (uint i=0; i<_coinList.length; i++) { coinList.push(_coinList[i]); } } // Update coin info function updateCoinInfo(uint8 index, address addr, uint256 rate) public onlyAuthorized { coinList[index] = CoinInfo(addr, rate); } // Set vesting list function setVestingList(VestingInfo[] memory _vestingList) public onlyAuthorized { delete vestingList; for (uint i=0; i<_vestingList.length; i++) { vestingList.push(_vestingList[i]); } } function setVestingIndex(uint8 index) public onlyAuthorized { VESTING_INDEX = index; } // Update vesting info function updateVestingInfo(uint8 index, uint8 _initClaimablePercent, uint256 _lockingDuration, uint256 _vestingDuration) public onlyAuthorized { if (index == 255) { vestingList.push(VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration)); } else { vestingList[index] = VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration); } } // Start stop sale function startSale(bool bStart) public onlyAuthorized { SALE_FLAG = bStart; if (bStart) { SALE_START = block.timestamp; } } // Set GovToken public flag function setGovTokenPublicFlag(bool bFlag) public onlyAuthorized { GOVTOKEN_PUBLIC_FLAG = bFlag; } // Update sale duration function updateSaleDuration(uint256 saleDuration) public onlyAuthorized { SALE_DURATION = saleDuration; } // check sale period function checkSalePeriod() public view returns (bool) { return SALE_FLAG && block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(SALE_DURATION); } // check locking period function checkLockingPeriod(address userAddr) public view returns (bool) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); // return block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(vestingInfo.lockingDuration); return block.timestamp >= userInfo.firstDepositedTime && block.timestamp <= userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); } // check vesting period function checkVestingPeriod(address userAddr) public view returns (bool) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); // uint256 VESTING_START = SALE_START.add(vestingInfo.lockingDuration); // return block.timestamp >= VESTING_START; uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); return GOVTOKEN_PUBLIC_FLAG || block.timestamp >= VESTING_START; } // Update total sale amount function updateTotalSaleAmount(uint256 amount) public onlyAuthorized { totalSaleAmount = amount; } // Get user addrs function getUserAddrs() public view returns (address[] memory) { address[] memory returnData = new address[](userAddrs.length); for (uint i=0; i<userAddrs.length; i++) { returnData[i] = userAddrs[i]; } return returnData; } // Get user's vesting info function getUserVestingInfo(address userAddr) public view returns (VestingInfo memory) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = vestingList[userInfo.vestingIndex]; return vestingInfo; } // Set User Info function setUserInfo(address _addr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, uint256 _withdrawnAmount) public onlyAuthorized { UserInfo storage userInfo = userList[_addr]; if (userInfo.depositedAmount == 0) { userAddrs.push(_addr); userInfo.vestingIndex = _vestingIndex; userInfo.firstDepositedTime = block.timestamp; userInfo.depositedAmount = 0; userInfo.purchasedAmount = 0; userInfo.withdrawnAmount = 0; } else { totalCoinAmount = totalCoinAmount.sub(Math.min(totalCoinAmount, userInfo.depositedAmount)); totalSoldAmount = totalSoldAmount.sub(Math.min(totalSoldAmount, userInfo.purchasedAmount)); } totalCoinAmount = totalCoinAmount.add(_depositedAmount); totalSoldAmount = totalSoldAmount.add(_purchasedAmount); userInfo.depositedAmount = userInfo.depositedAmount.add(_depositedAmount); userInfo.purchasedAmount = userInfo.purchasedAmount.add(_purchasedAmount); userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(_withdrawnAmount); XJoyToken _xJoyToken = XJoyToken(address(xGovToken)); _xJoyToken.addPurchaser(_addr); } // Seed User List function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner { for (uint i=0; i<_userAddrs.length; i++) { setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount); if (_transferToken) { xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount); } } } function seedUser(address _userAddr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, bool _transferToken) public onlyOwner { setUserInfo(_userAddr, _vestingIndex, _depositedAmount, _purchasedAmount, 0); if (_transferToken) { xGovToken.safeTransfer(_userAddr, _purchasedAmount); } } // Deposit // coinAmount (decimals: COIN_DECIMALS) function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale { require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount"); CoinInfo memory coinInfo = coinList[coinIndex]; IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr); // calculate token amount to be transferred (uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex); uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount); // if the token amount is less than remaining if (availableTokenAmount < tokenAmount) { tokenAmount = availableTokenAmount; (_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex); } // validate purchasing _preValidatePurchase(_msgSender(), tokenAmount, coinAmount, coinIndex); // transfer coin and token coin.safeTransferFrom(_msgSender(), address(this), coinAmount); xGovToken.safeTransfer(_msgSender(), tokenAmount); // transfer coin to treasury if (treasuryAddrs.length != 0) { coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount); } // update global state totalCoinAmount = totalCoinAmount.add(_coinAmount); totalSoldAmount = totalSoldAmount.add(tokenAmount); // update purchased token list UserInfo storage userInfo = userList[_msgSender()]; if (userInfo.depositedAmount == 0) { userAddrs.push(_msgSender()); userInfo.vestingIndex = 1; userInfo.firstDepositedTime = block.timestamp; } userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount); userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount); emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount); XJoyToken _xJoyToken = XJoyToken(address(xGovToken)); _xJoyToken.addPurchaser(_msgSender()); } // Withdraw function withdraw() external whenVesting(_msgSender()) { uint256 withdrawalAmount = calcWithdrawalAmount(_msgSender()); uint256 govTokenAmount = govToken.balanceOf(address(this)); uint256 xGovTokenAmount = xGovToken.balanceOf(address(_msgSender())); uint256 withdrawAmount = Math.min(withdrawalAmount, Math.min(govTokenAmount, xGovTokenAmount)); require(withdrawAmount > 0, "No withdraw amount!"); require(xGovToken.allowance(_msgSender(), address(this)) >= withdrawAmount, "withdraw's allowance is low!"); xGovToken.safeTransferFrom(_msgSender(), address(this), withdrawAmount); govToken.safeTransfer(_msgSender(), withdrawAmount); UserInfo storage userInfo = userList[_msgSender()]; userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(withdrawAmount); userInfo.lastWithdrawnTime = block.timestamp; emit TokensWithdrawed(_msgSender(), withdrawAmount); } // Calc token amount by coin amount function calcWithdrawalAmount(address userAddr) public view returns (uint256) { require(checkVestingPeriod(userAddr), "This is not vesting period."); UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); // uint256 VESTING_START = SALE_START.add(vestingInfo.lockingDuration); uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); uint256 totalAmount = 0; if (block.timestamp <= VESTING_START) { totalAmount = userInfo.purchasedAmount.mul(vestingInfo.initClaimablePercent).div(100); } else if (block.timestamp >= VESTING_START.add(vestingInfo.vestingDuration)) { totalAmount = userInfo.purchasedAmount; } else { totalAmount = userInfo.purchasedAmount.mul(block.timestamp.sub(VESTING_START)).div(vestingInfo.vestingDuration); } uint256 withdrawalAmount = totalAmount.sub(userInfo.withdrawnAmount); return withdrawalAmount; } // Calc token amount by coin amount function calcTokenAmount(uint256 _coinAmount, uint8 coinIndex) public view returns (uint256, uint256) { require( coinList.length > coinIndex, "coinList.length > coinIndex"); CoinInfo memory coinInfo = coinList[coinIndex]; ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr); uint256 rate = coinInfo.rate; uint tokenDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS; uint256 tokenAmount = _coinAmount .mul(10**tokenDecimal) .div(rate); uint coinDecimal = COIN_DECIMALS - coin.decimals(); uint256 coinAmount = _coinAmount .div(10**coinDecimal); return (tokenAmount, coinAmount); } // Calc coin amount by token amount function calcCoinAmount(uint256 _tokenAmount, uint8 coinIndex) public view returns (uint256, uint256) { require( coinList.length > coinIndex, "coinList.length > coinIndex"); CoinInfo memory coinInfo = coinList[coinIndex]; ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr); uint256 rate = coinInfo.rate; uint _coinDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS; uint256 _coinAmount = _tokenAmount .div(10**_coinDecimal) .mul(rate); uint coinDecimal = COIN_DECIMALS - coin.decimals(); uint256 coinAmount = _coinAmount .div(10**coinDecimal); return (_coinAmount, coinAmount); } // Calc max coin amount to be deposit function calcMaxCoinAmountToBeDeposit(uint8 coinIndex) public view returns (uint256) { uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount); (uint256 _coinAmount,) = calcCoinAmount(availableTokenAmount, coinIndex); return _coinAmount; } // Withdraw all coins by owner function withdrawAllCoins(address treasury) public onlyOwner { for (uint i=0; i<coinList.length; i++) { CoinInfo memory coinInfo = coinList[i]; IERC20Upgradeable _coin = IERC20Upgradeable(coinInfo.addr); uint256 coinAmount = _coin.balanceOf(address(this)); _coin.safeTransfer(treasury, coinAmount); } } // Withdraw all xJOY by owner function withdrawAllxGovTokens(address treasury) public onlyOwner { uint256 tokenAmount = xGovToken.balanceOf(address(this)); xGovToken.safeTransfer(treasury, tokenAmount); } // Withdraw all $JOY by owner function withdrawAllGovTokens(address treasury) public onlyOwner { uint256 tokenAmount = govToken.balanceOf(address(this)); govToken.safeTransfer(treasury, tokenAmount); } //////////////////////////////////////////////////////////////////////// // Internal functions //////////////////////////////////////////////////////////////////////// // Validate purchase function _preValidatePurchase(address purchaser, uint256 tokenAmount, uint256 coinAmount, uint8 coinIndex) internal view { require( coinList.length > coinIndex, "coinList.length > coinIndex"); CoinInfo memory coinInfo = coinList[coinIndex]; IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr); require(purchaser != address(0), "Purchaser is the zero address"); require(coinAmount != 0, "Coin amount is 0"); require(tokenAmount != 0, "Token amount is 0"); require(xGovToken.balanceOf(address(this)) >= tokenAmount, "$xJoyToken amount is lack!"); require(coin.balanceOf(msg.sender) >= coinAmount, "Purchaser's coin amount is lack!"); require(coin.allowance(msg.sender, address(this)) >= coinAmount, "Purchaser's allowance is low!"); this; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT 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 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' 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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // 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; 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.6; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract AuthorizableU is OwnableUpgradeable { //////////////////////////////////////////////////////////////////////// // State variables //////////////////////////////////////////////////////////////////////// mapping(address => bool) public isAuthorized; //////////////////////////////////////////////////////////////////////// // Events & Modifiers //////////////////////////////////////////////////////////////////////// event AddedAuthorized(address _user); event RemovedAuthorized(address _user); modifier onlyAuthorized() { require(isAuthorized[msg.sender] || owner() == msg.sender, "caller is not authorized"); _; } //////////////////////////////////////////////////////////////////////// // Initialization functions //////////////////////////////////////////////////////////////////////// function __Authorizable_init() internal virtual initializer { __Ownable_init(); } //////////////////////////////////////////////////////////////////////// // External functions //////////////////////////////////////////////////////////////////////// function addAuthorized(address _toAdd) public onlyOwner { isAuthorized[_toAdd] = true; emit AddedAuthorized(_toAdd); } function removeAuthorized(address _toRemove) public onlyOwner { require(_toRemove != msg.sender); isAuthorized[_toRemove] = false; emit RemovedAuthorized(_toRemove); } //////////////////////////////////////////////////////////////////////// // Internal functions //////////////////////////////////////////////////////////////////////// } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "./BlackListToken.sol"; contract XJoyToken is BlackListToken { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; //////////////////////////////////////////////////////////////////////// // State variables //////////////////////////////////////////////////////////////////////// uint256 public manualMinted; //////////////////////////////////////////////////////////////////////// // Events & Modifiers //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Initialization functions //////////////////////////////////////////////////////////////////////// function initialize( string memory name, string memory symbol, uint256 initialSupply ) public virtual initializer { __ERC20_init(name, symbol); __BlackList_init(); _mint(_msgSender(), initialSupply); addAuthorized(_msgSender()); manualMinted = 0; } //////////////////////////////////////////////////////////////////////// // External functions //////////////////////////////////////////////////////////////////////// function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } function burn(address _from, uint256 _amount) public onlyOwner { _burn(_from, _amount); } function manualMint(address _to, uint256 _amount) public onlyAuthorized { _mint(_to, _amount); manualMinted = manualMinted.add(_amount); } // add purchaser function addPurchaser(address addr) public onlyAuthorized { addBlackList(addr); } } // 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 "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; /** * @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 "../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 { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../utils/AuthorizableU.sol"; contract BlackListToken is ERC20Upgradeable, AuthorizableU { //////////////////////////////////////////////////////////////////////// // State variables //////////////////////////////////////////////////////////////////////// bool public isBlackListChecking; mapping (address => bool) public isBlackListed; // for from address mapping (address => bool) public isWhiteListed; // for to address //////////////////////////////////////////////////////////////////////// // Events & Modifiers //////////////////////////////////////////////////////////////////////// event SetBlackList(address[] _users, bool _status); event AddedBlackList(address _user); event RemovedBlackList(address _user); event SetWhiteList(address[] _users, bool _status); event AddedWhiteList(address _user); event RemovedWhiteList(address _user); modifier whenTransferable(address _from, address _to) { require(isTransferable(_from, _to), "[email protected]: transfer isn't allowed"); _; } //////////////////////////////////////////////////////////////////////// // Initialization functions //////////////////////////////////////////////////////////////////////// function __BlackList_init() internal virtual initializer { __Authorizable_init(); isBlackListChecking = true; } //////////////////////////////////////////////////////////////////////// // External functions //////////////////////////////////////////////////////////////////////// function startBlackList(bool _status) public onlyAuthorized { isBlackListChecking = _status; } // Blacklist function setBlackList(address[] memory _addrs, bool _status) public onlyAuthorized { for (uint256 i; i < _addrs.length; ++i) { isBlackListed[_addrs[i]] = _status; } emit SetBlackList(_addrs, _status); } function addBlackList(address _toAdd) public onlyAuthorized { isBlackListed[_toAdd] = true; emit AddedBlackList(_toAdd); } function removeBlackList(address _toRemove) public onlyAuthorized { isBlackListed[_toRemove] = false; emit RemovedBlackList(_toRemove); } // Whitelist function setWhiteList(address[] memory _addrs, bool _status) public onlyAuthorized { for (uint256 i; i < _addrs.length; ++i) { isWhiteListed[_addrs[i]] = _status; } emit SetWhiteList(_addrs, _status); } function addWhiteList(address _toAdd) public onlyAuthorized { isWhiteListed[_toAdd] = true; emit AddedWhiteList(_toAdd); } function removeWhiteList (address _toRemove) public onlyAuthorized { isWhiteListed[_toRemove] = false; emit RemovedWhiteList(_toRemove); } function isTransferable(address _from, address _to) public view returns (bool) { if (isBlackListChecking) { // require(!isBlackListed[_from], "[email protected]: _from is in isBlackListed"); // require(!isBlackListed[_to] || isWhiteListed[_to], "[email protected]: _to is in isBlackListed"); require(!isBlackListed[_from] || isWhiteListed[_to], "[email protected]: _from is in isBlackListed"); } return true; } //////////////////////////////////////////////////////////////////////// // Internal functions //////////////////////////////////////////////////////////////////////// function _transfer(address _from, address _to, uint256 _amount) internal virtual override whenTransferable(_from, _to) { super._transfer(_from, _to, _amount); } }
Get user's vesting info
function getUserVestingInfo(address userAddr) public view returns (VestingInfo memory) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = vestingList[userInfo.vestingIndex]; return vestingInfo; }
480,079
pragma solidity ^0.5.3; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping (address=>bool) private contractAuthorization; //variables defining a airline struct Airline { bool isRegistered; uint256 funds; uint256 votes; } //private map holding registered airlines mapping (address=>Airline) private airlines; uint256 private _numAirlines = 0; uint32 private _numFundedAirlines = 0; //Consensus data mapping (address=>address[]) private consensusMap; //Insurance Struct struct InsuranceContract{ address passenger; string flight; uint256 value; bool redeemed; bool payed; } /****************************** * Insurance Data * ******************************/ mapping(bytes32 => InsuranceContract) private insuredFlightsList; mapping(string => address[]) private flightPassengersArray; mapping(address => uint256) private passengerPayoutFunds; //flight struct struct Flight{ string name; uint256 flightDateTime; address airline; uint8 status; } /**************************** * Flight Data * *****************************/ //registered flights by flight name and airling mapping(bytes32 => Flight) private registeredFlights; /********************************************************************************************/ /* Flight Functions */ /********************************************************************************************/ /** Register a flight */ function registerFlight(string calldata flightName, address airline, uint256 flightDateTime, uint8 flightStatus) external isAuthorizedCaller requireIsOperational { Flight memory regFlight = Flight({ name: flightName, flightDateTime: flightDateTime, airline: airline, status: flightStatus }); bytes32 tmpKey = getKey(regFlight.name, regFlight.airline); registeredFlights[tmpKey] = regFlight; } /** Get Flight Info */ function getFlightInfo(string calldata flightName, address airline) view external requireIsOperational isAuthorizedCaller returns(string memory, uint256, address, uint8 ) { bytes32 tmpKey = getKey(flightName, airline); require(registeredFlights[tmpKey].airline != address(0), "This flight is not registered."); return( registeredFlights[tmpKey].name, registeredFlights[tmpKey].flightDateTime, registeredFlights[tmpKey].airline, registeredFlights[tmpKey].status); } /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; contractAuthorization[msg.sender] = true; //create insertion of first airline airlines[msg.sender] = Airline(true, 0, 0); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireNotAlreadyRegistered(address toReg) { require(airlines[toReg].isRegistered, "Airline already registered!"); _; } /** * @dev Modifier that requires the "authorized caller" account to be the function caller */ modifier isAuthorizedCaller() { require(contractAuthorization[msg.sender], "Caller is not authorized caller"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Set authorized callors * @return A bool that is the current operating status */ function authorizeCaller(address dataContract) external requireContractOwner{ contractAuthorization[dataContract] = true; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function getKey(string memory name, address addr) pure internal returns(bytes32) { bytes32 tmpkey = keccak256(abi.encodePacked(name, addr)); return (tmpkey); } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address airlineAddress ) isAuthorizedCaller external { // airlines[airlineAddress]=Airline({ isRegistered: true, funds: 0, votes: consensusMap[airlineAddress].length }); _numAirlines = _numAirlines.add(1); } /** * @dev deposit airline funds * Can only be called from FlightSuretyApp contract * */ function depositAirlineFunds(address depositor, uint256 funds) isAuthorizedCaller payable external { airlines[depositor].funds = airlines[depositor].funds.add(funds); } /** * @dev deposit airline funds * Can only be called from FlightSuretyApp contract * */ function setAirlineAsRegistered(address authorize) isAuthorizedCaller payable external { airlines[authorize].isRegistered = true; _numAirlines = _numAirlines.add(1); } /** * @dev vote on airline consensus * Can only be called from FlightSuretyApp contract * */ function concensusVote(address airlineToAdd, address sponsorAirline) isAuthorizedCaller external payable returns(uint256) { if(consensusMap[airlineToAdd].length != 0){ for(uint i=0; i < consensusMap[airlineToAdd].length; i++){ require(consensusMap[airlineToAdd][i] != sponsorAirline, "Airline has already voted!"); } } consensusMap[airlineToAdd].push(sponsorAirline); airlines[airlineToAdd].votes = airlines[airlineToAdd].votes.add(1); return consensusMap[airlineToAdd].length; } /** * @dev return total votes airline funds * Can only be called from FlightSuretyApp contract * */ function airlineTotalVotes(address airlineToAdd) isAuthorizedCaller external view returns(uint256) { return consensusMap[airlineToAdd].length; } /** * @dev get current number of registered airlines * Can only be called from FlightSuretyApp contract * */ function getNumberRegisteredAirlines() isAuthorizedCaller view external returns(uint256) { return _numAirlines; } //this is here to make boilerplate test pass function isAirline( address airlineAddress ) isAuthorizedCaller external view returns (bool) { Airline memory myAirline =airlines[airlineAddress]; bool out = false; if(myAirline.isRegistered){ out = true; } return out; } //get current funds for airline function getAirlineFunds( address airlineAddress ) isAuthorizedCaller external view returns (uint256) { Airline memory myAirline =airlines[airlineAddress]; uint256 theFunds = myAirline.funds; return theFunds; } //get current funds for airline function getAirline( address airlineAddress ) isAuthorizedCaller external view returns (bool, uint256, uint256) { Airline memory myAirline =airlines[airlineAddress]; return (myAirline.isRegistered, myAirline.funds, myAirline.votes); } /********************************************************************************************/ /* Insurance CONTRACT FUNCTIONS */ /********************************************************************************************/ /* * Passenger Purchases Insurance */ function passengerPurchase(string calldata flight, address passenger) external payable isAuthorizedCaller{ //create a new contract InsuranceContract memory insTmp = InsuranceContract({ passenger: passenger, flight: flight, value: msg.value, redeemed: false, payed: false }); //keep track of it bytes32 tmpkey = keccak256(abi.encodePacked(flight, passenger)); //keep list of insurance contracts by hashed flight Passenger pair insuredFlightsList[tmpkey] = insTmp; //keep a list of passengers with insurance by flight flightPassengersArray[flight].push(passenger); } /* * Get Insurance Contract */ function getInsuranceContract(string calldata flight, address passenger) external view isAuthorizedCaller returns (address, string memory, uint256, bool, bool) { //create hashed flight Passenger pair bytes32 tmpkey = keccak256(abi.encodePacked(flight, passenger)); return (insuredFlightsList[tmpkey].passenger, insuredFlightsList[tmpkey].flight, insuredFlightsList[tmpkey].value, insuredFlightsList[tmpkey].redeemed, insuredFlightsList[tmpkey].payed); } /* * credit passengers with flight insurance */ function creditByFlight(string calldata flight)external isAuthorizedCaller { //get passengers to be credited by flight address[] memory psgArray = flightPassengersArray[flight]; //loop through passengers and credit for(uint i = 0; i < psgArray.length; i++){ //get key for insurance contracts bytes32 tmpkey = keccak256(abi.encodePacked(flight, psgArray[i])); //get record InsuranceContract storage psgInsContract = insuredFlightsList[tmpkey]; //add passenger to a list of passengers authorized to pay //increase by insurance leverage 1.5 = (3*value)/2 uint256 tmpVal = psgInsContract.value.mul(3).div(2); passengerPayoutFunds[psgInsContract.passenger] = tmpVal; //mark contract as redeemed psgInsContract.redeemed = true; //update stored contract insuredFlightsList[tmpkey] = psgInsContract; } } /** * @dev Buy insurance for a flight * */ function buy ( ) external payable { } /** * @dev Credits payouts to insurees */ function creditInsurees ( ) external pure { } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( ) external pure { } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( ) public payable { } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(); } }
this is here to make boilerplate test pass
function isAirline( address airlineAddress ) isAuthorizedCaller external view returns (bool) { Airline memory myAirline =airlines[airlineAddress]; bool out = false; if(myAirline.isRegistered){ out = true; } return out; }
14,045,112
/* https://www.apache.org/licenses/LICENSE-2.0 */ pragma solidity ^0.4.20; import "./Ibox9User.sol"; import "./Ibox9Admin.sol"; import "./Ibox9Any.sol"; import "./SafeMath.sol"; contract Box9 is Ibox9User, Ibox9Admin, Ibox9Any { using SafeMath for uint256; uint256 public firstSpin; uint256 private constant precision = 3; /* decimal places for mantissa */ uint256 private constant rounding = 2; /* round down the number for winnings for user friendliness*/ uint256 private constant referralReward = 10; uint256 private constant goldReward = 650; uint256 private constant silverReward = 125; uint256 private constant jackpotReward = 50; uint256 private constant jackpotKeyCost = 50; /* how many credits per key*/ uint256 private constant session = 10; /* blocks between spins */ uint256 private constant jackpotSession = 10000; /* blocks between jackpots */ address private constant zeroAddress = address(0x0); address private admin; address private houseWallet; uint256 private houseVault; uint256[] private tables; uint256 private nextBet; uint256[] private nextJackpot; function Box9(address _houseWallet) public { admin = msg.sender; houseWallet = _houseWallet; nextBet = 1; /* initiate tables */ tables.push(1 * 1e8); tables.push(10 * 1e8); tables.push(50 * 1e8); tables.push(100 * 1e8); tables.push(500 * 1e8); tables.push(1000 * 1e8); /* save first round */ firstSpin = _getNextRound(); uint256 firstJackpotSpin = _computeNextJackpotRound(block.number); for (uint256 i = 0; i < tables.length; i++) { nextJackpot.push(firstJackpotSpin); } } struct Player { address referrer; uint256 credits; address[] referrees; uint256 rewards; uint256[] betIds; uint256 totalBets; uint256[] jackpotCredits; } struct Round { bool requireFix; uint256 result; /* blockhash */ } struct Table { uint256 id; uint256 boxPrice; uint256 round; uint8[3] winningNumbers; /* gold, silver1, silver2 */ uint256[3] winningAmount; uint256[9] boxesOnNumber; address[] players; uint256 pot; bool open; uint256[] betId; /* all bets for this table */ } struct Betting { uint256 id; address player; uint256 round; uint256 tableIndex; uint16 boxChoice; bool claimed; } struct Jackpot { bool arranged; uint256 pot; address[] jPlayers; uint256[] betId; address[] winners; uint256 award; } struct LastResults { uint256 round; address[] lastWinners; uint256[] lastAwards; } /* mappings */ mapping(address => Player) private playerInfo; mapping(uint256 => Round) private roundInfo; /* mapping by blockHeight; */ mapping(uint256 => mapping(uint256 => Jackpot)) private jackpotInfo; /* first uint is round,second is table index */ mapping(uint256 => mapping(uint256 => Table)) private tableInfo; /* first uint is round, second is table index */ mapping(uint256 => Betting) private betInfo; mapping(uint256 => LastResults) private tableWinners; /* mapping by table id */ /* events */ event RegisterEvent(address player, address referrer); event DepositEvent(address player, uint256 amount); event WithdrawEvent(address player, address destination, uint256 amount); event BetEvent( uint256 bettingId, address player, uint256 round, uint256 _tableId, uint256 amount ); event WithdrawProfitsEvent(uint256 profits); event ClaimReward( address winner, uint256 round, uint256 table, uint256 amount ); event ClaimJackpotPrize( address winner, uint256 round, uint256 table, uint256 jPrize ); event JoinJackpot(address player, uint256 round, uint256 betId); event UpdateRoundState(uint256 blocknumber, uint256 hash); event UpdateTableState(uint256 blocknumber, uint256 tableIndex); event UpdateLastWinners( uint256 round, uint256 winners, uint256 totalAwards ); event UpdateJackpotTableState( uint256 jackpotRound, uint256 tableIndex, uint256 award, uint256 winners ); modifier isAdmin() { assert(msg.sender == admin); _; } modifier isPlayer(address _playersAddr) { Player storage pl = playerInfo[_playersAddr]; assert(pl.referrer != zeroAddress); _; } modifier tableExists(uint256 _index) { require(_index < tables.length); _; } /** * @notice fallback not payable * don't accept deposits directly, user must call deposit() */ function() external {} /** * @notice adds new table, the only difference is box price * only contract owner can add a table * @param _boxPrice - price in coins per box * @return uint256 - returns the table id */ function addNewTable(uint256 _boxPrice) external isAdmin() returns (uint256 tableId) { require(_boxPrice > 0); tables.push(_boxPrice); nextJackpot.push(_computeNextJackpotRound(block.number)); return (tables.length - 1); } /** * @notice user must register a referrer first * or the zero address if he doesn't have one * Refferer can't be changed later * Refferer must have already been registered * @param _referrer - address of refferer */ function register(address _referrer) external { Player storage pl = playerInfo[msg.sender]; /* check if user already registered */ require(pl.referrer == zeroAddress); /* check if there is a referrer*/ if (_referrer == zeroAddress || _referrer == msg.sender) { pl.referrer = houseWallet; emit RegisterEvent(msg.sender, zeroAddress); } else { /* register only if referrer already registered */ Player storage referrer = playerInfo[_referrer]; require(referrer.referrer != zeroAddress); pl.referrer = _referrer; referrer.referrees.push(msg.sender); emit RegisterEvent(msg.sender, _referrer); } } /** * @notice withdraws all profits to cold wallet * callable only by admin * @param _amount - the amount. If zero then withdraw all credits * @return uint256 - the withdrawn profits */ function withdrawProfits(uint256 _amount) external payable isAdmin() returns (uint256 profits) { require(houseVault > 0); if (_amount == 0) { profits = houseVault; } else { require(_amount <= houseVault); profits = _amount; } houseVault = houseVault.sub(profits); houseWallet.transfer(profits); emit WithdrawProfitsEvent(profits); return profits; } /** * @notice returns general data for a player * @param _player address * @return address - refferer's address * @return uint256 - credits * @return uint256 - commissions */ function getPlayerInfo(address _player) external view returns ( address referrer, uint256 credits, uint256 commissions, uint256 totalBets ) { Player storage pl = playerInfo[_player]; return (pl.referrer, pl.credits, pl.rewards, pl.totalBets); } /** * @notice returns the withdrawable vault balance - admin only * @return uint256 - house balance */ function checkVaultBalance() external view returns (uint256 balance) { return houseVault; } /** * @notice player chooses boxes (6 maximum) * Transaction reverts if not enough coins in his account * Also, bettor opens(initiates) the table if he is the first bettor * @param _chosenBoxes - 9 lowest bits show the boxes he has chosen * @param _tableId - the table * @param _joinJackpot - boolean if the player wishes to join the jp * @return uint256 - the next blockheigh for the box spin */ function chooseBoxes( uint16 _chosenBoxes, uint256 _tableId, bool _joinJackpot ) external isPlayer(msg.sender) returns (uint256 round) { require(_tableId < tables.length); uint8 quantity; quantity = _checkValidity(_chosenBoxes); require(quantity != 0); uint256 boxprice = tables[_tableId]; require(boxprice > 0); /* check if enough credits */ Player storage pl = playerInfo[msg.sender]; uint256 amount = quantity * boxprice; require(pl.credits.add(pl.rewards) >= amount); /* get next round */ round = _getNextRound(); /* use bonus first */ uint256 bonus = pl.rewards; if (bonus > amount) { bonus = amount; } pl.rewards = pl.rewards.sub(bonus); pl.credits = pl.credits.add(bonus); /* decrease credits */ pl.credits = pl.credits.sub(amount); /* create bet struct */ Betting storage bet = betInfo[nextBet]; bet.id = nextBet; nextBet = nextBet.add(1); bet.player = msg.sender; bet.round = round; bet.tableIndex = _tableId; bet.boxChoice = _chosenBoxes; _updateTableOnBet( msg.sender, round, _chosenBoxes, _tableId, bet.id, amount ); pl.totalBets = pl.totalBets.add(amount); pl.betIds.push(bet.id); /* in case of new tables by admin adjust the array length accordingly */ if (pl.jackpotCredits.length != tables.length) { pl.jackpotCredits.length = tables.length; } pl.jackpotCredits[_tableId] = pl.jackpotCredits[_tableId].add(quantity); /* give the bonus to referrer */ bonus = amount.mul(referralReward); bonus = bonus.div(10**precision); if (pl.referrer == houseWallet) { houseVault = houseVault.add(bonus); } else { Player storage ref = playerInfo[pl.referrer]; ref.rewards = ref.rewards.add(bonus); } /* emit event */ emit BetEvent(bet.id, msg.sender, round, _tableId, amount); /* also join jackpot table */ if ( _joinJackpot && (nextJackpot[_tableId] == _getNextRound()) && (pl.jackpotCredits[_tableId] >= jackpotKeyCost) ) { joinJackpot(_tableId); } return round; } /* internal use, only for chooseBoxes() to avoid stack too deep error */ function _updateTableOnBet( address _bettor, uint256 _round, uint16 _choice, uint256 _tableId, uint256 _betId, uint256 _amount ) internal { Table storage tbl = tableInfo[_round][_tableId]; /* player shouldn't be able to rebet on same table and spin */ require(!_addressExists(tbl.players, _bettor)); if (!tbl.open) { /* open the table if first bettor */ tbl.open = true; tbl.boxPrice = tables[_tableId]; tbl.round = _round; } /* update table info */ tbl.players.push(_bettor); tbl.betId.push(_betId); tbl.pot = tbl.pot.add(_amount); uint16 mask = 1; for (uint256 i = 0; i < 9; i++) { if (_choice & mask != 0) { tbl.boxesOnNumber[i] = tbl.boxesOnNumber[i].add(1); } mask = mask << 1; } } /** * @notice use a key to join the jackpot spin * succeeds only if there is normal bet on this round * @param _tableId - the table id * @return round - the jackpot round */ function joinJackpot(uint256 _tableId) internal isPlayer(msg.sender) returns (uint256 round) { uint256 nRound = _getNextRound(); uint256 jRound = nextJackpot[_tableId]; require(nRound == jRound); Player storage pl = playerInfo[msg.sender]; /* in case of new tables by admin adjust the array length accordingly */ if (pl.jackpotCredits.length != tables.length) { pl.jackpotCredits.length = tables.length; } require(pl.jackpotCredits[_tableId] >= jackpotKeyCost); /* reduntant check */ pl.jackpotCredits[_tableId] = pl.jackpotCredits[_tableId].sub( jackpotKeyCost ); Jackpot storage j = jackpotInfo[jRound][_tableId]; j.jPlayers.push(msg.sender); /* find the correct bet id for this table */ uint256 nBetId; for (uint256 i = 0; i < pl.betIds.length; i++) { Betting storage nBet = betInfo[pl.betIds[pl.betIds.length + i - 1]]; if ((nBet.round == nRound) && (nBet.tableIndex == _tableId)) { nBetId = nBet.id; break; } } require(nBetId != 0); j.betId.push(nBetId); emit JoinJackpot(msg.sender, jRound, nBetId); return jRound; } /** * @notice shows current players and betting amounts for a table * @param _blocknumber the block height of the round * @param _tableId - the table id * @return address[] - list of all players for the round * @return amount - how many coins are in the pot */ function currentPlayers(uint256 _blocknumber, uint256 _tableId) external view tableExists(_tableId) returns (address[] players) { Table storage tbl = tableInfo[_blocknumber][_tableId]; players = tbl.players; return players; } /** * @notice returns total coins in pool for a round * @param _blocknumber - the block height of the round * @param _tableId - the table id * @return uint256 , total coins in pool for this round */ function poolTotal(uint256 _blocknumber, uint256 _tableId) external view tableExists(_tableId) returns (uint256 total) { Table storage tbl = tableInfo[_blocknumber][_tableId]; return tbl.pot; } /** * @notice returns addresses of refferees * @param _referrer - address of the referrer * @return address[] - returns the referee addresses */ function showReferrees(address _referrer) external view isPlayer(_referrer) returns (address[]) { Player storage pl = playerInfo[_referrer]; return pl.referrees; } /** * @notice returns an array of bonuses for a refferer * @param _referrer - address of the referrer * @return uint256[] - returns the corresponding total amount of coins */ function showReferralBonuses(address _referrer) external view returns (uint256[] totalBonus) { Player storage pl = playerInfo[_referrer]; uint256[] memory tBonus = new uint256[](pl.referrees.length); for (uint256 i = 0; i < pl.referrees.length; i++) { Player storage ref = playerInfo[pl.referrees[i]]; tBonus[i] = (ref.totalBets * referralReward) / (10**precision); } return tBonus; } /** * @notice bonus info * @param _referree - the address of referee * @return address, uint256 - returns the referrer address and total rewards given to referrer */ function bonusGiven(address _referree) external view isPlayer(_referree) returns (address referrer, uint256 amount) { Player storage pl = playerInfo[_referree]; amount = (pl.totalBets * referralReward) / (10**precision); return (pl.referrer, amount); } /** * @notice deposit ECOC * revert on non-register user */ function deposit() external payable isPlayer(msg.sender) { require(msg.value > 0); Player storage pl = playerInfo[msg.sender]; pl.credits = pl.credits.add(msg.value); emit DepositEvent(msg.sender, msg.value); } /** * @notice withdraw ECOC, can be to any address * if zero address just return to sender * @param _amount - the number of coins * @param _to - receiver's address */ function withdraw(address _to, uint256 _amount) external payable { require(_amount > 0); Player storage pl = playerInfo[msg.sender]; require(pl.credits >= _amount); /* prevent a frontend bug to send coins to zero address */ address to = _to; if (_to == zeroAddress) { to = msg.sender; } pl.credits = pl.credits.sub(_amount); to.transfer(_amount); emit WithdrawEvent(msg.sender, _to, _amount); } /** * @notice return all table prices * @return uint256[] - returns the table's box prices */ function showTables() external view returns (uint256[]) { return tables; } /** * @notice returns how many bettors and coins on a specific number for the next round * @param _round - block height * @param _tableId - table index * @return bool - true if table is open * @return uint256 - box price * @return uint256 - total amount in table pot */ function getTableStatus(uint256 _round, uint256 _tableId) external view tableExists(_tableId) returns ( bool status, uint256 boxPrice, uint256 potAmount ) { require(_round.mod(session) == 0); Table storage tbl = tableInfo[_round][_tableId]; return (tbl.open, tbl.boxPrice, tbl.pot); } /** * @notice returns how many bettors and coins on a specific number for the next round * @param _round - block height * @param _tableId - table index * @return uint256[3] - array of prizes, fisrt is gold */ function getTablePrizes(uint256 _round, uint256 _tableId) external view tableExists(_tableId) returns (uint256[3] winningAmount) { require(_round.mod(session) == 0); Table storage tbl = tableInfo[_round][_tableId]; require(tbl.winningAmount.length > 0); return tbl.winningAmount; } /** * @notice returns how many bettors and coins on a specific number for the next round * @param _round - block height * @param _tableId - table index * @return address[] - array of addresses of table joiners */ function getTableJoiners(uint256 _round, uint256 _tableId) external view tableExists(_tableId) returns (address[] players) { require(_round.mod(session) == 0); Table storage tbl = tableInfo[_round][_tableId]; return tbl.players; } /** * @notice returns how many bettors and coins exist on a specific number for the next round * @param _number - box number * @param _tableId - table index * @return uint256 - the number of bettors * @return uint256 - coins amount */ function getNumberState(uint8 _number, uint256 _tableId) external view tableExists(_tableId) returns (uint256 totalPlayers, uint256 totalBets) { require(_number < 9); uint256 round = _getNextRound(); Table storage tbl = tableInfo[round][_tableId]; totalPlayers = tbl.boxesOnNumber[uint256(_number)]; totalBets = totalPlayers.mul(tbl.boxPrice); return (totalPlayers, totalBets); } /** * @notice returns the winning boxes by blockhash and table * @param _blockhash - the round blockhash * @param _tableId - table index * @return uint8[3] - returns three winning boxes by box index (first is golden) */ function _roundResult(uint256 _blockhash, uint256 _tableId) internal view tableExists(_tableId) returns (uint8[3] result) { uint256 mask = 0xfffffff; uint256[9] memory boxes; uint256 min; uint256 index; /* add the table price to blockhash to make it unique for each table and rehash using keccak256 */ uint256 random = uint256( keccak256(_blockhash + tables[_tableId].div(1e8)) ); random = random >> 4; /* discard the last hex digit*/ for (uint8 i = 0; i < 9; i++) { boxes[8 - i] = random & mask; /* get last 7 hex digits */ random = random >> (7 * 4); /* prepare the random number for next box */ } /* get the three lowest numbers */ for (uint8 j = 0; j < 3; j++) { min = boxes[0]; index = 0; for (i = 1; i < 9; i++) { if (boxes[i] < min) { min = boxes[i]; index = i; } } boxes[index] = uint256(-1); result[j] = uint8(index); } return result; } /** * @notice returns all information about a bet * @param _betId - id of the bet * @return address - the players address * @return uint256 - the round number * @return uint256 - the table index * @return uint16 - the chosen numbers (encoded) */ function getBetInfo(uint256 _betId) external view returns ( address player, uint256 round, uint256 tableIndex, uint16 chosenBoxes ) { Betting storage bet = betInfo[_betId]; /* check if bet exists */ require(_betId == bet.id); player = bet.player; round = bet.round; tableIndex = bet.tableIndex; chosenBoxes = bet.boxChoice; return (player, round, tableIndex, chosenBoxes); } /** * @notice returns the winning amount for an unclaimed bet * @param _betId - id of the bet * @return uint256 - the winning amount to claim */ function showUnclaimedReward(uint256 _betId) external view returns (uint256 amount) { require(_betId < nextBet); Betting storage bet = betInfo[_betId]; require(!bet.claimed); Round storage r = roundInfo[bet.round]; require(r.result != 0); Table storage tbl = tableInfo[bet.round][bet.tableIndex]; require(_numberExists(tbl.betId, _betId)); uint16 wMask; for (uint256 i = 0; i < 3; i++) { wMask = uint16(2)**tbl.winningNumbers[i]; if (bet.boxChoice & wMask != 0) { amount = amount.add(tbl.boxPrice); amount = amount.add(tbl.winningAmount[i]); } } return amount; } /** * @notice returns the winning boxes by block height and table * @param _round - block height * @param _tableId - table index * @return uint8[3] - returns three winning boxes by box index (first is golden) */ function _winningBoxes(uint256 _round, uint256 _tableId) internal view tableExists(_tableId) returns (uint8[3] result) { uint256 blockhash; Round storage r = roundInfo[_round]; blockhash = r.result; require(blockhash != 0); return (_roundResult(blockhash, _tableId)); } /** * @notice returns the winning boxes by block height and table * @param _round - block height * @param _tableId - table index * @return uint8[3] - returns three winning boxes by box index (first is golden) */ function winningBoxes(uint256 _round, uint256 _tableId) external view returns (uint8[3] result) { return _winningBoxes(_round, _tableId); } /** * @notice returns block height for next round(internal) * @return uint256 - the block height of next spin */ function _getNextRound() internal view returns (uint256 blockHeight) { uint256 nextSpin; uint256 gap; nextSpin = block.number; gap = nextSpin.mod(session); if (gap == session) { gap = 0; } nextSpin = nextSpin.add(session - gap); return nextSpin; } /** * @notice returns block height for next round (external) * @return uint256 - the block height of next spin */ function getNextSpin() external view returns (uint256 blockHeight) { return _getNextRound(); } /** * @notice returns block height for next jackpot(internal) * @param _round - the next jackpot after this round * @return uint256 - the block height of next jackpot */ function _computeNextJackpotRound(uint256 _round) internal pure returns (uint256 blockHeight) { uint256 nextJackpotSpin; uint256 gap; nextJackpotSpin = _round; gap = nextJackpotSpin.mod(jackpotSession); if (gap == jackpotSession) { gap = 0; } nextJackpotSpin = nextJackpotSpin.add(jackpotSession - gap); return nextJackpotSpin; } /** * @notice returns block height for next jackpot(external) * @param _tableId - table index * @return uint256 - the block height of next jackpot */ function getNextJackpotSpin(uint256 _tableId) external view tableExists(_tableId) returns (uint256 blockHeight) { return nextJackpot[_tableId]; } /** * @notice checks the 16bit number of box choice * @param _encodedNumber - the choice payload * @return uint16[] - returns the number of choiced boxes, zero if invalid */ function _checkValidity(uint16 _encodedNumber) internal pure returns (uint8 quantity) { uint8 maxQuantity = 6; uint16 mask = 0x8000; /* mask to set first bit */ /* 7 most significant bits must be zero */ for (uint8 i = 0; i < 7; i++) { if (_encodedNumber & mask != 0) { return 0; } mask = mask >> 1; /* next bit check */ } /* count chosen boxes */ for (i = 0; i < 9; i++) { if (_encodedNumber & mask != 0) { quantity++; } mask = mask >> 1; /* next bit check */ } /* choice limit is 6 per round */ if (quantity > maxQuantity) { return 0; } return quantity; } /** * @notice update the smart contract's state after a round - callable by anyone * @param _blocknumber the block height of the round * @return uint256 - returns the blockhash or revert if it was called succesfully before */ function arrangeRound(uint256 _blocknumber) external returns (uint256 result) { /* necessary checks */ require(_blocknumber < block.number); require(_blocknumber.mod(session) == 0); Round storage r = roundInfo[_blocknumber]; require(r.result == 0); result = uint256(block.blockhash(_blocknumber)); /* if the blockhash is zero something is very wrong * 256 blocks passed and noone has triggered this function * raise status to require fix */ if (result != 0) { r.result = result; } else { r.requireFix = true; } emit UpdateRoundState(_blocknumber, result); return result; } /** * @notice checks if a round hash is arranged (saved) or not * callable by anyone * @param _blocknumber the block height of the round * @return bool - true if arranged */ function isRoundArranged(uint256 _blocknumber) external view returns (bool arranged) { Round storage r = roundInfo[_blocknumber]; if (r.result == 0) { return false; } else { return true; } } /** * @notice checks if a table is arranged (updated) or not * callable by anyone * @param _round the block height of the round * @param _tableId the table index * @return bool - true if arranged */ function isTableArranged(uint256 _round, uint256 _tableId) external view returns (bool arranged) { Table storage tbl = tableInfo[_round][_tableId]; /* if call takes place to soon, table isn't arranged for sure */ if (_round >= block.number) { return false; } if (tbl.players.length == 0) { /* table never used, no need to be arranged */ return true; } return !tbl.open; } /** * @notice checks if the jackpot is arranged (updated) or not * callable by anyone * @param _round the block height of jackpot round * @param _tableId the table index * @return bool - true if arranged */ function isJTableArranged(uint256 _round, uint256 _tableId) external view returns (bool arranged) { Jackpot storage j = jackpotInfo[_round][_tableId]; return j.arranged; } /** * @notice checks if last results were updated for a round and table * @param _round the block height of check * @param _tableId the table index * @return bool - true if last results have been updated */ function isLastWinnersUpdated(uint256 _round, uint256 _tableId) external view returns (bool isUpdated) { LastResults storage tw = tableWinners[_tableId]; isUpdated = (tw.round == _round); return isUpdated; } /** * @notice update the round state if not updated on time - admin only * @param _blocknumber the block height of the round * @param _blockhash the correct blockhash * @return bool - returns true on success */ function fixRound(uint256 _blocknumber, uint256 _blockhash) external isAdmin() returns (bool result) { /* necessary checks */ require(_blocknumber < block.number); require(_blocknumber.mod(session) == 0); Round storage r = roundInfo[_blocknumber]; require(r.result == 0); require(r.requireFix); r.result = _blockhash; r.requireFix = false; emit UpdateRoundState(_blocknumber, _blockhash); return true; } /** * @notice change the jackpot round if already passed and not updated - admin only * @param _tableId the table */ function fixNextJackpotRound(uint256 _tableId) external isAdmin() tableExists(_tableId) { uint256 blocknumber = nextJackpot[_tableId]; require(blocknumber < block.number); Jackpot storage j = jackpotInfo[blocknumber][_tableId]; require(!j.arranged); /* fix the next jackpot */ nextJackpot[_tableId] = _computeNextJackpotRound(block.number); Jackpot storage newJ = jackpotInfo[nextJackpot[_tableId]][_tableId]; /* move the pot*/ newJ.pot = j.pot; j.pot = 0; j.arranged = true; } /** * @notice update table state after a round is updated - callable by anyone * @param _round the block height of the round * @param _tableId the block height of the round * @return bool - returns true on success */ function arrangeTable(uint256 _round, uint256 _tableId) external tableExists(_tableId) returns (bool result) { /* necessary checks */ require(_round < block.number); require(_round.mod(session) == 0); Round storage r = roundInfo[_round]; /* round must be updated first */ require(r.result != 0); Table storage tbl = tableInfo[_round][_tableId]; require(tbl.open == true); uint256 houseGains = tbl.pot; /* update winning numbers */ tbl.winningNumbers = _winningBoxes(_round, _tableId); /* compute and save all rewards awards */ uint256 jRound = nextJackpot[_tableId]; Jackpot storage j = jackpotInfo[jRound][_tableId]; uint256 capital = (tbl.boxesOnNumber[tbl.winningNumbers[0]] + tbl.boxesOnNumber[tbl.winningNumbers[1]] + tbl.boxesOnNumber[tbl.winningNumbers[2]]) .mul(tbl.boxPrice); uint256 remaining = tbl.pot - capital; uint256 roundMask = 8 - rounding; /* ECOC has 8 decimals */ uint256 award; if (tbl.boxesOnNumber[tbl.winningNumbers[0]] != 0) { award = remaining.mul(goldReward).div(10**precision); tbl.winningAmount[0] = award; tbl.winningAmount[0] = tbl.winningAmount[0].div( tbl.boxesOnNumber[tbl.winningNumbers[0]] ); /* for each gold winner */ tbl.winningAmount[0] = _roundNumber( tbl.winningAmount[0], roundMask ); award = tbl.boxesOnNumber[tbl.winningNumbers[0]].mul( tbl.winningAmount[0] ); houseGains = houseGains.sub(award); } else { award = remaining.mul(goldReward).div(10**precision); j.pot = j.pot.add(award); tbl.pot = tbl.pot.sub(award); houseGains = houseGains.sub(award); } if (tbl.boxesOnNumber[tbl.winningNumbers[1]] != 0) { award = remaining.mul(silverReward).div(10**precision); tbl.winningAmount[1] = award; tbl.winningAmount[1] = remaining.mul(silverReward).div( 10**precision ); tbl.winningAmount[1] = tbl.winningAmount[1].div( tbl.boxesOnNumber[tbl.winningNumbers[1]] ); /* for each silver1 winner */ tbl.winningAmount[1] = _roundNumber( tbl.winningAmount[1], roundMask ); award = tbl.boxesOnNumber[tbl.winningNumbers[1]].mul( tbl.winningAmount[1] ); houseGains = houseGains.sub(award); } else { award = remaining.mul(silverReward).div(10**precision); j.pot = j.pot.add(remaining.mul(silverReward).div(10**precision)); tbl.pot = tbl.pot.sub(award); houseGains = houseGains.sub(award); } if (tbl.boxesOnNumber[tbl.winningNumbers[2]] != 0) { award = remaining.mul(silverReward).div(10**precision); tbl.winningAmount[2] = award; tbl.winningAmount[2] = remaining.mul(silverReward).div( 10**precision ); tbl.winningAmount[2] = tbl.winningAmount[2].div( tbl.boxesOnNumber[tbl.winningNumbers[2]] ); /* for each silver2 winner */ tbl.winningAmount[2] = _roundNumber( tbl.winningAmount[2], roundMask ); award = tbl.boxesOnNumber[tbl.winningNumbers[2]].mul( tbl.winningAmount[2] ); houseGains = houseGains.sub(award); } else { award = remaining.mul(silverReward).div(10**precision); j.pot = j.pot.add(remaining.mul(silverReward).div(10**precision)); tbl.pot = tbl.pot.sub(award); houseGains = houseGains.sub(award); } /* jackpot award */ award = remaining.mul(jackpotReward).div(10**precision); award = _roundNumber(award, roundMask); j.pot = j.pot.add(award); /* update houseVault */ houseGains = houseGains.sub(award); houseGains = houseGains.sub(capital); houseVault = houseVault.add(houseGains); /* remove jackpot award from table pot*/ tbl.pot = tbl.pot.sub(award); /* remove house gains from table pot*/ tbl.pot = tbl.pot.sub(houseGains); tbl.open = false; emit UpdateTableState(_round, _tableId); return true; } /** * @notice update jackpot state after a round is updated - callable by anyone * @param _tableId the block height of the round * @return uint256 - prize * @return uint256 - how many jackpoters */ function arrangeJackpotTable(uint256 _tableId) external returns (uint256 award, uint256 winners) { uint256 round = nextJackpot[_tableId]; require(block.number > round); /* check if normal table is arranged */ Table storage tbl = tableInfo[round][_tableId]; require(!tbl.open); /* update Jackpot state */ Jackpot storage j = jackpotInfo[round][_tableId]; require(!j.arranged); uint16 winnersMask = uint16(2)**tbl.winningNumbers[0] + uint16(2)**tbl.winningNumbers[1] + uint16(2)**tbl.winningNumbers[2]; for (uint256 i = 0; i < j.betId.length; i++) { Betting storage jBet = betInfo[j.betId[i]]; if ((jBet.boxChoice & winnersMask) == winnersMask) { j.winners.push(jBet.player); } } if (j.winners.length > 0) { j.award = j.pot.div(j.winners.length); /* round amount, send any changes to housevault */ j.award = _roundNumber(j.award, (8 - rounding)); /* ECOC has 8 decimals */ uint256 change = j.pot.sub(j.award.mul(j.winners.length)); j.pot = j.pot.sub(change); houseVault.add(change); nextJackpot[_tableId] = _computeNextJackpotRound(round); } else { /* no winner, move the pot to the next spin */ uint256 nextSpin; if (j.pot == 0) { /* in case of an unused table, roll to the next jp session*/ nextSpin = _computeNextJackpotRound(round); nextJackpot[_tableId] = nextSpin; } else { nextSpin = _getNextRound(); nextJackpot[_tableId] = nextSpin; Jackpot storage nextJ = jackpotInfo[nextSpin][_tableId]; nextJ.pot = j.pot; j.pot = 0; } } emit UpdateJackpotTableState( round, _tableId, j.award, j.winners.length ); /* set jackpot table as arranged */ j.arranged = true; return (j.award, j.winners.length); } /** * @notice rounding number by _precision digits * @param _number - to be rounded * @param _cut - how many digits to cut * @return uint256 - the _number after rounding */ function _roundNumber(uint256 _number, uint256 _cut) internal pure returns (uint256 rounded) { rounded = _number; uint256 mask = 10**_cut; rounded = rounded.div(mask).mul(mask); return rounded; } /** * @notice saving last round winners for showing purposes only * can be triggered by anyone, doesnt affect the player's credits * @param _tableId - the table * @return uint256 - returns the number of winners * @return uint256 - the total awards given */ function updateLastWinners(uint256 _tableId) external tableExists(_tableId) returns (uint256 winners, uint256 totalAwards) { uint256 lastRound = _getNextRound() - session; /* exit if already computed */ LastResults storage tw = tableWinners[_tableId]; require(tw.round != lastRound); /* table must be arranged first */ Table storage tbl = tableInfo[lastRound][_tableId]; /* use as storage to save some gas*/ require(!tbl.open); /* initiate the structure */ tw.round = lastRound; tw.lastWinners.length = 0; tw.lastAwards.length = 0; /* get all winners for the table */ Betting storage bet; uint256 mask; uint256 amount; for (uint256 i = 0; i < tbl.betId.length; i++) { bet = betInfo[tbl.betId[i]]; for (uint256 w = 0; w < 3; w++) { mask = uint16(2)**tbl.winningNumbers[w]; if (bet.boxChoice & mask != 0) { amount = amount.add(tbl.winningAmount[w]); } } if (amount != 0) { /* player won at least one prize */ tw.lastWinners.push(bet.player); tw.lastAwards.push(amount); winners = winners.add(1); totalAwards = totalAwards.add(amount); amount = 0; } else { /* no winnings, set it to claimed to save gas for other functions */ bet.claimed = true; } } emit UpdateLastWinners(tw.round, winners, totalAwards); return (winners, totalAwards); } /** * @notice get winners addresses for a table of the last round * @param _tableId - table id * @return address[] - address list of winners */ function lastRoundWinners(uint256 _tableId) external view tableExists(_tableId) returns (address[] winners) { LastResults memory tw = tableWinners[_tableId]; winners = tw.lastWinners; return winners; } /** * @notice get winning amounts for a table of the last round * @param _tableId - table id * @return uint256[] - winning amount list of winners */ function lastRoundAwards(uint256 _tableId) external view tableExists(_tableId) returns (uint256[] winningAmount) { LastResults memory tw = tableWinners[_tableId]; winningAmount = tw.lastAwards; return winningAmount; } /** * @notice returns jackpot info * @param _round - block height * @param _tableId - the table index * @return bool - false if not arranged yet * @return uint256 - the amount in jackpot * @return uint256 - how many winners * @return uint256 - prize amount */ function getjackpotInfo(uint256 _round, uint256 _tableId) external view tableExists(_tableId) returns ( bool status, uint256 potAmount, uint256 winners, uint256 prize ) { Jackpot storage j = jackpotInfo[_round][_tableId]; return (j.arranged, j.pot, j.winners.length, j.award); } /** * @notice returns jackpot players * @param _round - block height * @param _tableId - the table index * @return address[] - addresses of joiners */ function getjackpotJoiners(uint256 _round, uint256 _tableId) external view tableExists(_tableId) returns (address[] joiners) { Jackpot storage j = jackpotInfo[_round][_tableId]; return (j.jPlayers); } /** * @notice returns jackpot wiiners if table already arranged * @param _round - block height * @param _tableId - the table index * @return address[] - addresses of winners */ function showJackpotWinners(uint256 _round, uint256 _tableId) external view tableExists(_tableId) returns (address[] winners) { Jackpot storage j = jackpotInfo[_round][_tableId]; require(j.arranged); return (j.winners); } /** * @notice returns jackpot bet ids * @param _round - block height * @param _tableId - the table index * @return uint256[] - array of bet ids */ function getjackpotBets(uint256 _round, uint256 _tableId) external view tableExists(_tableId) returns (uint256[] betIds) { Jackpot storage j = jackpotInfo[_round][_tableId]; return (j.betId); } /** * @notice returns all betIds for unclaimed wins for a player * @param _player - player's address * @return uint256[] - returns the array for betIds that haven't been claimed yet */ function getUnclaimedWinnings(address _player) external view isPlayer(_player) returns (uint256[]) { Player memory pl = playerInfo[_player]; uint256[] memory unclaimedBets = new uint256[](pl.betIds.length); Betting memory bet; uint256 index; for (uint256 i = 0; i < pl.betIds.length; i++) { bet = betInfo[pl.betIds[i]]; if (bet.claimed) { continue; } else { unclaimedBets[index] = pl.betIds[i]; index = index.add(1); } } uint256[] memory unclaimedBetIds = new uint256[](index); unclaimedBetIds = unclaimedBets; return unclaimedBetIds; } /** * @notice returns all betIds for a player * @param _player - player's address * @return uint256[] - returns the array for betIds that haven't been claimed yet */ function getBettingHistory(address _player) external view isPlayer(_player) returns (uint256[] betIds) { Player memory pl = playerInfo[_player]; betIds = pl.betIds; return betIds; } /** * @notice returns round info * @param _round - block height * @return uint256 - saved blockhash * @return bool - true if needs fix */ function getRoundInfo(uint256 _round) external view returns (uint256 hash, bool requireFix) { Round storage r = roundInfo[_round]; require(_round <= block.number); require(_round.mod(session) == 0); return (r.result, r.requireFix); } /** * @notice give winnings for a bet to the player - can be triggered only by player * @param _betId - the bet id * @return uint256 - returns the winning amount */ function claimWinnings(uint256 _betId) external returns (uint256 amount) { Betting storage bet = betInfo[_betId]; require(!bet.claimed); require(bet.player == msg.sender); require(bet.round < block.number); Table storage tbl = tableInfo[bet.round][bet.tableIndex]; /* extra check, if betid exists on table */ require(_numberExists(tbl.betId, bet.id)); /* compute the winning amount */ uint16 mask; for (uint256 w = 0; w < 3; w++) { mask = uint16(2)**tbl.winningNumbers[w]; if (bet.boxChoice & mask != 0) { amount = amount.add(tbl.boxPrice); /* capital */ amount = amount.add(tbl.winningAmount[w]); } } bet.claimed = true; Player storage pl = playerInfo[msg.sender]; tbl.pot = tbl.pot.sub(amount); pl.credits = pl.credits.add(amount); emit ClaimReward(bet.player, bet.round, bet.tableIndex, amount); return amount; } /** * @notice gives jackpot prize to player - can be triggered only by player * @param _round - block height * @param _tableId - the table index * @return uint256 - returns the jackpot prize */ function claimJackpotPrize(uint256 _round, uint256 _tableId) external tableExists(_tableId) isPlayer(msg.sender) returns (uint256 prize) { Jackpot storage j = jackpotInfo[_round][_tableId]; require(j.arranged); /* find the bet id */ Player storage pl = playerInfo[msg.sender]; for (uint256 i = pl.betIds.length; i != 0; --i) { Betting storage nBet = betInfo[pl.betIds[i - 1]]; if ((nBet.round == _round) && (nBet.tableIndex == _tableId)) { uint256 betId = nBet.id; break; } else { continue; } /* if no normal bettor, revert */ revert(); } require(nBet.player == msg.sender); require(nBet.round < block.number); /* reduntant */ /* check if player hits the jackpot */ for (i = 0; i < j.betId.length; i++) { if (j.betId[i] == betId) { /* ok, player has joinned jackpot and also never got his prize */ uint256 jBetIndex = i; break; } else { continue; } /* no jackpot joiner*/ revert(); } /* if no winner, revert */ require(_addressExists(j.winners, msg.sender)); /* transfer credits from pot to player */ j.pot = j.pot.sub(j.award); pl.credits = pl.credits.add(j.award); /* remove bet id from jackpot table to mark prize as claimed */ j.betId[jBetIndex] = 0; /* emit event */ emit ClaimJackpotPrize(msg.sender, _round, _tableId, j.award); return j.award; } /** * @notice returns how many keys and how many more boxes are needed for next key * @param _player - player's address * @param _tableId - table index * @return uint256 - number of unused keys * @return uint256 - how many boxes to bet to get the next key */ function getJackpotKeysInfo(address _player, uint256 _tableId) external view isPlayer(_player) tableExists(_tableId) returns (uint256 keys, uint256 creditsLeftForNextKey) { Player storage pl = playerInfo[_player]; keys = pl.jackpotCredits[_tableId].div(jackpotKeyCost); creditsLeftForNextKey = jackpotKeyCost.sub( pl.jackpotCredits[_tableId].mod(jackpotKeyCost) ); if (creditsLeftForNextKey == 0) { creditsLeftForNextKey = jackpotKeyCost; } return (keys, creditsLeftForNextKey); } /** * @notice search adddress in array * @param _array - array to be searched * @param _value - the element * @return bool - returns true if exists, else false */ function _addressExists(address[] _array, address _value) internal pure returns (bool) { for (uint256 i = 0; i < _array.length; i++) { if (_array[i] == _value) { return true; } } return false; } /** * @notice search integer in array * @param _array - array to be searched * @param _value - the element * @return bool - returns true if exists, else false */ function _numberExists(uint256[] _array, uint256 _value) internal pure returns (bool) { for (uint256 i = 0; i < _array.length; i++) { if (_array[i] == _value) { return true; } } return false; } }
checks if the jackpot is arranged (updated) or not callable by anyone _round the block height of jackpot round _tableId the table index return bool - true if arranged/
function isJTableArranged(uint256 _round, uint256 _tableId) external view returns (bool arranged) { Jackpot storage j = jackpotInfo[_round][_tableId]; return j.arranged; }
1,060,677